diff --git a/Alignment/CommonAlignment/python/tools/trackselectionRefitting.py b/Alignment/CommonAlignment/python/tools/trackselectionRefitting.py index b8c7d65f08d68..8391e9156adf0 100644 --- a/Alignment/CommonAlignment/python/tools/trackselectionRefitting.py +++ b/Alignment/CommonAlignment/python/tools/trackselectionRefitting.py @@ -130,6 +130,7 @@ def getSequence(process, collection, "minimumHits": 10, }) elif collection in ("ALCARECOTkAlCosmicsCTF0T", + "ALCARECOTkAlCosmicsCosmicTF0T", "ALCARECOTkAlCosmicsInCollisions"): isCosmics = True options["TrackSelector"]["HighPurity"] = {} # drop high purity cut @@ -336,7 +337,7 @@ def getSequence(process, collection, **(mod[2])), src modules.append(getattr(process, src)) else: - if mods[-1][-1]["method"] is "load" and \ + if mods[-1][-1]["method"] == "load" and \ not mods[-1][-1].get("clone", False): print("Name of the last module needs to be modifiable.") sys.exit(1) diff --git a/Alignment/CommonAlignmentAlgorithm/interface/IntegratedCalibrationPluginFactory.h b/Alignment/CommonAlignmentAlgorithm/interface/IntegratedCalibrationPluginFactory.h index a1b34c9fc732c..2d8ac29879405 100644 --- a/Alignment/CommonAlignmentAlgorithm/interface/IntegratedCalibrationPluginFactory.h +++ b/Alignment/CommonAlignmentAlgorithm/interface/IntegratedCalibrationPluginFactory.h @@ -13,7 +13,7 @@ #include "FWCore/PluginManager/interface/PluginFactory.h" #include "Alignment/CommonAlignmentAlgorithm/interface/IntegratedCalibrationBase.h" -typedef edmplugin::PluginFactory +typedef edmplugin::PluginFactory IntegratedCalibrationPluginFactory; #endif diff --git a/Alignment/CommonAlignmentAlgorithm/plugins/SiPixelLorentzAngleCalibration.cc b/Alignment/CommonAlignmentAlgorithm/plugins/SiPixelLorentzAngleCalibration.cc index 2b42e4ef29db2..aa30f3e2ac925 100644 --- a/Alignment/CommonAlignmentAlgorithm/plugins/SiPixelLorentzAngleCalibration.cc +++ b/Alignment/CommonAlignmentAlgorithm/plugins/SiPixelLorentzAngleCalibration.cc @@ -23,7 +23,6 @@ #include "DataFormats/DetId/interface/DetId.h" #include "DataFormats/SiPixelDetId/interface/PixelSubdetector.h" -#include "FWCore/Framework/interface/ESHandle.h" #include "FWCore/Framework/interface/ESWatcher.h" #include "FWCore/Framework/interface/Run.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" @@ -37,6 +36,7 @@ #include "MagneticField/Engine/interface/MagneticField.h" #include "MagneticField/Records/interface/IdealMagneticFieldRecord.h" #include "TrackingTools/TransientTrackingRecHit/interface/TransientTrackingRecHit.h" +#include "FWCore/Framework/interface/ConsumesCollector.h" #include "TTree.h" #include "TFile.h" @@ -54,7 +54,7 @@ class SiPixelLorentzAngleCalibration : public IntegratedCalibrationBase { public: /// Constructor - explicit SiPixelLorentzAngleCalibration(const edm::ParameterSet &cfg); + explicit SiPixelLorentzAngleCalibration(const edm::ParameterSet &cfg, edm::ConsumesCollector &iC); /// Destructor ~SiPixelLorentzAngleCalibration() override = default; @@ -116,7 +116,8 @@ class SiPixelLorentzAngleCalibration : public IntegratedCalibrationBase { const std::string outFileName_; const std::vector mergeFileNames_; const std::string lorentzAngleLabel_; - + const edm::ESGetToken lorentzAngleToken_; + const edm::ESGetToken magFieldToken_; edm::ESWatcher watchLorentzAngleRcd_; // const AlignableTracker *alignableTracker_; @@ -134,13 +135,15 @@ class SiPixelLorentzAngleCalibration : public IntegratedCalibrationBase { //====================================================================== //====================================================================== -SiPixelLorentzAngleCalibration::SiPixelLorentzAngleCalibration(const edm::ParameterSet &cfg) +SiPixelLorentzAngleCalibration::SiPixelLorentzAngleCalibration(const edm::ParameterSet &cfg, edm::ConsumesCollector &iC) : IntegratedCalibrationBase(cfg), saveToDB_(cfg.getParameter("saveToDB")), recordNameDBwrite_(cfg.getParameter("recordNameDBwrite")), outFileName_(cfg.getParameter("treeFile")), mergeFileNames_(cfg.getParameter >("mergeTreeFiles")), lorentzAngleLabel_(cfg.getParameter("lorentzAngleLabel")), + lorentzAngleToken_(iC.esConsumes(edm::ESInputTag("", lorentzAngleLabel_))), + magFieldToken_(iC.esConsumes()), moduleGroupSelCfg_(cfg.getParameter("LorentzAngleModuleGroups")) {} //====================================================================== @@ -165,9 +168,9 @@ void SiPixelLorentzAngleCalibration::beginRun(const edm::Run &run, const edm::Ev } } - edm::ESHandle lorentzAngleHandle; + const SiPixelLorentzAngle *lorentzAngleHandle = &setup.getData(lorentzAngleToken_); const auto &lorentzAngleRcd = setup.get(); - lorentzAngleRcd.get(lorentzAngleLabel_, lorentzAngleHandle); + if (cachedLorentzAngleInputs_.find(firstRun) == cachedLorentzAngleInputs_.end()) { cachedLorentzAngleInputs_.emplace(firstRun, SiPixelLorentzAngle(*lorentzAngleHandle)); } else { @@ -202,8 +205,8 @@ unsigned int SiPixelLorentzAngleCalibration::derivatives(std::vectorgetParameterIndexFromDetId(hit.det()->geographicalId(), eventInfo.eventId().run()); if (index >= 0) { // otherwise not treated - edm::ESHandle magneticField; - setup.get().get(magneticField); + + const MagneticField *magneticField = &setup.getData(magFieldToken_); const GlobalVector bField(magneticField->inTesla(hit.det()->surface().position())); const LocalVector bFieldLocal(hit.det()->surface().toLocal(bField)); const double dZ = hit.det()->surface().bounds().thickness(); // it is a float only... @@ -337,7 +340,7 @@ void SiPixelLorentzAngleCalibration::endOfJob() { if (saveToDB_) { // If requested, write out to DB edm::Service dbService; if (dbService.isAvailable()) { - dbService->writeOne(&output, firstRunOfIOV, recordNameDBwrite_); + dbService->writeOneIOV(output, firstRunOfIOV, recordNameDBwrite_); } else { edm::LogError("BadConfig") << "@SUB=SiPixelLorentzAngleCalibration::endOfJob" << "No PoolDBOutputService available, but saveToDB true!"; diff --git a/Alignment/CommonAlignmentAlgorithm/plugins/SiStripBackplaneCalibration.cc b/Alignment/CommonAlignmentAlgorithm/plugins/SiStripBackplaneCalibration.cc index 795f70f9912d0..b3da1338201bd 100644 --- a/Alignment/CommonAlignmentAlgorithm/plugins/SiStripBackplaneCalibration.cc +++ b/Alignment/CommonAlignmentAlgorithm/plugins/SiStripBackplaneCalibration.cc @@ -29,7 +29,6 @@ #include "DataFormats/DetId/interface/DetId.h" #include "DataFormats/SiStripDetId/interface/SiStripDetId.h" -#include "FWCore/Framework/interface/ESHandle.h" #include "FWCore/Framework/interface/ESWatcher.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "FWCore/ServiceRegistry/interface/Service.h" @@ -39,6 +38,7 @@ #include "MagneticField/Engine/interface/MagneticField.h" #include "MagneticField/Records/interface/IdealMagneticFieldRecord.h" #include "TrackingTools/TransientTrackingRecHit/interface/TransientTrackingRecHit.h" +#include "FWCore/Framework/interface/ConsumesCollector.h" #include "TTree.h" #include "TFile.h" @@ -54,7 +54,7 @@ class SiStripBackplaneCalibration : public IntegratedCalibrationBase { public: /// Constructor - explicit SiStripBackplaneCalibration(const edm::ParameterSet &cfg); + explicit SiStripBackplaneCalibration(const edm::ParameterSet &cfg, edm::ConsumesCollector &iC); /// Destructor ~SiStripBackplaneCalibration() override; @@ -135,13 +135,17 @@ class SiStripBackplaneCalibration : public IntegratedCalibrationBase { TkModuleGroupSelector *moduleGroupSelector_; const edm::ParameterSet moduleGroupSelCfg_; + const edm::ESGetToken latencyToken_; + const edm::ESGetToken lorentzAngleToken_; + const edm::ESGetToken magFieldToken_; + const edm::ESGetToken backPlaneCorrToken_; }; //====================================================================== //====================================================================== //====================================================================== -SiStripBackplaneCalibration::SiStripBackplaneCalibration(const edm::ParameterSet &cfg) +SiStripBackplaneCalibration::SiStripBackplaneCalibration(const edm::ParameterSet &cfg, edm::ConsumesCollector &iC) : IntegratedCalibrationBase(cfg), readoutModeName_(cfg.getParameter("readoutMode")), saveToDB_(cfg.getParameter("saveToDB")), @@ -150,7 +154,11 @@ SiStripBackplaneCalibration::SiStripBackplaneCalibration(const edm::ParameterSet mergeFileNames_(cfg.getParameter >("mergeTreeFiles")), siStripBackPlaneCorrInput_(nullptr), moduleGroupSelector_(nullptr), - moduleGroupSelCfg_(cfg.getParameter("BackplaneModuleGroups")) { + moduleGroupSelCfg_(cfg.getParameter("BackplaneModuleGroups")), + latencyToken_(iC.esConsumes()), + lorentzAngleToken_(iC.esConsumes(edm::ESInputTag("", readoutModeName_))), + magFieldToken_(iC.esConsumes()), + backPlaneCorrToken_(iC.esConsumes(edm::ESInputTag("", readoutModeName_))) { // SiStripLatency::singleReadOutMode() returns // 1: all in peak, 0: all in deco, -1: mixed state // (in principle one could treat even mixed state APV by APV...) @@ -187,8 +195,7 @@ unsigned int SiStripBackplaneCalibration::derivatives(std::vector latency; - setup.get().get(latency); + const SiStripLatency *latency = &setup.getData(latencyToken_); const int16_t mode = latency->singleReadOutMode(); if (mode == readoutMode_) { @@ -197,16 +204,14 @@ unsigned int SiStripBackplaneCalibration::derivatives(std::vectorgetParameterIndexFromDetId(hit.det()->geographicalId(), eventInfo.eventId().run()); if (index >= 0) { // otherwise not treated - edm::ESHandle magneticField; - setup.get().get(magneticField); + const MagneticField *magneticField = &setup.getData(magFieldToken_); const GlobalVector bField(magneticField->inTesla(hit.det()->surface().position())); const LocalVector bFieldLocal(hit.det()->surface().toLocal(bField)); //std::cout << "SiStripBackplaneCalibration derivatives " << readoutModeName_ << std::endl; const double dZ = hit.det()->surface().bounds().thickness(); // it's a float only... const double tanPsi = tsos.localParameters().mixedFormatVector()[1]; //float... - edm::ESHandle lorentzAngleHandle; - setup.get().get(readoutModeName_, lorentzAngleHandle); + const SiStripLorentzAngle *lorentzAngleHandle = &setup.getData(lorentzAngleToken_); // Yes, mobility (= LA/By) stored in object called LA... const double mobility = lorentzAngleHandle->getLorentzAngle(hit.det()->geographicalId()); // shift due to dead back plane has two parts: @@ -393,16 +398,17 @@ void SiStripBackplaneCalibration::endOfJob() { //====================================================================== bool SiStripBackplaneCalibration::checkBackPlaneCorrectionInput(const edm::EventSetup &setup, const EventInfo &eventInfo) { - edm::ESHandle backPlaneCorrHandle; + const SiStripBackPlaneCorrection *backPlaneCorrHandle = nullptr; if (!siStripBackPlaneCorrInput_) { - setup.get().get(readoutModeName_, backPlaneCorrHandle); + backPlaneCorrHandle = &setup.getData(backPlaneCorrToken_); siStripBackPlaneCorrInput_ = new SiStripBackPlaneCorrection(*backPlaneCorrHandle); // FIXME: Should we call 'watchBackPlaneCorrRcd_.check(setup)' as well? // Otherwise could be that next check has to check via following 'else', though // no new IOV has started... (to be checked) } else { if (watchBackPlaneCorrRcd_.check(setup)) { // new IOV of input - but how to check peak vs deco? - setup.get().get(readoutModeName_, backPlaneCorrHandle); + backPlaneCorrHandle = &setup.getData(backPlaneCorrToken_); + if (backPlaneCorrHandle->getBackPlaneCorrections() // but only bad if non-identical values != siStripBackPlaneCorrInput_->getBackPlaneCorrections()) { // (comparing maps) // Maps are containers sorted by key, but comparison problems may arise from diff --git a/Alignment/CommonAlignmentAlgorithm/plugins/SiStripLorentzAngleCalibration.cc b/Alignment/CommonAlignmentAlgorithm/plugins/SiStripLorentzAngleCalibration.cc index b910f6f965f0e..787e8982c8941 100644 --- a/Alignment/CommonAlignmentAlgorithm/plugins/SiStripLorentzAngleCalibration.cc +++ b/Alignment/CommonAlignmentAlgorithm/plugins/SiStripLorentzAngleCalibration.cc @@ -27,7 +27,7 @@ #include "DataFormats/DetId/interface/DetId.h" #include "DataFormats/SiStripDetId/interface/SiStripDetId.h" -#include "FWCore/Framework/interface/ESHandle.h" +#include "FWCore/Framework/interface/ConsumesCollector.h" #include "FWCore/Framework/interface/ESWatcher.h" #include "FWCore/Framework/interface/Run.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" @@ -53,7 +53,7 @@ class SiStripLorentzAngleCalibration : public IntegratedCalibrationBase { public: /// Constructor - explicit SiStripLorentzAngleCalibration(const edm::ParameterSet &cfg); + explicit SiStripLorentzAngleCalibration(const edm::ParameterSet &cfg, edm::ConsumesCollector &iC); /// Destructor ~SiStripLorentzAngleCalibration() override = default; @@ -130,20 +130,29 @@ class SiStripLorentzAngleCalibration : public IntegratedCalibrationBase { std::unique_ptr moduleGroupSelector_; const edm::ParameterSet moduleGroupSelCfg_; + + const edm::ESGetToken latencyToken_; + const edm::ESGetToken lorentzAngleToken_; + const edm::ESGetToken magFieldToken_; + const edm::ESGetToken backPlaneCorrToken_; }; //====================================================================== //====================================================================== //====================================================================== -SiStripLorentzAngleCalibration::SiStripLorentzAngleCalibration(const edm::ParameterSet &cfg) +SiStripLorentzAngleCalibration::SiStripLorentzAngleCalibration(const edm::ParameterSet &cfg, edm::ConsumesCollector &iC) : IntegratedCalibrationBase(cfg), readoutModeName_(cfg.getParameter("readoutMode")), saveToDB_(cfg.getParameter("saveToDB")), recordNameDBwrite_(cfg.getParameter("recordNameDBwrite")), outFileName_(cfg.getParameter("treeFile")), mergeFileNames_(cfg.getParameter >("mergeTreeFiles")), - moduleGroupSelCfg_(cfg.getParameter("LorentzAngleModuleGroups")) { + moduleGroupSelCfg_(cfg.getParameter("LorentzAngleModuleGroups")), + latencyToken_(iC.esConsumes()), + lorentzAngleToken_(iC.esConsumes(edm::ESInputTag("", readoutModeName_))), + magFieldToken_(iC.esConsumes()), + backPlaneCorrToken_(iC.esConsumes(edm::ESInputTag("", readoutModeName_))) { // SiStripLatency::singleReadOutMode() returns // 1: all in peak, 0: all in deco, -1: mixed state // (in principle one could treat even mixed state APV by APV...) @@ -180,9 +189,8 @@ void SiStripLorentzAngleCalibration::beginRun(const edm::Run &run, const edm::Ev } } - edm::ESHandle lorentzAngleHandle; + const SiStripLorentzAngle *lorentzAngleHandle = &setup.getData(lorentzAngleToken_); const auto &lorentzAngleRcd = setup.get(); - lorentzAngleRcd.get(readoutModeName_, lorentzAngleHandle); if (cachedLorentzAngleInputs_.find(firstRun) == cachedLorentzAngleInputs_.end()) { cachedLorentzAngleInputs_.emplace(firstRun, SiStripLorentzAngle(*lorentzAngleHandle)); } else { @@ -212,8 +220,7 @@ unsigned int SiStripLorentzAngleCalibration::derivatives(std::vector latency; - setup.get().get(latency); + const SiStripLatency *latency = &setup.getData(latencyToken_); const int16_t mode = latency->singleReadOutMode(); if (mode == readoutMode_) { if (hit.det()) { // otherwise 'constraint hit' or whatever @@ -221,8 +228,7 @@ unsigned int SiStripLorentzAngleCalibration::derivatives(std::vectorgetParameterIndexFromDetId(hit.det()->geographicalId(), eventInfo.eventId().run()); if (index >= 0) { // otherwise not treated - edm::ESHandle magneticField; - setup.get().get(magneticField); + const MagneticField *magneticField = &setup.getData(magFieldToken_); const GlobalVector bField(magneticField->inTesla(hit.det()->surface().position())); const LocalVector bFieldLocal(hit.det()->surface().toLocal(bField)); const double dZ = this->effectiveThickness(hit.det(), mode, setup); @@ -377,7 +383,7 @@ void SiStripLorentzAngleCalibration::endOfJob() { if (saveToDB_) { // If requested, write out to DB edm::Service dbService; if (dbService.isAvailable()) { - dbService->writeOne(&output, firstRunOfIOV, recordNameDBwrite_); + dbService->writeOneIOV(output, firstRunOfIOV, recordNameDBwrite_); } else { edm::LogError("BadConfig") << "@SUB=SiStripLorentzAngleCalibration::endOfJob" << "No PoolDBOutputService available, but saveToDB true!"; @@ -394,10 +400,9 @@ double SiStripLorentzAngleCalibration::effectiveThickness(const GeomDet *det, return 0.; double dZ = det->surface().bounds().thickness(); // it is a float only... const SiStripDetId id(det->geographicalId()); - edm::ESHandle backPlaneHandle; + const SiStripBackPlaneCorrection *backPlaneHandle = &setup.getData(backPlaneCorrToken_); // FIXME: which one? DepRcd->get(handle) or Rcd->get(readoutModeName_, handle)?? // setup.get().get(backPlaneHandle); // get correct mode - setup.get().get(readoutModeName_, backPlaneHandle); const double bpCor = backPlaneHandle->getBackPlaneCorrection(id); // it's a float... // std::cout << "bpCor " << bpCor << " in subdet " << id.subdetId() << std::endl; dZ *= (1. - bpCor); diff --git a/Alignment/CommonAlignmentMonitor/plugins/AlignmentMonitorMuonSystemMap1D.cc b/Alignment/CommonAlignmentMonitor/plugins/AlignmentMonitorMuonSystemMap1D.cc index 644c76b724fc4..76996cb3d005b 100644 --- a/Alignment/CommonAlignmentMonitor/plugins/AlignmentMonitorMuonSystemMap1D.cc +++ b/Alignment/CommonAlignmentMonitor/plugins/AlignmentMonitorMuonSystemMap1D.cc @@ -51,6 +51,7 @@ class AlignmentMonitorMuonSystemMap1D : public AlignmentMonitorBase { const edm::ESGetToken m_esTokenDetId; const edm::ESGetToken m_esTokenProp; const edm::ESGetToken m_esTokenMF; + const MuonResidualsFromTrack::BuilderToken m_esTokenBuilder; // parameters edm::InputTag m_muonCollectionTag; @@ -155,6 +156,7 @@ AlignmentMonitorMuonSystemMap1D::AlignmentMonitorMuonSystemMap1D(const edm::Para m_esTokenDetId(iC.esConsumes(edm::ESInputTag("", "MuonDetIdAssociator"))), m_esTokenProp(iC.esConsumes(edm::ESInputTag("", "SteppingHelixPropagatorAny"))), m_esTokenMF(iC.esConsumes()), + m_esTokenBuilder(iC.esConsumes(MuonResidualsFromTrack::builderESInputTag())), m_muonCollectionTag(cfg.getParameter("muonCollectionTag")), m_minTrackPt(cfg.getParameter("minTrackPt")), m_maxTrackPt(cfg.getParameter("maxTrackPt")), @@ -271,6 +273,7 @@ void AlignmentMonitorMuonSystemMap1D::event(const edm::Event &iEvent, const DetIdAssociator *muonDetIdAssociator_ = &iSetup.getData(m_esTokenDetId); const Propagator *prop = &iSetup.getData(m_esTokenProp); const MagneticField *magneticField = &iSetup.getData(m_esTokenMF); + auto builder = iSetup.getHandle(m_esTokenBuilder); if (m_muonCollectionTag.label().empty()) // use trajectories { @@ -287,7 +290,7 @@ void AlignmentMonitorMuonSystemMap1D::event(const edm::Event &iEvent, m_counter_trackdxy++; MuonResidualsFromTrack muonResidualsFromTrack( - iSetup, magneticField, globalGeometry, muonDetIdAssociator_, prop, traj, track, pNavigator(), 1000.); + builder, magneticField, globalGeometry, muonDetIdAssociator_, prop, traj, track, pNavigator(), 1000.); processMuonResidualsFromTrack(muonResidualsFromTrack, iEvent); } } // end if track has acceptable momentum diff --git a/Alignment/CommonAlignmentMonitor/plugins/AlignmentMonitorMuonVsCurvature.cc b/Alignment/CommonAlignmentMonitor/plugins/AlignmentMonitorMuonVsCurvature.cc index 33b6b1f12afa4..c674bc5e7639f 100644 --- a/Alignment/CommonAlignmentMonitor/plugins/AlignmentMonitorMuonVsCurvature.cc +++ b/Alignment/CommonAlignmentMonitor/plugins/AlignmentMonitorMuonVsCurvature.cc @@ -49,6 +49,7 @@ class AlignmentMonitorMuonVsCurvature : public AlignmentMonitorBase { const edm::ESGetToken m_esTokenDetId; const edm::ESGetToken m_esTokenProp; const edm::ESGetToken m_esTokenMF; + const MuonResidualsFromTrack::BuilderToken m_esTokenBuilder; // parameters edm::InputTag m_muonCollectionTag; @@ -88,6 +89,7 @@ AlignmentMonitorMuonVsCurvature::AlignmentMonitorMuonVsCurvature(const edm::Para m_esTokenDetId(iC.esConsumes(edm::ESInputTag("", "MuonDetIdAssociator"))), m_esTokenProp(iC.esConsumes(edm::ESInputTag("", "SteppingHelixPropagatorAny"))), m_esTokenMF(iC.esConsumes()), + m_esTokenBuilder(iC.esConsumes(MuonResidualsFromTrack::builderESInputTag())), m_muonCollectionTag(cfg.getParameter("muonCollectionTag")), m_minTrackPt(cfg.getParameter("minTrackPt")), m_minTrackP(cfg.getParameter("minTrackP")), @@ -201,6 +203,7 @@ void AlignmentMonitorMuonVsCurvature::event(const edm::Event &iEvent, const DetIdAssociator *muonDetIdAssociator_ = &iSetup.getData(m_esTokenDetId); const Propagator *prop = &iSetup.getData(m_esTokenProp); const MagneticField *magneticField = &iSetup.getData(m_esTokenMF); + auto builder = iSetup.getHandle(m_esTokenBuilder); if (m_muonCollectionTag.label().empty()) // use trajectories { @@ -211,7 +214,7 @@ void AlignmentMonitorMuonVsCurvature::event(const edm::Event &iEvent, if (track->pt() > m_minTrackPt && track->p() > m_minTrackP && fabs(track->dxy(beamSpot->position())) < m_maxDxy) { MuonResidualsFromTrack muonResidualsFromTrack( - iSetup, magneticField, globalGeometry, muonDetIdAssociator_, prop, traj, track, pNavigator(), 1000.); + builder, magneticField, globalGeometry, muonDetIdAssociator_, prop, traj, track, pNavigator(), 1000.); processMuonResidualsFromTrack(muonResidualsFromTrack, traj); } // end if track pT is within range } // end loop over tracks diff --git a/Alignment/CommonAlignmentMonitor/plugins/AlignmentMonitorSegmentDifferences.cc b/Alignment/CommonAlignmentMonitor/plugins/AlignmentMonitorSegmentDifferences.cc index 185bf2bc5b79e..55234490d0000 100644 --- a/Alignment/CommonAlignmentMonitor/plugins/AlignmentMonitorSegmentDifferences.cc +++ b/Alignment/CommonAlignmentMonitor/plugins/AlignmentMonitorSegmentDifferences.cc @@ -49,6 +49,7 @@ class AlignmentMonitorSegmentDifferences : public AlignmentMonitorBase { const edm::ESGetToken m_esTokenDetId; const edm::ESGetToken m_esTokenProp; const edm::ESGetToken m_esTokenMF; + const MuonResidualsFromTrack::BuilderToken m_esTokenBuilder; // parameters edm::InputTag m_muonCollectionTag; @@ -121,6 +122,7 @@ AlignmentMonitorSegmentDifferences::AlignmentMonitorSegmentDifferences(const edm m_esTokenDetId(iC.esConsumes(edm::ESInputTag("", "MuonDetIdAssociator"))), m_esTokenProp(iC.esConsumes(edm::ESInputTag("", "SteppingHelixPropagatorAny"))), m_esTokenMF(iC.esConsumes()), + m_esTokenBuilder(iC.esConsumes(MuonResidualsFromTrack::builderESInputTag())), m_muonCollectionTag(cfg.getParameter("muonCollectionTag")), m_minTrackPt(cfg.getParameter("minTrackPt")), m_minTrackP(cfg.getParameter("minTrackP")), @@ -376,6 +378,7 @@ void AlignmentMonitorSegmentDifferences::event(const edm::Event &iEvent, const DetIdAssociator *muonDetIdAssociator_ = &iSetup.getData(m_esTokenDetId); const Propagator *prop = &iSetup.getData(m_esTokenProp); const MagneticField *magneticField = &iSetup.getData(m_esTokenMF); + auto builder = iSetup.getHandle(m_esTokenBuilder); if (m_muonCollectionTag.label().empty()) // use trajectories { @@ -386,7 +389,7 @@ void AlignmentMonitorSegmentDifferences::event(const edm::Event &iEvent, if (track->pt() > m_minTrackPt && track->p() > m_minTrackP && fabs(track->dxy(beamSpot->position())) < m_maxDxy) { MuonResidualsFromTrack muonResidualsFromTrack( - iSetup, magneticField, globalGeometry, muonDetIdAssociator_, prop, traj, track, pNavigator(), 1000.); + builder, magneticField, globalGeometry, muonDetIdAssociator_, prop, traj, track, pNavigator(), 1000.); processMuonResidualsFromTrack(muonResidualsFromTrack); } } // end loop over tracks diff --git a/Alignment/CommonAlignmentMonitor/plugins/TrackerToMuonPropagator.cc b/Alignment/CommonAlignmentMonitor/plugins/TrackerToMuonPropagator.cc index c2dcd5a0ce7a6..0100ad24a85a7 100644 --- a/Alignment/CommonAlignmentMonitor/plugins/TrackerToMuonPropagator.cc +++ b/Alignment/CommonAlignmentMonitor/plugins/TrackerToMuonPropagator.cc @@ -26,6 +26,7 @@ #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/EventSetup.h" #include "FWCore/Framework/interface/MakerMacros.h" +#include "FWCore/Framework/interface/ConsumesCollector.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" // products @@ -105,7 +106,8 @@ TrackerToMuonPropagator::TrackerToMuonPropagator(const edm::ParameterSet& iConfi m_globalMuonTracks = iConfig.getParameter("globalMuonTracks"); m_refitTracker = iConfig.getParameter("refitTrackerTrack"); if (m_refitTracker) { - m_trackTransformer = new TrackTransformer(iConfig.getParameter("trackerTrackTransformer")); + m_trackTransformer = + new TrackTransformer(iConfig.getParameter("trackerTrackTransformer"), consumesCollector()); } else m_trackTransformer = nullptr; diff --git a/Alignment/CommonAlignmentProducer/interface/AlignmentProducerBase.h b/Alignment/CommonAlignmentProducer/interface/AlignmentProducerBase.h index 60816aea033d6..1d9783b1cfe81 100644 --- a/Alignment/CommonAlignmentProducer/interface/AlignmentProducerBase.h +++ b/Alignment/CommonAlignmentProducer/interface/AlignmentProducerBase.h @@ -143,7 +143,7 @@ class AlignmentProducerBase { void createMonitors(edm::ConsumesCollector&); /// Creates the calibrations - void createCalibrations(); + void createCalibrations(edm::ConsumesCollector&); /// Checks if one of the EventSetup-Records has changed bool setupChanged(const edm::EventSetup&); diff --git a/Alignment/CommonAlignmentProducer/src/AlignmentProducerBase.cc b/Alignment/CommonAlignmentProducer/src/AlignmentProducerBase.cc index 1a8681b8ff496..efc0861f0c36d 100644 --- a/Alignment/CommonAlignmentProducer/src/AlignmentProducerBase.cc +++ b/Alignment/CommonAlignmentProducer/src/AlignmentProducerBase.cc @@ -93,7 +93,7 @@ AlignmentProducerBase::AlignmentProducerBase(const edm::ParameterSet& config, ed createAlignmentAlgorithm(iC); createMonitors(iC); - createCalibrations(); + createCalibrations(iC); } //------------------------------------------------------------------------------ @@ -297,11 +297,11 @@ void AlignmentProducerBase::createMonitors(edm::ConsumesCollector& iC) { } //------------------------------------------------------------------------------ -void AlignmentProducerBase::createCalibrations() { +void AlignmentProducerBase::createCalibrations(edm::ConsumesCollector& iC) { const auto& calibrations = config_.getParameter("calibrations"); for (const auto& iCalib : calibrations) { - calibrations_.emplace_back( - IntegratedCalibrationPluginFactory::get()->create(iCalib.getParameter("calibrationName"), iCalib)); + calibrations_.emplace_back(IntegratedCalibrationPluginFactory::get()->create( + iCalib.getParameter("calibrationName"), iCalib, iC)); } } diff --git a/Alignment/LaserAlignmentSimulation/src/LaserOpticalPhysicsList.cc b/Alignment/LaserAlignmentSimulation/src/LaserOpticalPhysicsList.cc index ffb9f2a5e5576..d84a8ba8f0609 100644 --- a/Alignment/LaserAlignmentSimulation/src/LaserOpticalPhysicsList.cc +++ b/Alignment/LaserAlignmentSimulation/src/LaserOpticalPhysicsList.cc @@ -56,14 +56,14 @@ LaserOpticalPhysicsList::~LaserOpticalPhysicsList() { delete theScintProcess; } if (verboseLevel > 0) - std::cout << " done " << std::endl; + G4cout << " done " << G4endl; } void LaserOpticalPhysicsList::ConstructParticle() { if (verboseLevel > 0) - std::cout << ": constructing " - "the optical photon ... " - << std::endl; + G4cout << ": constructing " + "the optical photon ... " + << G4endl; // optical photon G4OpticalPhoton::OpticalPhotonDefinition(); @@ -71,12 +71,11 @@ void LaserOpticalPhysicsList::ConstructParticle() { void LaserOpticalPhysicsList::ConstructProcess() { if (verboseLevel > 0) - std::cout << ": constructing " - "the physics ... " - << std::endl; + G4cout << ": constructing " + "the physics ... " + << G4endl; theScintProcess = new G4Scintillation(); - // theCerenkovProcess=new G4Cerenkov(); theAbsorptionProcess = new G4OpAbsorption(); theRayleighScattering = new G4OpRayleigh(); theBoundaryProcess = new G4OpBoundaryProcess("OpBoundary"); @@ -91,12 +90,10 @@ void LaserOpticalPhysicsList::ConstructProcess() { pManager = G4OpticalPhoton::OpticalPhoton()->GetProcessManager(); pManager->AddDiscreteProcess(theAbsorptionProcess); pManager->AddDiscreteProcess(theRayleighScattering); - // theBoundaryProcess->SetModel(unified); pManager->AddDiscreteProcess(theBoundaryProcess); pManager->AddDiscreteProcess(theWLSProcess); theScintProcess->SetScintillationYieldFactor(1.); - theScintProcess->SetScintillationExcitationRatio(0.0); theScintProcess->SetTrackSecondariesFirst(true); G4ParticleTable *table = G4ParticleTable::GetParticleTable(); diff --git a/Alignment/MillePedeAlignmentAlgorithm/plugins/MillePedeAlignmentAlgorithm.cc b/Alignment/MillePedeAlignmentAlgorithm/plugins/MillePedeAlignmentAlgorithm.cc index 53627617a0303..2170bab0c296c 100644 --- a/Alignment/MillePedeAlignmentAlgorithm/plugins/MillePedeAlignmentAlgorithm.cc +++ b/Alignment/MillePedeAlignmentAlgorithm/plugins/MillePedeAlignmentAlgorithm.cc @@ -93,6 +93,11 @@ MillePedeAlignmentAlgorithm::MillePedeAlignmentAlgorithm(const edm::ParameterSet theDir(theConfig.getUntrackedParameter("fileDir")), theAlignmentParameterStore(nullptr), theAlignables(), + theTrajectoryFactory( + TrajectoryFactoryPlugin::get()->create(theConfig.getParameter("TrajectoryFactory") + .getParameter("TrajectoryFactoryName"), + theConfig.getParameter("TrajectoryFactory"), + iC)), theMinNumHits(cfg.getParameter("minNumHits")), theMaximalCor2D(cfg.getParameter("max2Dcorrelation")), firstIOV_(cfg.getUntrackedParameter("firstIOV")), @@ -273,9 +278,6 @@ void MillePedeAlignmentAlgorithm::initialize(const edm::EventSetup &setup, theMonitor = std::make_unique(tTopo, (theDir + moniFile).c_str()); // Get trajectory factory. In case nothing found, FrameWork will throw... - const edm::ParameterSet fctCfg(theConfig.getParameter("TrajectoryFactory")); - const std::string fctName(fctCfg.getParameter("TrajectoryFactoryName")); - theTrajectoryFactory = TrajectoryFactoryPlugin::get()->create(fctName, fctCfg); } if (this->isMode(myPedeSteerBit)) { diff --git a/Alignment/MillePedeAlignmentAlgorithm/python/mpsvalidate/bigModule.py b/Alignment/MillePedeAlignmentAlgorithm/python/mpsvalidate/bigModule.py index 257723495afe0..5d947b8c05ef4 100644 --- a/Alignment/MillePedeAlignmentAlgorithm/python/mpsvalidate/bigModule.py +++ b/Alignment/MillePedeAlignmentAlgorithm/python/mpsvalidate/bigModule.py @@ -106,20 +106,20 @@ def plot(MillePedeUser, alignables, config): for i in range(3): # get first and last bin with content and chose the one which # has a greater distance to the center - if (abs(numberOfBins / 2 - plot.histo[i].FindFirstBinAbove()) > abs(plot.histo[i].FindLastBinAbove() - numberOfBins / 2)): + if (abs(numberOfBins // 2 - plot.histo[i].FindFirstBinAbove()) > abs(plot.histo[i].FindLastBinAbove() - numberOfBins // 2)): plot.maxBinShift[i] = abs( - numberOfBins / 2 - plot.histo[i].FindFirstBinAbove()) + numberOfBins // 2 - plot.histo[i].FindFirstBinAbove()) # set the maxShift value plot.maxShift[i] = plot.histo[i].GetBinCenter( plot.histo[i].FindFirstBinAbove()) else: plot.maxBinShift[i] = abs( - plot.histo[i].FindLastBinAbove() - numberOfBins / 2) + plot.histo[i].FindLastBinAbove() - numberOfBins // 2) # set the maxShift value plot.maxShift[i] = plot.histo[i].GetBinCenter( plot.histo[i].FindLastBinAbove()) # skip empty histogram - if (abs(plot.maxBinShift[i]) == numberOfBins / 2 + 1): + if (abs(plot.maxBinShift[i]) == numberOfBins // 2 + 1): plot.maxBinShift[i] = 0 # three types of ranges @@ -179,10 +179,10 @@ def plot(MillePedeUser, alignables, config): # count entries which are not shown anymore for i in range(3): # bin 1 to begin of histogram - for j in range(1, numberOfBins / 2 - plot.binShift[i]): + for j in range(1, numberOfBins // 2 - plot.binShift[i]): plot.hiddenEntries[i] += plot.histo[i].GetBinContent(j) # from the end of shown bins to the end of histogram - for j in range(numberOfBins / 2 + plot.binShift[i], plot.histo[i].GetNbinsX()): + for j in range(numberOfBins // 2 + plot.binShift[i], plot.histo[i].GetNbinsX()): plot.hiddenEntries[i] += plot.histo[i].GetBinContent(j) # apply new range diff --git a/Alignment/MillePedeAlignmentAlgorithm/python/mpsvalidate/dumpparser.py b/Alignment/MillePedeAlignmentAlgorithm/python/mpsvalidate/dumpparser.py index 4bfce7e0aef25..5a841a4292346 100644 --- a/Alignment/MillePedeAlignmentAlgorithm/python/mpsvalidate/dumpparser.py +++ b/Alignment/MillePedeAlignmentAlgorithm/python/mpsvalidate/dumpparser.py @@ -23,7 +23,7 @@ def parse(path, config): # save lines in list try: with gzip.open(path) as gzipFile: - dumpFile = gzipFile.readlines() + dumpFile = [ l.decode() for l in gzipFile.readlines() ] except IOError: logger.error("PedeDump: {0} does not exist".format(path)) return @@ -32,11 +32,11 @@ def parse(path, config): # Sum(Chi^2)/Sum(Ndf) if ("Sum(Chi^2)/Sum(Ndf) =" in line): number = [] - number.append(map(float, re.findall( - r"[-+]?\d*\.\d+", dumpFile[i]))) - number.append(map(int, re.findall(r"[-+]?\d+", dumpFile[i + 1]))) - number.append(map(float, re.findall( - r"[-+]?\d*\.\d+", dumpFile[i + 2]))) + number.append(list(map(float, re.findall( + r"[-+]?\d*\.\d+", dumpFile[i])))) + number.append(list(map(int, re.findall(r"[-+]?\d+", dumpFile[i + 1])))) + number.append(list(map(float, re.findall( + r"[-+]?\d*\.\d+", dumpFile[i + 2])))) pedeDump.sumSteps = "{0} / ( {1} - {2} )".format( number[0][0], number[1][0], number[1][1]) pedeDump.sumValue = number[2][0] @@ -44,29 +44,29 @@ def parse(path, config): # Sum(W*Chi^2)/Sum(Ndf)/ if ("Sum(W*Chi^2)/Sum(Ndf)/ =" in line): number = [] - number.append(map(float, re.findall( - r"[-+]?\d*\.\d+", dumpFile[i]))) - number.append(map(int, re.findall(r"[-+]?\d+", dumpFile[i + 1]))) - number.append(map(float, re.findall( - r"[-+]?\d*\.\d+", dumpFile[i + 2]))) - number.append(map(float, re.findall( - r"[-+]?\d*\.\d+", dumpFile[i + 3]))) + number.append(list(map(float, re.findall( + r"[-+]?\d*\.\d+", dumpFile[i])))) + number.append(list(map(int, re.findall(r"[-+]?\d+", dumpFile[i + 1])))) + number.append(list(map(float, re.findall( + r"[-+]?\d*\.\d+", dumpFile[i + 2])))) + number.append(list(map(float, re.findall( + r"[-+]?\d*\.\d+", dumpFile[i + 3])))) pedeDump.sumSteps = "{0} / ( {1} - {2} ) / {3}".format( number[0][0], number[1][0], number[1][1], number[2][0]) pedeDump.sumWValue = number[3][0] if ("with correction for down-weighting" in line): - number = map(float, re.findall(r"[-+]?\d*\.\d+", dumpFile[i])) + number = list(map(float, re.findall(r"[-+]?\d*\.\d+", dumpFile[i]))) pedeDump.correction = number[0] # Peak dynamic memory allocation if ("Peak dynamic memory allocation:" in line): - number = map(float, re.findall(r"[-+]?\d*\.\d+", dumpFile[i])) + number = list(map(float, re.findall(r"[-+]?\d*\.\d+", dumpFile[i]))) pedeDump.memory = number[0] # total time if ("Iteration-end" in line): - number = map(int, re.findall(r"\d+", dumpFile[i + 1])) + number = list(map(int, re.findall(r"\d+", dumpFile[i + 1]))) pedeDump.time = number[:3] # warings @@ -79,17 +79,17 @@ def parse(path, config): # nrec number of records if (" = number of records" in line): - number = map(int, re.findall("\d+", dumpFile[i])) + number = list(map(int, re.findall("\d+", dumpFile[i]))) pedeDump.nrec = number[0] # ntgb total number of parameters if (" = total number of parameters" in line): - number = map(int, re.findall("\d+", dumpFile[i])) + number = list(map(int, re.findall("\d+", dumpFile[i]))) pedeDump.ntgb = number[0] # nvgb number of variable parameters if (" = number of variable parameters" in line): - number = map(int, re.findall("\d+", dumpFile[i])) + number = list(map(int, re.findall("\d+", dumpFile[i]))) pedeDump.nvgb = number[0] return pedeDump diff --git a/Alignment/MillePedeAlignmentAlgorithm/python/mpsvalidate/monitorPlot.py b/Alignment/MillePedeAlignmentAlgorithm/python/mpsvalidate/monitorPlot.py index fc36a1c4b591f..d93a2a2cb62c1 100644 --- a/Alignment/MillePedeAlignmentAlgorithm/python/mpsvalidate/monitorPlot.py +++ b/Alignment/MillePedeAlignmentAlgorithm/python/mpsvalidate/monitorPlot.py @@ -4,7 +4,10 @@ import logging import os -import cPickle +try: + import cPickle as pickle +except: + import pickle import ROOT ROOT.PyConfig.IgnoreCommandLineOptions = True @@ -24,7 +27,7 @@ def plot(config): # retrieve the weights of the different datasets with open(os.path.join(config.jobDataPath, ".weights.pkl"), "rb") as f: - weight_conf = cPickle.load(f) + weight_conf = pickle.load(f) # loop over all millepedemonitor_X.root files for filename in os.listdir("{0}".format(config.jobDataPath)): diff --git a/Alignment/MillePedeAlignmentAlgorithm/scripts/mps_check.py b/Alignment/MillePedeAlignmentAlgorithm/scripts/mps_check.py index 2975222f41590..072564c83cd30 100755 --- a/Alignment/MillePedeAlignmentAlgorithm/scripts/mps_check.py +++ b/Alignment/MillePedeAlignmentAlgorithm/scripts/mps_check.py @@ -24,7 +24,7 @@ # create a list of eos ls entries containing files on eos binary store command = ["ls", "-l", os.path.join(lib.mssDir, "binaries")] try: - eoslsoutput = subprocess.check_output(command, stderr=subprocess.STDOUT).split('\n') + eoslsoutput = subprocess.check_output(command, stderr=subprocess.STDOUT).decode().split('\n') except subprocess.CalledProcessError: eoslsoutput = "" @@ -136,7 +136,7 @@ "RemoteSysCpu", "JobStatus", "RemoveReason"], - stderr = subprocess.STDOUT) + stderr = subprocess.STDOUT).decode() condor_log = condor_log.split() cputime = int(round(float(condor_log[0]))) @@ -242,7 +242,7 @@ for line in eoslsoutput: if milleOut in line: columns = line.split() - mOutSize = columns[4] # 5th column = size + mOutSize = int(columns[4]) # 5th column = size if not (mOutSize>0): emptyDatErr = 1 diff --git a/Alignment/MillePedeAlignmentAlgorithm/scripts/mps_fire.py b/Alignment/MillePedeAlignmentAlgorithm/scripts/mps_fire.py index 13f475061749f..5a7d1caf5b39e 100755 --- a/Alignment/MillePedeAlignmentAlgorithm/scripts/mps_fire.py +++ b/Alignment/MillePedeAlignmentAlgorithm/scripts/mps_fire.py @@ -39,7 +39,7 @@ def forward_proxy(rundir): print("Please create proxy via 'voms-proxy-init -voms cms -rfc'.") sys.exit(1) - local_proxy = subprocess.check_output(["voms-proxy-info", "--path"]).strip() + local_proxy = subprocess.check_output(["voms-proxy-info", "--path"]).decode().strip() shutil.copyfile(local_proxy, os.path.join(rundir,".user_proxy")) @@ -107,7 +107,7 @@ def write_HTCondor_submit_file_pede(path, script, config, lib): for directory in ("binaries", "monitors", "tree_files") for item in spco(cmd+ - glob.glob(opj(lib.mssDir, directory, "*"))).splitlines()] + glob.glob(opj(lib.mssDir, directory, "*"))).decode().splitlines()] disk_usage = sum(disk_usage) disk_usage *= 1.1 # reserve 10% additional space @@ -272,7 +272,7 @@ def write_HTCondor_submit_file_mille(path, script, lib, proxy_path=None): resources = '-q'+resources+' -m g_cmscaf' elif "htcondor" in resources: fire_htcondor = True - schedinfo = subprocess.check_output(["myschedd","show"]) + schedinfo = subprocess.check_output(["myschedd","show"]).decode() if 'cafalca' in resources: if not 'tzero' in schedinfo: print("\nMPS fire: request to use CAF pool which has not been set up. Call `module load lxbatch/tzero` and try again") @@ -310,10 +310,10 @@ def write_HTCondor_submit_file_mille(path, script, lib, proxy_path=None): try: result = subprocess.check_output(submission, stderr=subprocess.STDOUT, - shell=True) + shell=True).decode() except subprocess.CalledProcessError as e: result = "" # -> check for successful job submission will fail - print(' '+result, end=' ') + print(result) result = result.strip() # check if job was submitted and updating jobdatabase @@ -374,7 +374,7 @@ def write_HTCondor_submit_file_mille(path, script, lib, proxy_path=None): try: result = subprocess.check_output(submission, stderr=subprocess.STDOUT, - shell=True) + shell=True).decode() except subprocess.CalledProcessError as e: result = "" # -> check for successful job submission will fail print(' '+result, end=' ') @@ -404,7 +404,7 @@ def write_HTCondor_submit_file_mille(path, script, lib, proxy_path=None): resources = '-q cmscafalcamille' elif "htcondor" in resources: fire_htcondor = True - schedinfo = subprocess.check_output(["myschedd","show"]) + schedinfo = subprocess.check_output(["myschedd","show"]).decode() if 'bigmem' in resources: if not 'share' in schedinfo: print("\nMPS fire: CAF pool is set up, but request to use high-memory machines which live in the standard pool. Call `module load lxbatch/share` and try again") @@ -453,7 +453,7 @@ def write_HTCondor_submit_file_mille(path, script, lib, proxy_path=None): # get the name of merge cfg file -> either the.py or alignment_merge.py command = 'cat '+backupScriptPath+' | grep CONFIG_FILE | head -1 | awk -F"/" \'{print $NF}\'' - mergeCfg = subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True) + mergeCfg = subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True).decode() mergeCfg = mergeCfg.strip() if fire_htcondor: @@ -493,9 +493,9 @@ def write_HTCondor_submit_file_mille(path, script, lib, proxy_path=None): # get the name of merge cfg file command = "cat "+scriptPath+" | grep '^\s*CONFIG_FILE' | awk -F'=' '{print $2}'" - mergeCfg = subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True) + mergeCfg = subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True).decode() command = 'basename '+mergeCfg - mergeCfg = subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True) + mergeCfg = subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True).decode() mergeCfg = mergeCfg.replace('\n','') if fire_htcondor: @@ -521,7 +521,7 @@ def write_HTCondor_submit_file_mille(path, script, lib, proxy_path=None): submission = ["bsub", "-J", curJobName, resources, scriptPath] for _ in range(5): try: - result = subprocess.check_output(submission, stderr=subprocess.STDOUT) + result = subprocess.check_output(submission, stderr=subprocess.STDOUT).decode() break except subprocess.CalledProcessError as e: result = e.output @@ -577,9 +577,9 @@ def write_HTCondor_submit_file_mille(path, script, lib, proxy_path=None): # get the name of merge cfg file command = "cat "+scriptPath+" | grep '^\s*CONFIG_FILE' | awk -F'=' '{print $2}'" - mergeCfg = subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True) + mergeCfg = subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True).decode() command = 'basename '+mergeCfg - mergeCfg = subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True) + mergeCfg = subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True).decode() mergeCfg = mergeCfg.replace('\n','') if fire_htcondor: @@ -604,7 +604,7 @@ def write_HTCondor_submit_file_mille(path, script, lib, proxy_path=None): submission = ["bsub", "-J", curJobName, resources, scriptPath] for _ in range(5): try: - result = subprocess.check_output(submission, stderr=subprocess.STDOUT) + result = subprocess.check_output(submission, stderr=subprocess.STDOUT).decode() break except subprocess.CalledProcessError as e: result = e.output diff --git a/Alignment/MillePedeAlignmentAlgorithm/scripts/mps_update.py b/Alignment/MillePedeAlignmentAlgorithm/scripts/mps_update.py index 7b10f74629082..3b7af2d933fa0 100755 --- a/Alignment/MillePedeAlignmentAlgorithm/scripts/mps_update.py +++ b/Alignment/MillePedeAlignmentAlgorithm/scripts/mps_update.py @@ -63,7 +63,7 @@ def fill_time_info(mps_index, status, cpu_time): job_status = {} condor_q = subprocess.check_output(["condor_q", "-af:j", "JobStatus", "RemoteSysCpu"], - stderr = subprocess.STDOUT) + stderr = subprocess.STDOUT).decode() for line in condor_q.splitlines(): job_id, status, cpu_time = line.split() job_status[job_id] = {"status": htcondor_jobstatus[status], @@ -90,7 +90,8 @@ def fill_time_info(mps_index, status, cpu_time): ################################################################################ # loop over remaining jobs to see whether they are done -for job_id, mps_index in submitted_jobs.items(): # IMPORTANT to copy here (no iterator!) +submitted_jobs_copy = { k:v for k,v in submitted_jobs.items() } +for job_id, mps_index in submitted_jobs_copy.items(): # IMPORTANT to copy here (no iterator!) # check if current job is disabled. Print stuff. disabled = "DISABLED" if "DISABLED" in lib.JOBSTATUS[mps_index] else "" print(" DB job ", job_id, mps_index) @@ -100,7 +101,7 @@ def fill_time_info(mps_index, status, cpu_time): condor_h = subprocess.check_output(["condor_history", job_id, "-limit", "1", "-userlog", userlog, "-af:j", "JobStatus", "RemoteSysCpu"], - stderr = subprocess.STDOUT) + stderr = subprocess.STDOUT).decode() if len(condor_h.strip()) > 0: job_id, status, cpu_time = condor_h.split() status = htcondor_jobstatus[status] diff --git a/Alignment/MuonAlignment/interface/MuonAlignment.h b/Alignment/MuonAlignment/interface/MuonAlignment.h index ec70e349ca87f..09bfcf08cb339 100644 --- a/Alignment/MuonAlignment/interface/MuonAlignment.h +++ b/Alignment/MuonAlignment/interface/MuonAlignment.h @@ -20,7 +20,7 @@ class MuonAlignment { public: - MuonAlignment(const edm::EventSetup& iSetup); + MuonAlignment(const DTGeometry* dtGeometry, const CSCGeometry* cscGeometry, const GEMGeometry* gemGeometry); MuonAlignment(const edm::EventSetup& iSetup, const MuonAlignmentInputMethod& input); @@ -45,7 +45,10 @@ class MuonAlignment { void fillGapsInSurvey(double shiftErr, double angleErr); void copySurveyToAlignment(); - void writeXML(const edm::ParameterSet& iConfig, const edm::EventSetup& iSetup); + void writeXML(const edm::ParameterSet& iConfig, + const DTGeometry* dtGeometryXML, + const CSCGeometry* cscGeometryXML, + const GEMGeometry* gemGeometryXML); void saveDTSurveyToDB(); void saveCSCSurveyToDB(); @@ -66,9 +69,9 @@ class MuonAlignment { std::string theDTSurveyRecordName, theDTSurveyErrorRecordName; std::string theCSCSurveyRecordName, theCSCSurveyErrorRecordName; - edm::ESGetToken esTokenDT_; - edm::ESGetToken esTokenCSC_; - edm::ESGetToken esTokenGEM_; + const DTGeometry* dtGeometry_; + const CSCGeometry* cscGeometry_; + const GEMGeometry* gemGeometry_; align::Scalars displacements; diff --git a/Alignment/MuonAlignment/interface/MuonAlignmentInputDB.h b/Alignment/MuonAlignment/interface/MuonAlignmentInputDB.h index 714e788b5b194..19db1d959c756 100644 --- a/Alignment/MuonAlignment/interface/MuonAlignmentInputDB.h +++ b/Alignment/MuonAlignment/interface/MuonAlignmentInputDB.h @@ -28,9 +28,23 @@ class MuonAlignmentInputDB : public MuonAlignmentInputMethod { public: - MuonAlignmentInputDB(); - MuonAlignmentInputDB( - std::string dtLabel, std::string cscLabel, std::string gemLabel, std::string idealLabel, bool getAPEs); + MuonAlignmentInputDB(const DTGeometry* dtGeometry, + const CSCGeometry* cscGeometry, + const GEMGeometry* gemGeometry, + const Alignments* dtAlignments, + const Alignments* cscAlignments, + const Alignments* gemAlignments, + const Alignments* globalPositionRcd); + MuonAlignmentInputDB(const DTGeometry* dtGeometry, + const CSCGeometry* cscGeometry, + const GEMGeometry* gemGeometry, + const Alignments* dtAlignments, + const Alignments* cscAlignments, + const Alignments* gemAlignments, + const Alignments* globalPositionRcd, + const AlignmentErrorsExtended* dtAlignmentErrorsExtended, + const AlignmentErrorsExtended* cscAlignmentErrorsExtended, + const AlignmentErrorsExtended* gemAlignmentErrorsExtended); ~MuonAlignmentInputDB() override; // ---------- const member functions --------------------- @@ -39,17 +53,26 @@ class MuonAlignmentInputDB : public MuonAlignmentInputMethod { // ---------- member functions --------------------------- - AlignableMuon *newAlignableMuon(const edm::EventSetup &iSetup) const override; + AlignableMuon* newAlignableMuon() const override; - MuonAlignmentInputDB(const MuonAlignmentInputDB &) = delete; // stop default + MuonAlignmentInputDB(const MuonAlignmentInputDB&) = delete; // stop default - const MuonAlignmentInputDB &operator=(const MuonAlignmentInputDB &) = delete; // stop default + const MuonAlignmentInputDB& operator=(const MuonAlignmentInputDB&) = delete; // stop default private: // ---------- member data -------------------------------- - - std::string m_dtLabel, m_cscLabel, m_gemLabel, idealGeometryLabel; - bool m_getAPEs; + const DTGeometry* dtGeometry_; + const CSCGeometry* cscGeometry_; + const GEMGeometry* gemGeometry_; + const Alignments* dtAlignments_; + const Alignments* cscAlignments_; + const Alignments* gemAlignments_; + const Alignments* globalPositionRcd_; + const AlignmentErrorsExtended* dtAlignmentErrorsExtended_; + const AlignmentErrorsExtended* cscAlignmentErrorsExtended_; + const AlignmentErrorsExtended* gemAlignmentErrorsExtended_; + + const bool m_getAPEs; }; #endif diff --git a/Alignment/MuonAlignment/interface/MuonAlignmentInputMethod.h b/Alignment/MuonAlignment/interface/MuonAlignmentInputMethod.h index 8beb005427983..3b5041d130df4 100644 --- a/Alignment/MuonAlignment/interface/MuonAlignmentInputMethod.h +++ b/Alignment/MuonAlignment/interface/MuonAlignmentInputMethod.h @@ -28,13 +28,16 @@ #include "Alignment/MuonAlignment/interface/AlignableMuon.h" #include "Geometry/DTGeometry/interface/DTGeometry.h" #include "Geometry/CSCGeometry/interface/CSCGeometry.h" +#include "Geometry/GEMGeometry/interface/GEMGeometry.h" // forward declarations class MuonAlignmentInputMethod { public: MuonAlignmentInputMethod(); - MuonAlignmentInputMethod(std::string idealLabel); + MuonAlignmentInputMethod(const DTGeometry* dtGeometry, + const CSCGeometry* cscGeometry, + const GEMGeometry* gemGeometry); virtual ~MuonAlignmentInputMethod(); // ---------- const member functions --------------------- @@ -43,15 +46,17 @@ class MuonAlignmentInputMethod { // ---------- member functions --------------------------- - virtual AlignableMuon *newAlignableMuon(const edm::EventSetup &iSetup) const; + virtual AlignableMuon* newAlignableMuon() const; - MuonAlignmentInputMethod(const MuonAlignmentInputMethod &) = delete; // stop default + MuonAlignmentInputMethod(const MuonAlignmentInputMethod&) = delete; // stop default - const MuonAlignmentInputMethod &operator=(const MuonAlignmentInputMethod &) = delete; // stop default + const MuonAlignmentInputMethod& operator=(const MuonAlignmentInputMethod&) = delete; // stop default private: // ---------- member data -------------------------------- - std::string idealGeometryLabel; + const DTGeometry* dtGeometry_; + const CSCGeometry* cscGeometry_; + const GEMGeometry* gemGeometry_; }; #endif diff --git a/Alignment/MuonAlignment/interface/MuonAlignmentInputSurveyDB.h b/Alignment/MuonAlignment/interface/MuonAlignmentInputSurveyDB.h index fda75deb7d61b..bf67083744645 100644 --- a/Alignment/MuonAlignment/interface/MuonAlignmentInputSurveyDB.h +++ b/Alignment/MuonAlignment/interface/MuonAlignmentInputSurveyDB.h @@ -30,8 +30,13 @@ class MuonAlignmentInputSurveyDB : public MuonAlignmentInputMethod { public: - MuonAlignmentInputSurveyDB(); - MuonAlignmentInputSurveyDB(std::string dtLabel, std::string cscLabel, std::string idealLabel); + MuonAlignmentInputSurveyDB(const DTGeometry* dtGeometry, + const CSCGeometry* cscGeometry, + const GEMGeometry* gemGeometry, + const Alignments* dtSurvey, + const Alignments* cscSurvey, + const SurveyErrors* dtSurveyError, + const SurveyErrors* cscSurveyError); ~MuonAlignmentInputSurveyDB() override; // ---------- const member functions --------------------- @@ -40,7 +45,7 @@ class MuonAlignmentInputSurveyDB : public MuonAlignmentInputMethod { // ---------- member functions --------------------------- - AlignableMuon* newAlignableMuon(const edm::EventSetup& iSetup) const override; + AlignableMuon* newAlignableMuon() const override; MuonAlignmentInputSurveyDB(const MuonAlignmentInputSurveyDB&) = delete; // stop default @@ -53,8 +58,13 @@ class MuonAlignmentInputSurveyDB : public MuonAlignmentInputMethod { const SurveyErrors* theSurveyErrors) const; // ---------- member data -------------------------------- - - std::string m_dtLabel, m_cscLabel, idealGeometryLabel; + const DTGeometry* dtGeometry_; + const CSCGeometry* cscGeometry_; + const GEMGeometry* gemGeometry_; + const Alignments* dtSurvey_; + const Alignments* cscSurvey_; + const SurveyErrors* dtSurveyError_; + const SurveyErrors* cscSurveyError_; }; #endif diff --git a/Alignment/MuonAlignment/interface/MuonAlignmentInputXML.h b/Alignment/MuonAlignment/interface/MuonAlignmentInputXML.h index 044a31c4e0f0d..e0fee72f31e32 100644 --- a/Alignment/MuonAlignment/interface/MuonAlignmentInputXML.h +++ b/Alignment/MuonAlignment/interface/MuonAlignmentInputXML.h @@ -32,7 +32,13 @@ class MuonAlignmentInputXML : public MuonAlignmentInputMethod { public: - MuonAlignmentInputXML(const std::string &fileName, std::string idealLabel); + MuonAlignmentInputXML(const std::string &fileName, + const DTGeometry *dtGeometry, + const CSCGeometry *cscGeometry, + const GEMGeometry *gemGeometry, + const DTGeometry *dtGeometryIdeal, + const CSCGeometry *cscGeometryIdeal, + const GEMGeometry *gemGeometryIdeal); ~MuonAlignmentInputXML() override; // ---------- const member functions --------------------- @@ -41,7 +47,7 @@ class MuonAlignmentInputXML : public MuonAlignmentInputMethod { // ---------- member functions --------------------------- - AlignableMuon *newAlignableMuon(const edm::EventSetup &iSetup) const override; + AlignableMuon *newAlignableMuon() const override; MuonAlignmentInputXML(const MuonAlignmentInputXML &) = delete; // stop default @@ -66,6 +72,10 @@ class MuonAlignmentInputXML : public MuonAlignmentInputMethod { std::map &alignableNavigator, const XERCES_CPP_NAMESPACE::DOMElement *node, const AlignableObjectId &) const; + Alignable *getGEMnode(align::StructureType structureType, + std::map &alignableNavigator, + const XERCES_CPP_NAMESPACE::DOMElement *node, + const AlignableObjectId &) const; double parseDouble(const XMLCh *str, const char *attribute) const; void set_one_position(Alignable *ali, const align::PositionType &pos, const align::RotationType &rot) const; @@ -96,7 +106,14 @@ class MuonAlignmentInputXML : public MuonAlignmentInputMethod { std::map &alitoideal) const; // ---------- member data -------------------------------- - std::string m_fileName, idealGeometryLabel; + std::string m_fileName; + + const DTGeometry *dtGeometry_; + const CSCGeometry *cscGeometry_; + const GEMGeometry *gemGeometry_; + const DTGeometry *dtGeometryIdeal_; + const CSCGeometry *cscGeometryIdeal_; + const GEMGeometry *gemGeometryIdeal_; XMLCh *str_operation; XMLCh *str_collection; @@ -112,6 +129,12 @@ class MuonAlignmentInputXML : public MuonAlignmentInputMethod { XMLCh *str_CSCRing; XMLCh *str_CSCChamber; XMLCh *str_CSCLayer; + XMLCh *str_GEMEndcap; + XMLCh *str_GEMStation; + XMLCh *str_GEMRing; + XMLCh *str_GEMSuperChamber; + XMLCh *str_GEMChamber; + XMLCh *str_GEMEtaPartition; XMLCh *str_setposition; XMLCh *str_setape; XMLCh *str_setsurveyerr; @@ -130,6 +153,8 @@ class MuonAlignmentInputXML : public MuonAlignmentInputMethod { XMLCh *str_endcap; XMLCh *str_ring; XMLCh *str_chamber; + XMLCh *str_superChamber; + XMLCh *str_etaPartition; XMLCh *str_axisx; XMLCh *str_axisy; XMLCh *str_axisz; diff --git a/Alignment/MuonAlignment/interface/MuonAlignmentOutputXML.h b/Alignment/MuonAlignment/interface/MuonAlignmentOutputXML.h index 18d79608b1356..fb345393682f0 100644 --- a/Alignment/MuonAlignment/interface/MuonAlignmentOutputXML.h +++ b/Alignment/MuonAlignment/interface/MuonAlignmentOutputXML.h @@ -28,13 +28,18 @@ // user include files #include "Alignment/MuonAlignment/interface/AlignableMuon.h" #include "CondFormats/Alignment/interface/AlignTransformErrorExtended.h" - +#include "Geometry/DTGeometry/interface/DTGeometry.h" +#include "Geometry/CSCGeometry/interface/CSCGeometry.h" +#include "Geometry/GEMGeometry/interface/GEMGeometry.h" // forward declarations class AlignableObjectId; class MuonAlignmentOutputXML { public: - MuonAlignmentOutputXML(const edm::ParameterSet &iConfig); + MuonAlignmentOutputXML(const edm::ParameterSet &iConfig, + const DTGeometry *dtGeometry, + const CSCGeometry *cscGeometry, + const GEMGeometry *gemGeometry); virtual ~MuonAlignmentOutputXML(); // ---------- const member functions --------------------- @@ -43,18 +48,19 @@ class MuonAlignmentOutputXML { // ---------- member functions --------------------------- - void write(AlignableMuon *alignableMuon, const edm::EventSetup &iSetup) const; + void write(AlignableMuon *alignableMuon) const; MuonAlignmentOutputXML(const MuonAlignmentOutputXML &) = delete; // stop default const MuonAlignmentOutputXML &operator=(const MuonAlignmentOutputXML &) = delete; // stop default private: + enum { doDT, doCSC, doGEM }; void writeComponents(align::Alignables &alignables, align::Alignables &ideals, std::map &errors, std::ofstream &outputFile, - bool DT, + const int doDet, const AlignableObjectId &) const; // ---------- member data -------------------------------- @@ -65,7 +71,12 @@ class MuonAlignmentOutputXML { bool m_suppressDTBarrel, m_suppressDTWheels, m_suppressDTStations, m_suppressDTChambers, m_suppressDTSuperLayers, m_suppressDTLayers; bool m_suppressCSCEndcaps, m_suppressCSCStations, m_suppressCSCRings, m_suppressCSCChambers, m_suppressCSCLayers; - std::string idealGeometryLabel; + bool m_suppressGEMEndcaps, m_suppressGEMStations, m_suppressGEMRings, m_suppressGEMSuperChambers, + m_suppressGEMChambers, m_suppressGEMEtaPartitions; + + const DTGeometry *dtGeometry_; + const CSCGeometry *cscGeometry_; + const GEMGeometry *gemGeometry_; }; #endif diff --git a/Alignment/MuonAlignment/plugins/MuonGeometryArrange.cc b/Alignment/MuonAlignment/plugins/MuonGeometryArrange.cc index 69dbe635bbb8d..1139b2137121d 100644 --- a/Alignment/MuonAlignment/plugins/MuonGeometryArrange.cc +++ b/Alignment/MuonAlignment/plugins/MuonGeometryArrange.cc @@ -47,7 +47,20 @@ MuonGeometryArrange::MuonGeometryArrange(const edm::ParameterSet& cfg) firstEvent_(true), idealInputLabel1("MuonGeometryArrangeLabel1"), idealInputLabel2("MuonGeometryArrangeLabel2"), - idealInputLabel2a("MuonGeometryArrangeLabel2a") { + idealInputLabel2a("MuonGeometryArrangeLabel2a"), + geomIdeal("MuonGeometryArrangeGeomIdeal"), + dtGeomToken1_(esConsumes(edm::ESInputTag("", idealInputLabel1))), + cscGeomToken1_(esConsumes(edm::ESInputTag("", idealInputLabel1))), + gemGeomToken1_(esConsumes(edm::ESInputTag("", idealInputLabel1))), + dtGeomToken2_(esConsumes(edm::ESInputTag("", idealInputLabel2))), + cscGeomToken2_(esConsumes(edm::ESInputTag("", idealInputLabel2))), + gemGeomToken2_(esConsumes(edm::ESInputTag("", idealInputLabel2))), + dtGeomToken3_(esConsumes(edm::ESInputTag("", idealInputLabel2a))), + cscGeomToken3_(esConsumes(edm::ESInputTag("", idealInputLabel2a))), + gemGeomToken3_(esConsumes(edm::ESInputTag("", idealInputLabel2a))), + dtGeomIdealToken_(esConsumes(edm::ESInputTag("", geomIdeal))), + cscGeomIdealToken_(esConsumes(edm::ESInputTag("", geomIdeal))), + gemGeomIdealToken_(esConsumes(edm::ESInputTag("", geomIdeal))) { referenceMuon = nullptr; currentMuon = nullptr; // Input is XML @@ -622,14 +635,31 @@ void MuonGeometryArrange::createROOTGeometry(const edm::EventSetup& iSetup) {} ////////////////////////////////////////////////// void MuonGeometryArrange::analyze(const edm::Event&, const edm::EventSetup& iSetup) { if (firstEvent_) { - // My stuff - MuonAlignmentInputXML inputMethod1(_inputXMLCurrent, idealInputLabel1); + MuonAlignmentInputXML inputMethod1(_inputXMLCurrent, + &iSetup.getData(dtGeomToken1_), + &iSetup.getData(cscGeomToken1_), + &iSetup.getData(gemGeomToken1_), + &iSetup.getData(dtGeomToken1_), + &iSetup.getData(cscGeomToken1_), + &iSetup.getData(gemGeomToken1_)); inputAlign1 = new MuonAlignment(iSetup, inputMethod1); inputAlign1->fillGapsInSurvey(0, 0); - MuonAlignmentInputXML inputMethod2(_inputXMLReference, idealInputLabel2); + MuonAlignmentInputXML inputMethod2(_inputXMLReference, + &iSetup.getData(dtGeomToken2_), + &iSetup.getData(cscGeomToken2_), + &iSetup.getData(gemGeomToken2_), + &iSetup.getData(dtGeomToken1_), + &iSetup.getData(cscGeomToken1_), + &iSetup.getData(gemGeomToken1_)); inputAlign2 = new MuonAlignment(iSetup, inputMethod2); inputAlign2->fillGapsInSurvey(0, 0); - MuonAlignmentInputXML inputMethod2a(_inputXMLReference, idealInputLabel2a); + MuonAlignmentInputXML inputMethod2a(_inputXMLReference, + &iSetup.getData(dtGeomToken3_), + &iSetup.getData(cscGeomToken3_), + &iSetup.getData(gemGeomToken3_), + &iSetup.getData(dtGeomToken1_), + &iSetup.getData(cscGeomToken1_), + &iSetup.getData(gemGeomToken1_)); inputAlign2a = new MuonAlignment(iSetup, inputMethod2a); inputAlign2a->fillGapsInSurvey(0, 0); diff --git a/Alignment/MuonAlignment/plugins/MuonGeometryArrange.h b/Alignment/MuonAlignment/plugins/MuonGeometryArrange.h index 0d0e0551d1f7a..c5ef393e841f9 100644 --- a/Alignment/MuonAlignment/plugins/MuonGeometryArrange.h +++ b/Alignment/MuonAlignment/plugins/MuonGeometryArrange.h @@ -19,7 +19,7 @@ * \author Nhan Tran */ -#include "FWCore/Framework/interface/EDAnalyzer.h" +#include "FWCore/Framework/interface/one/EDAnalyzer.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "Alignment/MuonAlignment/interface/AlignableMuon.h" #include "CondFormats/Alignment/interface/SurveyErrors.h" @@ -35,7 +35,7 @@ class MuonAlignment; class TGraph; class TH2F; -class MuonGeometryArrange : public edm::EDAnalyzer { +class MuonGeometryArrange : public edm::one::EDAnalyzer<> { public: typedef AlignTransform SurveyValue; typedef Alignments SurveyValues; @@ -170,7 +170,23 @@ class MuonGeometryArrange : public edm::EDAnalyzer { bool firstEvent_; - std::string idealInputLabel1, idealInputLabel2, idealInputLabel2a; + std::string idealInputLabel1, idealInputLabel2, idealInputLabel2a, geomIdeal; + + const edm::ESGetToken dtGeomToken1_; + const edm::ESGetToken cscGeomToken1_; + const edm::ESGetToken gemGeomToken1_; + + const edm::ESGetToken dtGeomToken2_; + const edm::ESGetToken cscGeomToken2_; + const edm::ESGetToken gemGeomToken2_; + + const edm::ESGetToken dtGeomToken3_; + const edm::ESGetToken cscGeomToken3_; + const edm::ESGetToken gemGeomToken3_; + + const edm::ESGetToken dtGeomIdealToken_; + const edm::ESGetToken cscGeomIdealToken_; + const edm::ESGetToken gemGeomIdealToken_; }; #endif diff --git a/Alignment/MuonAlignment/plugins/MuonGeometryDBConverter.cc b/Alignment/MuonAlignment/plugins/MuonGeometryDBConverter.cc index 5afd04cf3f02f..580b99e1e4774 100644 --- a/Alignment/MuonAlignment/plugins/MuonGeometryDBConverter.cc +++ b/Alignment/MuonAlignment/plugins/MuonGeometryDBConverter.cc @@ -34,6 +34,8 @@ #include "Alignment/MuonAlignment/interface/MuonAlignmentInputSurveyDB.h" #include "Alignment/MuonAlignment/interface/MuonAlignmentInputXML.h" #include "Alignment/MuonAlignment/interface/MuonScenarioBuilder.h" +#include "Geometry/Records/interface/MuonGeometryRecord.h" +#include "CondFormats/AlignmentRecord/interface/GlobalPositionRcd.h" // // class decleration @@ -61,8 +63,20 @@ class MuonGeometryDBConverter : public edm::one::EDAnalyzer<> { edm::ParameterSet m_misalignmentScenario; edm::ParameterSet m_outputXML; - std::string idealGeometryLabelForInputMethod, idealGeometryLabelForInputDB, idealGeometryLabelForInputXML, - idealGeometryLabelForInputSurveyDB; + const std::string idealGeometryLabelForInputXML, idealGeometryLabel; + + const edm::ESGetToken dtGeomIdealToken_; + const edm::ESGetToken cscGeomIdealToken_; + const edm::ESGetToken gemGeomIdealToken_; + + edm::ESGetToken dtGeomToken_; + edm::ESGetToken cscGeomToken_; + edm::ESGetToken gemGeomToken_; + + edm::ESGetToken dtAliToken_; + edm::ESGetToken cscAliToken_; + edm::ESGetToken gemAliToken_; + const edm::ESGetToken gprToken_; }; // @@ -83,10 +97,12 @@ MuonGeometryDBConverter::MuonGeometryDBConverter(const edm::ParameterSet &iConfi m_shiftErr(0.), m_angleErr(0.), m_getAPEs(false), - idealGeometryLabelForInputMethod("idealForInputMethod"), - idealGeometryLabelForInputDB("idealForInputDB"), idealGeometryLabelForInputXML("idealForInputXML"), - idealGeometryLabelForInputSurveyDB("idealForInputSurveyDB") { + idealGeometryLabel("idealGeometry"), + dtGeomIdealToken_(esConsumes(edm::ESInputTag("", idealGeometryLabel))), + cscGeomIdealToken_(esConsumes(edm::ESInputTag("", idealGeometryLabel))), + gemGeomIdealToken_(esConsumes(edm::ESInputTag("", idealGeometryLabel))), + gprToken_(esConsumes(edm::ESInputTag("", ""))) { //////////////////////////////////////////////////////////////////// // Version V02-03-02 and earlier of this module had support for // // "cfg" as an input/output format. It turns out that reading // @@ -96,54 +112,46 @@ MuonGeometryDBConverter::MuonGeometryDBConverter(const edm::ParameterSet &iConfi //////////////////////////////////////////////////////////////////// if (m_input == std::string("ideal")) { - } - - else if (m_input == std::string("db")) { + } else if (m_input == std::string("db")) { m_dtLabel = iConfig.getParameter("dtLabel"); m_cscLabel = iConfig.getParameter("cscLabel"); m_gemLabel = iConfig.getParameter("gemLabel"); m_shiftErr = iConfig.getParameter("shiftErr"); m_angleErr = iConfig.getParameter("angleErr"); m_getAPEs = iConfig.getParameter("getAPEs"); - } + m_outputXML = iConfig.getParameter("outputXML"); + + dtAliToken_ = esConsumes(edm::ESInputTag("", m_dtLabel)); + cscAliToken_ = esConsumes(edm::ESInputTag("", m_cscLabel)); + gemAliToken_ = esConsumes(edm::ESInputTag("", m_gemLabel)); - else if (m_input == std::string("surveydb")) { + dtGeomToken_ = esConsumes(edm::ESInputTag("", idealGeometryLabelForInputXML)); + cscGeomToken_ = esConsumes(edm::ESInputTag("", idealGeometryLabelForInputXML)); + gemGeomToken_ = esConsumes(edm::ESInputTag("", idealGeometryLabelForInputXML)); + } else if (m_input == std::string("surveydb")) { m_dtLabel = iConfig.getParameter("dtLabel"); m_cscLabel = iConfig.getParameter("cscLabel"); m_gemLabel = iConfig.getParameter("gemLabel"); - } - - else if (m_input == std::string("scenario")) { + } else if (m_input == std::string("scenario")) { m_misalignmentScenario = iConfig.getParameter("MisalignmentScenario"); m_shiftErr = iConfig.getParameter("shiftErr"); m_angleErr = iConfig.getParameter("angleErr"); - } - - else if (m_input == std::string("xml")) { + } else if (m_input == std::string("xml")) { m_fileName = iConfig.getParameter("fileName"); m_shiftErr = iConfig.getParameter("shiftErr"); m_angleErr = iConfig.getParameter("angleErr"); - } - - else { + dtGeomToken_ = esConsumes(edm::ESInputTag("", idealGeometryLabelForInputXML)); + cscGeomToken_ = esConsumes(edm::ESInputTag("", idealGeometryLabelForInputXML)); + gemGeomToken_ = esConsumes(edm::ESInputTag("", idealGeometryLabelForInputXML)); + } else { throw cms::Exception("BadConfig") << "input must be \"ideal\", \"db\", \"surveydb\", or \"xml\"." << std::endl; } - if (m_output == std::string("none")) { - } - - else if (m_output == std::string("db")) { - } - - else if (m_output == std::string("surveydb")) { - } - - else if (m_output == std::string("xml")) { + } else if (m_output == std::string("db")) { + } else if (m_output == std::string("xml")) { m_outputXML = iConfig.getParameter("outputXML"); - } - - else { - throw cms::Exception("BadConfig") << "output must be \"none\", \"db\", or \"surveydb\"." << std::endl; + } else { + throw cms::Exception("BadConfig") << "output must be \"none\", \"db \", \"xml\"." << std::endl; } } @@ -152,64 +160,47 @@ MuonGeometryDBConverter::~MuonGeometryDBConverter() {} // ------------ method called to for each event ------------ void MuonGeometryDBConverter::analyze(const edm::Event &iEvent, const edm::EventSetup &iSetup) { if (!m_done) { - MuonAlignment *muonAlignment = nullptr; - if (m_input == std::string("ideal")) { - MuonAlignmentInputMethod inputMethod; - muonAlignment = new MuonAlignment(iSetup, inputMethod); + MuonAlignmentInputMethod inputMethod( + &iSetup.getData(dtGeomIdealToken_), &iSetup.getData(cscGeomIdealToken_), &iSetup.getData(gemGeomIdealToken_)); + MuonAlignment *muonAlignment = new MuonAlignment(iSetup, inputMethod); muonAlignment->fillGapsInSurvey(0., 0.); - } - - else if (m_input == std::string("db")) { - MuonAlignmentInputDB inputMethod(m_dtLabel, m_cscLabel, m_gemLabel, idealGeometryLabelForInputDB, m_getAPEs); - muonAlignment = new MuonAlignment(iSetup, inputMethod); + muonAlignment->saveToDB(); + } else if (m_input == std::string("db")) { + MuonAlignmentInputDB inputMethod(&iSetup.getData(dtGeomIdealToken_), + &iSetup.getData(cscGeomIdealToken_), + &iSetup.getData(gemGeomIdealToken_), + &iSetup.getData(dtAliToken_), + &iSetup.getData(cscAliToken_), + &iSetup.getData(gemAliToken_), + &iSetup.getData(gprToken_)); + MuonAlignment *muonAlignment = new MuonAlignment(iSetup, inputMethod); if (m_getAPEs) { muonAlignment->copyAlignmentToSurvey(m_shiftErr, m_angleErr); } - } - - else if (m_input == std::string("surveydb")) { - MuonAlignmentInputSurveyDB inputMethod(m_dtLabel, m_cscLabel, idealGeometryLabelForInputSurveyDB); - muonAlignment = new MuonAlignment(iSetup, inputMethod); - muonAlignment->copySurveyToAlignment(); - } - - else if (m_input == std::string("scenario")) { - MuonAlignmentInputMethod inputMethod; - muonAlignment = new MuonAlignment(iSetup, inputMethod); + muonAlignment->writeXML( + m_outputXML, &iSetup.getData(dtGeomToken_), &iSetup.getData(cscGeomToken_), &iSetup.getData(gemGeomToken_)); + } else if (m_input == std::string("scenario")) { + MuonAlignmentInputMethod inputMethod( + &iSetup.getData(dtGeomIdealToken_), &iSetup.getData(cscGeomIdealToken_), &iSetup.getData(gemGeomIdealToken_)); + MuonAlignment *muonAlignment = new MuonAlignment(iSetup, inputMethod); MuonScenarioBuilder muonScenarioBuilder(muonAlignment->getAlignableMuon()); muonScenarioBuilder.applyScenario(m_misalignmentScenario); + muonAlignment->saveToDB(); muonAlignment->copyAlignmentToSurvey(m_shiftErr, m_angleErr); - } - - else if (m_input == std::string("xml")) { - MuonAlignmentInputXML inputMethod(m_fileName, idealGeometryLabelForInputXML); - muonAlignment = new MuonAlignment(iSetup, inputMethod); + } else if (m_input == std::string("xml")) { + MuonAlignmentInputXML inputMethod(m_fileName, + &iSetup.getData(dtGeomToken_), + &iSetup.getData(cscGeomToken_), + &iSetup.getData(gemGeomToken_), + &iSetup.getData(dtGeomIdealToken_), + &iSetup.getData(cscGeomIdealToken_), + &iSetup.getData(gemGeomIdealToken_)); + MuonAlignment *muonAlignment = new MuonAlignment(iSetup, inputMethod); + muonAlignment->saveToDB(); muonAlignment->fillGapsInSurvey(m_shiftErr, m_angleErr); } - - ///////////// - - if (muonAlignment) { - if (m_output == std::string("none")) { - } - - else if (m_output == std::string("db")) { - muonAlignment->saveToDB(); - } - - else if (m_output == std::string("surveydb")) { - muonAlignment->saveSurveyToDB(); - } - - else if (m_output == std::string("xml")) { - muonAlignment->writeXML(m_outputXML, iSetup); - } - - delete muonAlignment; - } - m_done = true; } // end if not done else { @@ -233,8 +224,8 @@ void MuonGeometryDBConverter::fillDescriptions(edm::ConfigurationDescriptions &d edm::ParameterSetDescription outputXML; outputXML.add("fileName", "REPLACEME.xml"); outputXML.add("relativeto", "ideal"); - outputXML.add("survey", false); outputXML.add("rawIds", false); + outputXML.add("survey", false); outputXML.add("eulerAngles", false); outputXML.add("precision", 10); outputXML.addUntracked("suppressDTBarrel", true); @@ -248,6 +239,12 @@ void MuonGeometryDBConverter::fillDescriptions(edm::ConfigurationDescriptions &d outputXML.addUntracked("suppressCSCRings", true); outputXML.addUntracked("suppressCSCChambers", false); outputXML.addUntracked("suppressCSCLayers", false); + outputXML.addUntracked("suppressGEMEndcaps", true); + outputXML.addUntracked("suppressGEMStations", true); + outputXML.addUntracked("suppressGEMRings", true); + outputXML.addUntracked("suppressGEMSuperChambers", false); + outputXML.addUntracked("suppressGEMChambers", true); + outputXML.addUntracked("suppressGEMEtaPartitions", true); desc.add("outputXML", outputXML); descriptions.add("muonGeometryDBConverter", desc); } diff --git a/Alignment/MuonAlignment/plugins/MuonGeometrySanityCheck.cc b/Alignment/MuonAlignment/plugins/MuonGeometrySanityCheck.cc index 91db8d5f33c67..6010da76f0166 100644 --- a/Alignment/MuonAlignment/plugins/MuonGeometrySanityCheck.cc +++ b/Alignment/MuonAlignment/plugins/MuonGeometrySanityCheck.cc @@ -19,7 +19,7 @@ // system include files #include "FWCore/Framework/interface/Frameworkfwd.h" -#include "FWCore/Framework/interface/EDAnalyzer.h" +#include "FWCore/Framework/interface/one/EDAnalyzer.h" #include "FWCore/Framework/interface/EventSetup.h" #include "FWCore/Framework/interface/ESHandle.h" #include "FWCore/Framework/interface/Event.h" @@ -81,7 +81,7 @@ class MuonGeometrySanityCheckPoint { int number(std::string s); }; -class MuonGeometrySanityCheck : public edm::EDAnalyzer { +class MuonGeometrySanityCheck : public edm::one::EDAnalyzer<> { public: explicit MuonGeometrySanityCheck(const edm::ParameterSet &iConfig); ~MuonGeometrySanityCheck() override; @@ -94,6 +94,9 @@ class MuonGeometrySanityCheck : public edm::EDAnalyzer { std::string prefix; std::map m_frames; std::vector m_points; + + const edm::ESGetToken dtGeomToken_; + const edm::ESGetToken cscGeomToken_; }; // @@ -108,7 +111,8 @@ class MuonGeometrySanityCheck : public edm::EDAnalyzer { // constructors and destructor // -MuonGeometrySanityCheck::MuonGeometrySanityCheck(const edm::ParameterSet &iConfig) { +MuonGeometrySanityCheck::MuonGeometrySanityCheck(const edm::ParameterSet &iConfig) + : dtGeomToken_(esConsumes()), cscGeomToken_(esConsumes()) { printout = iConfig.getParameter("printout"); if (printout != std::string("all") && printout != std::string("bad")) { throw cms::Exception("BadConfig") << "Printout must be \"all\" or \"bad\"." << std::endl; @@ -580,11 +584,8 @@ std::string MuonGeometrySanityCheckPoint::detName() const { // ------------ method called to for each event ------------ void MuonGeometrySanityCheck::analyze(const edm::Event &iEvent, const edm::EventSetup &iSetup) { - edm::ESHandle dtGeometry; - iSetup.get().get(dtGeometry); - - edm::ESHandle cscGeometry; - iSetup.get().get(cscGeometry); + const DTGeometry *dtGeometry = &iSetup.getData(dtGeomToken_); + const CSCGeometry *cscGeometry = &iSetup.getData(cscGeomToken_); int num_transformed = 0; int num_tested = 0; diff --git a/Alignment/MuonAlignment/src/MuonAlignment.cc b/Alignment/MuonAlignment/src/MuonAlignment.cc index 2458e49befb2b..c858af7398a84 100644 --- a/Alignment/MuonAlignment/src/MuonAlignment.cc +++ b/Alignment/MuonAlignment/src/MuonAlignment.cc @@ -40,21 +40,20 @@ void MuonAlignment::init() { theAlignableNavigator = nullptr; } -MuonAlignment::MuonAlignment(const edm::EventSetup& iSetup) { +MuonAlignment::MuonAlignment(const DTGeometry* dtGeometry, + const CSCGeometry* cscGeometry, + const GEMGeometry* gemGeometry) + : dtGeometry_(dtGeometry), cscGeometry_(cscGeometry), gemGeometry_(gemGeometry) { init(); - edm::ESHandle dtGeometry = iSetup.getHandle(esTokenDT_); - edm::ESHandle cscGeometry = iSetup.getHandle(esTokenCSC_); - edm::ESHandle gemGeometry = iSetup.getHandle(esTokenGEM_); - - theAlignableMuon = new AlignableMuon(&(*dtGeometry), &(*cscGeometry), &(*gemGeometry)); + theAlignableMuon = new AlignableMuon(&*dtGeometry_, &*cscGeometry_, &*gemGeometry_); theAlignableNavigator = new AlignableNavigator(theAlignableMuon); } MuonAlignment::MuonAlignment(const edm::EventSetup& iSetup, const MuonAlignmentInputMethod& input) { init(); - theAlignableMuon = input.newAlignableMuon(iSetup); + theAlignableMuon = input.newAlignableMuon(); theAlignableNavigator = new AlignableNavigator(theAlignableMuon); } @@ -238,8 +237,11 @@ void MuonAlignment::copySurveyToAlignment() { recursiveCopySurveyToAlignment(the //____________________________________________________________________________________ // Code needed to store alignments to DB -void MuonAlignment::writeXML(const edm::ParameterSet& iConfig, const edm::EventSetup& iSetup) { - MuonAlignmentOutputXML(iConfig).write(theAlignableMuon, iSetup); +void MuonAlignment::writeXML(const edm::ParameterSet& iConfig, + const DTGeometry* dtGeometryXML, + const CSCGeometry* cscGeometryXML, + const GEMGeometry* gemGeometryXML) { + MuonAlignmentOutputXML(iConfig, dtGeometryXML, cscGeometryXML, gemGeometryXML).write(theAlignableMuon); } void MuonAlignment::saveDTSurveyToDB(void) { diff --git a/Alignment/MuonAlignment/src/MuonAlignmentInputDB.cc b/Alignment/MuonAlignment/src/MuonAlignmentInputDB.cc index e64b4183ad60b..1986b68bbf6a3 100644 --- a/Alignment/MuonAlignment/src/MuonAlignmentInputDB.cc +++ b/Alignment/MuonAlignment/src/MuonAlignmentInputDB.cc @@ -37,16 +37,42 @@ // // constructors and destructor // -MuonAlignmentInputDB::MuonAlignmentInputDB() - : m_dtLabel(""), m_cscLabel(""), m_gemLabel(""), idealGeometryLabel("idealForInputDB"), m_getAPEs(false) {} - -MuonAlignmentInputDB::MuonAlignmentInputDB( - std::string dtLabel, std::string cscLabel, std::string gemLabel, std::string idealLabel, bool getAPEs) - : m_dtLabel(dtLabel), - m_cscLabel(cscLabel), - m_gemLabel(gemLabel), - idealGeometryLabel(idealLabel), - m_getAPEs(getAPEs) {} +MuonAlignmentInputDB::MuonAlignmentInputDB(const DTGeometry* dtGeometry, + const CSCGeometry* cscGeometry, + const GEMGeometry* gemGeometry, + const Alignments* dtAlignments, + const Alignments* cscAlignments, + const Alignments* gemAlignments, + const Alignments* globalPositionRcd) + : dtGeometry_(dtGeometry), + cscGeometry_(cscGeometry), + gemGeometry_(gemGeometry), + dtAlignments_(dtAlignments), + cscAlignments_(cscAlignments), + gemAlignments_(gemAlignments), + globalPositionRcd_(globalPositionRcd), + m_getAPEs(false) {} +MuonAlignmentInputDB::MuonAlignmentInputDB(const DTGeometry* dtGeometry, + const CSCGeometry* cscGeometry, + const GEMGeometry* gemGeometry, + const Alignments* dtAlignments, + const Alignments* cscAlignments, + const Alignments* gemAlignments, + const Alignments* globalPositionRcd, + const AlignmentErrorsExtended* dtAlignmentErrorsExtended, + const AlignmentErrorsExtended* cscAlignmentErrorsExtended, + const AlignmentErrorsExtended* gemAlignmentErrorsExtended) + : dtGeometry_(dtGeometry), + cscGeometry_(cscGeometry), + gemGeometry_(gemGeometry), + dtAlignments_(dtAlignments), + cscAlignments_(cscAlignments), + gemAlignments_(gemAlignments), + globalPositionRcd_(globalPositionRcd), + dtAlignmentErrorsExtended_(dtAlignmentErrorsExtended), + cscAlignmentErrorsExtended_(cscAlignmentErrorsExtended), + gemAlignmentErrorsExtended_(gemAlignmentErrorsExtended), + m_getAPEs(true) {} // MuonAlignmentInputDB::MuonAlignmentInputDB(const MuonAlignmentInputDB& rhs) // { @@ -71,65 +97,41 @@ MuonAlignmentInputDB::~MuonAlignmentInputDB() {} // member functions // -AlignableMuon* MuonAlignmentInputDB::newAlignableMuon(const edm::EventSetup& iSetup) const { - edm::ESHandle dtGeometry; - edm::ESHandle cscGeometry; - edm::ESHandle gemGeometry; - iSetup.get().get(idealGeometryLabel, dtGeometry); - iSetup.get().get(idealGeometryLabel, cscGeometry); - iSetup.get().get(idealGeometryLabel, gemGeometry); - - edm::ESHandle dtAlignments; - edm::ESHandle dtAlignmentErrorsExtended; - edm::ESHandle cscAlignments; - edm::ESHandle cscAlignmentErrorsExtended; - edm::ESHandle gemAlignments; - edm::ESHandle gemAlignmentErrorsExtended; - edm::ESHandle globalPositionRcd; - - iSetup.get().get(m_dtLabel, dtAlignments); - iSetup.get().get(m_cscLabel, cscAlignments); - iSetup.get().get(m_gemLabel, gemAlignments); - iSetup.get().get(globalPositionRcd); - +AlignableMuon* MuonAlignmentInputDB::newAlignableMuon() const { if (m_getAPEs) { - iSetup.get().get(m_dtLabel, dtAlignmentErrorsExtended); - iSetup.get().get(m_cscLabel, cscAlignmentErrorsExtended); - iSetup.get().get(m_gemLabel, gemAlignmentErrorsExtended); - GeometryAligner aligner; - aligner.applyAlignments(&(*dtGeometry), - &(*dtAlignments), - &(*dtAlignmentErrorsExtended), - align::DetectorGlobalPosition(*globalPositionRcd, DetId(DetId::Muon))); - aligner.applyAlignments(&(*cscGeometry), - &(*cscAlignments), - &(*cscAlignmentErrorsExtended), - align::DetectorGlobalPosition(*globalPositionRcd, DetId(DetId::Muon))); - aligner.applyAlignments(&(*gemGeometry), - &(*gemAlignments), - &(*gemAlignmentErrorsExtended), - align::DetectorGlobalPosition(*globalPositionRcd, DetId(DetId::Muon))); + aligner.applyAlignments(dtGeometry_, + dtAlignments_, + dtAlignmentErrorsExtended_, + align::DetectorGlobalPosition(*globalPositionRcd_, DetId(DetId::Muon))); + aligner.applyAlignments(cscGeometry_, + cscAlignments_, + cscAlignmentErrorsExtended_, + align::DetectorGlobalPosition(*globalPositionRcd_, DetId(DetId::Muon))); + aligner.applyAlignments(gemGeometry_, + gemAlignments_, + gemAlignmentErrorsExtended_, + align::DetectorGlobalPosition(*globalPositionRcd_, DetId(DetId::Muon))); } else { AlignmentErrorsExtended dtAlignmentErrorsExtended2, cscAlignmentErrorsExtended2, gemAlignmentErrorsExtended2; - for (std::vector::const_iterator i = dtAlignments->m_align.begin(); - i != dtAlignments->m_align.end(); + for (std::vector::const_iterator i = dtAlignments_->m_align.begin(); + i != dtAlignments_->m_align.end(); ++i) { CLHEP::HepSymMatrix empty_matrix(3, 0); AlignTransformErrorExtended empty_error(empty_matrix, i->rawId()); dtAlignmentErrorsExtended2.m_alignError.push_back(empty_error); } - for (std::vector::const_iterator i = cscAlignments->m_align.begin(); - i != cscAlignments->m_align.end(); + for (std::vector::const_iterator i = cscAlignments_->m_align.begin(); + i != cscAlignments_->m_align.end(); ++i) { CLHEP::HepSymMatrix empty_matrix(3, 0); AlignTransformErrorExtended empty_error(empty_matrix, i->rawId()); cscAlignmentErrorsExtended2.m_alignError.push_back(empty_error); } - for (std::vector::const_iterator i = gemAlignments->m_align.begin(); - i != gemAlignments->m_align.end(); + for (std::vector::const_iterator i = gemAlignments_->m_align.begin(); + i != gemAlignments_->m_align.end(); ++i) { CLHEP::HepSymMatrix empty_matrix(3, 0); AlignTransformErrorExtended empty_error(empty_matrix, i->rawId()); @@ -137,21 +139,21 @@ AlignableMuon* MuonAlignmentInputDB::newAlignableMuon(const edm::EventSetup& iSe } GeometryAligner aligner; - aligner.applyAlignments(&(*dtGeometry), - &(*dtAlignments), - &(dtAlignmentErrorsExtended2), - align::DetectorGlobalPosition(*globalPositionRcd, DetId(DetId::Muon))); - aligner.applyAlignments(&(*cscGeometry), - &(*cscAlignments), - &(cscAlignmentErrorsExtended2), - align::DetectorGlobalPosition(*globalPositionRcd, DetId(DetId::Muon))); - aligner.applyAlignments(&(*gemGeometry), - &(*gemAlignments), - &(gemAlignmentErrorsExtended2), - align::DetectorGlobalPosition(*globalPositionRcd, DetId(DetId::Muon))); + aligner.applyAlignments(dtGeometry_, + dtAlignments_, + &dtAlignmentErrorsExtended2, + align::DetectorGlobalPosition(*globalPositionRcd_, DetId(DetId::Muon))); + aligner.applyAlignments(cscGeometry_, + cscAlignments_, + &cscAlignmentErrorsExtended2, + align::DetectorGlobalPosition(*globalPositionRcd_, DetId(DetId::Muon))); + aligner.applyAlignments(gemGeometry_, + gemAlignments_, + &gemAlignmentErrorsExtended2, + align::DetectorGlobalPosition(*globalPositionRcd_, DetId(DetId::Muon))); } - return new AlignableMuon(&(*dtGeometry), &(*cscGeometry), &(*gemGeometry)); + return new AlignableMuon(dtGeometry_, cscGeometry_, gemGeometry_); } // diff --git a/Alignment/MuonAlignment/src/MuonAlignmentInputMethod.cc b/Alignment/MuonAlignment/src/MuonAlignmentInputMethod.cc index 903baa50cc933..d087ad67b9b84 100644 --- a/Alignment/MuonAlignment/src/MuonAlignmentInputMethod.cc +++ b/Alignment/MuonAlignment/src/MuonAlignmentInputMethod.cc @@ -33,8 +33,11 @@ // // constructors and destructor // -MuonAlignmentInputMethod::MuonAlignmentInputMethod() : idealGeometryLabel("idealForInputMethod") {} -MuonAlignmentInputMethod::MuonAlignmentInputMethod(std::string idealLabel) : idealGeometryLabel(idealLabel) {} +MuonAlignmentInputMethod::MuonAlignmentInputMethod() {} +MuonAlignmentInputMethod::MuonAlignmentInputMethod(const DTGeometry* dtGeometry, + const CSCGeometry* cscGeometry, + const GEMGeometry* gemGeometry) + : dtGeometry_(dtGeometry), cscGeometry_(cscGeometry), gemGeometry_(gemGeometry) {} // MuonAlignmentInputMethod::MuonAlignmentInputMethod(const MuonAlignmentInputMethod& rhs) // { @@ -59,14 +62,8 @@ MuonAlignmentInputMethod::~MuonAlignmentInputMethod() {} // member functions // -AlignableMuon* MuonAlignmentInputMethod::newAlignableMuon(const edm::EventSetup& iSetup) const { - edm::ESHandle dtGeometry; - edm::ESHandle cscGeometry; - edm::ESHandle gemGeometry; - iSetup.get().get(idealGeometryLabel, dtGeometry); - iSetup.get().get(idealGeometryLabel, cscGeometry); - iSetup.get().get(idealGeometryLabel, gemGeometry); - return new AlignableMuon(&(*dtGeometry), &(*cscGeometry), &(*gemGeometry)); +AlignableMuon* MuonAlignmentInputMethod::newAlignableMuon() const { + return new AlignableMuon(&*dtGeometry_, &*cscGeometry_, &*gemGeometry_); } // diff --git a/Alignment/MuonAlignment/src/MuonAlignmentInputSurveyDB.cc b/Alignment/MuonAlignment/src/MuonAlignmentInputSurveyDB.cc index eb0dacf2e2916..55a6b133b0227 100644 --- a/Alignment/MuonAlignment/src/MuonAlignmentInputSurveyDB.cc +++ b/Alignment/MuonAlignment/src/MuonAlignmentInputSurveyDB.cc @@ -34,18 +34,25 @@ // // constructors and destructor // -MuonAlignmentInputSurveyDB::MuonAlignmentInputSurveyDB() - : m_dtLabel(""), m_cscLabel(""), idealGeometryLabel("idealForInputSurveyDB") {} - -MuonAlignmentInputSurveyDB::MuonAlignmentInputSurveyDB(std::string dtLabel, - std::string cscLabel, - std::string idealLabel) - : m_dtLabel(dtLabel), m_cscLabel(cscLabel), idealGeometryLabel(idealLabel) {} +MuonAlignmentInputSurveyDB::MuonAlignmentInputSurveyDB(const DTGeometry* dtGeometry, + const CSCGeometry* cscGeometry, + const GEMGeometry* gemGeometry, + const Alignments* dtSurvey, + const Alignments* cscSurvey, + const SurveyErrors* dtSurveyError, + const SurveyErrors* cscSurveyError) + : dtGeometry_(dtGeometry), + cscGeometry_(cscGeometry), + gemGeometry_(gemGeometry), + dtSurvey_(dtSurvey), + cscSurvey_(cscSurvey), + dtSurveyError_(dtSurveyError), + cscSurveyError_(cscSurveyError) {} // MuonAlignmentInputSurveyDB::MuonAlignmentInputSurveyDB(const MuonAlignmentInputSurveyDB& rhs) // { // // do actual copying here; -// } +// MuonAlignmentInputSurveyDB::~MuonAlignmentInputSurveyDB() {} @@ -65,36 +72,20 @@ MuonAlignmentInputSurveyDB::~MuonAlignmentInputSurveyDB() {} // member functions // -AlignableMuon* MuonAlignmentInputSurveyDB::newAlignableMuon(const edm::EventSetup& iSetup) const { - edm::ESHandle dtGeometry; - edm::ESHandle cscGeometry; - edm::ESHandle gemGeometry; - iSetup.get().get(idealGeometryLabel, dtGeometry); - iSetup.get().get(idealGeometryLabel, cscGeometry); - iSetup.get().get(idealGeometryLabel, gemGeometry); - - edm::ESHandle dtSurvey; - edm::ESHandle dtSurveyError; - edm::ESHandle cscSurvey; - edm::ESHandle cscSurveyError; - iSetup.get().get(m_dtLabel, dtSurvey); - iSetup.get().get(m_dtLabel, dtSurveyError); - iSetup.get().get(m_cscLabel, cscSurvey); - iSetup.get().get(m_cscLabel, cscSurveyError); - - AlignableMuon* output = new AlignableMuon(&(*dtGeometry), &(*cscGeometry), &(*gemGeometry)); +AlignableMuon* MuonAlignmentInputSurveyDB::newAlignableMuon() const { + AlignableMuon* output = new AlignableMuon(dtGeometry_, cscGeometry_, gemGeometry_); unsigned int theSurveyIndex = 0; - const Alignments* theSurveyValues = &*dtSurvey; - const SurveyErrors* theSurveyErrors = &*dtSurveyError; + const Alignments* theSurveyValues = dtSurvey_; + const SurveyErrors* theSurveyErrors = dtSurveyError_; const auto& barrels = output->DTBarrel(); for (const auto& iter : barrels) { addSurveyInfo_(iter, &theSurveyIndex, theSurveyValues, theSurveyErrors); } theSurveyIndex = 0; - theSurveyValues = &*cscSurvey; - theSurveyErrors = &*cscSurveyError; + theSurveyValues = cscSurvey_; + theSurveyErrors = cscSurveyError_; const auto& endcaps = output->CSCEndcaps(); for (const auto& iter : endcaps) { addSurveyInfo_(iter, &theSurveyIndex, theSurveyValues, theSurveyErrors); diff --git a/Alignment/MuonAlignment/src/MuonAlignmentInputXML.cc b/Alignment/MuonAlignment/src/MuonAlignmentInputXML.cc index 855317c929157..0aa9e0f16ab51 100644 --- a/Alignment/MuonAlignment/src/MuonAlignmentInputXML.cc +++ b/Alignment/MuonAlignment/src/MuonAlignmentInputXML.cc @@ -29,6 +29,7 @@ XERCES_CPP_NAMESPACE_USE #include "Alignment/CommonAlignment/interface/StructureType.h" #include "Alignment/CommonAlignment/interface/AlignableObjectId.h" #include "DataFormats/MuonDetId/interface/CSCDetId.h" +#include "DataFormats/MuonDetId/interface/GEMDetId.h" #include "DataFormats/MuonDetId/interface/DTLayerId.h" #include "Alignment/CommonAlignment/interface/SurveyDet.h" #include "DataFormats/GeometryCommonDetAlgo/interface/AlignmentPositionError.h" @@ -45,8 +46,20 @@ XERCES_CPP_NAMESPACE_USE // // constructors and destructor // -MuonAlignmentInputXML::MuonAlignmentInputXML(const std::string &fileName, std::string idealLabel) - : m_fileName(fileName), idealGeometryLabel(idealLabel) { +MuonAlignmentInputXML::MuonAlignmentInputXML(const std::string &fileName, + const DTGeometry *dtGeometry, + const CSCGeometry *cscGeometry, + const GEMGeometry *gemGeometry, + const DTGeometry *dtGeometryIdeal, + const CSCGeometry *cscGeometryIdeal, + const GEMGeometry *gemGeometryIdeal) + : m_fileName(fileName), + dtGeometry_(dtGeometry), + cscGeometry_(cscGeometry), + gemGeometry_(gemGeometry), + dtGeometryIdeal_(dtGeometryIdeal), + cscGeometryIdeal_(cscGeometryIdeal), + gemGeometryIdeal_(gemGeometryIdeal) { cms::concurrency::xercesInitialize(); str_operation = XMLString::transcode("operation"); str_collection = XMLString::transcode("collection"); @@ -62,6 +75,12 @@ MuonAlignmentInputXML::MuonAlignmentInputXML(const std::string &fileName, std::s str_CSCRing = XMLString::transcode("CSCRing"); str_CSCChamber = XMLString::transcode("CSCChamber"); str_CSCLayer = XMLString::transcode("CSCLayer"); + str_GEMEndcap = XMLString::transcode("GEMEndcap"); + str_GEMStation = XMLString::transcode("GEMStation"); + str_GEMRing = XMLString::transcode("GEMRing"); + str_GEMSuperChamber = XMLString::transcode("GEMSuperChamber"); + str_GEMChamber = XMLString::transcode("GEMChamber"); + str_GEMEtaPartition = XMLString::transcode("GEMEtaPartition"); str_setposition = XMLString::transcode("setposition"); str_setape = XMLString::transcode("setape"); str_setsurveyerr = XMLString::transcode("setsurveyerr"); @@ -80,6 +99,8 @@ MuonAlignmentInputXML::MuonAlignmentInputXML(const std::string &fileName, std::s str_endcap = XMLString::transcode("endcap"); str_ring = XMLString::transcode("ring"); str_chamber = XMLString::transcode("chamber"); + str_superChamber = XMLString::transcode("SuperChamber"); + str_etaPartition = XMLString::transcode("etaPartition"); str_axisx = XMLString::transcode("axisx"); str_axisy = XMLString::transcode("axisy"); str_axisz = XMLString::transcode("axisz"); @@ -141,6 +162,12 @@ MuonAlignmentInputXML::~MuonAlignmentInputXML() { XMLString::release(&str_CSCRing); XMLString::release(&str_CSCChamber); XMLString::release(&str_CSCLayer); + XMLString::release(&str_GEMEndcap); + XMLString::release(&str_GEMStation); + XMLString::release(&str_GEMRing); + XMLString::release(&str_GEMSuperChamber); + XMLString::release(&str_GEMChamber); + XMLString::release(&str_GEMEtaPartition); XMLString::release(&str_setposition); XMLString::release(&str_setape); XMLString::release(&str_setsurveyerr); @@ -159,6 +186,8 @@ MuonAlignmentInputXML::~MuonAlignmentInputXML() { XMLString::release(&str_endcap); XMLString::release(&str_ring); XMLString::release(&str_chamber); + XMLString::release(&str_superChamber); + XMLString::release(&str_etaPartition); XMLString::release(&str_axisx); XMLString::release(&str_axisy); XMLString::release(&str_axisz); @@ -225,7 +254,10 @@ void MuonAlignmentInputXML::recursiveGetId(std::map & (*ali)->alignableObjectId() == align::AlignableDTSuperLayer || (*ali)->alignableObjectId() == align::AlignableDTLayer || (*ali)->alignableObjectId() == align::AlignableCSCChamber || - (*ali)->alignableObjectId() == align::AlignableCSCLayer) { + (*ali)->alignableObjectId() == align::AlignableCSCLayer || + (*ali)->alignableObjectId() == align::AlignableGEMSuperChamber || + (*ali)->alignableObjectId() == align::AlignableGEMChamber || + (*ali)->alignableObjectId() == align::AlignableGEMEtaPartition) { alignableNavigator[(*ali)->geomDetId().rawId()] = *ali; } recursiveGetId(alignableNavigator, (*ali)->components()); @@ -253,23 +285,18 @@ void MuonAlignmentInputXML::fillAliToIdeal(std::map &a } } -AlignableMuon *MuonAlignmentInputXML::newAlignableMuon(const edm::EventSetup &iSetup) const { - edm::ESHandle dtGeometry; - edm::ESHandle cscGeometry; - edm::ESHandle gemGeometry; - iSetup.get().get(idealGeometryLabel, dtGeometry); - iSetup.get().get(idealGeometryLabel, cscGeometry); - iSetup.get().get(idealGeometryLabel, gemGeometry); - - AlignableMuon *alignableMuon = new AlignableMuon(&(*dtGeometry), &(*cscGeometry), &(*gemGeometry)); +AlignableMuon *MuonAlignmentInputXML::newAlignableMuon() const { + AlignableMuon *alignableMuon = new AlignableMuon(dtGeometry_, cscGeometry_, gemGeometry_); std::map alignableNavigator; // real AlignableNavigators don't have const methods recursiveGetId(alignableNavigator, alignableMuon->DTBarrel()); recursiveGetId(alignableNavigator, alignableMuon->CSCEndcaps()); + recursiveGetId(alignableNavigator, alignableMuon->GEMEndcaps()); - AlignableMuon *ideal_alignableMuon = new AlignableMuon(&(*dtGeometry), &(*cscGeometry), &(*gemGeometry)); + AlignableMuon *ideal_alignableMuon = new AlignableMuon(dtGeometryIdeal_, cscGeometryIdeal_, gemGeometryIdeal_); std::map ideal_alignableNavigator; // real AlignableNavigators don't have const methods recursiveGetId(ideal_alignableNavigator, ideal_alignableMuon->DTBarrel()); recursiveGetId(ideal_alignableNavigator, ideal_alignableMuon->CSCEndcaps()); + recursiveGetId(ideal_alignableNavigator, ideal_alignableMuon->GEMEndcaps()); try { cms::concurrency::xercesInitialize(); @@ -304,6 +331,7 @@ AlignableMuon *MuonAlignmentInputXML::newAlignableMuon(const edm::EventSetup &iS std::map alitoideal; fillAliToIdeal(alitoideal, alignableMuon->DTBarrel(), ideal_alignableMuon->DTBarrel()); fillAliToIdeal(alitoideal, alignableMuon->CSCEndcaps(), ideal_alignableMuon->CSCEndcaps()); + fillAliToIdeal(alitoideal, alignableMuon->GEMEndcaps(), ideal_alignableMuon->GEMEndcaps()); const auto &alignableObjectId = alignableMuon->objectIdProvider(); std::map > alicollections; @@ -473,6 +501,18 @@ Alignable *MuonAlignmentInputXML::getNode(std::map &a return getCSCnode(align::AlignableCSCChamber, alignableNavigator, node, alignableObjectId); else if (XMLString::equals(node->getNodeName(), str_CSCLayer)) return getCSCnode(align::AlignableDetUnit, alignableNavigator, node, alignableObjectId); + else if (XMLString::equals(node->getNodeName(), str_GEMEndcap)) + return getGEMnode(align::AlignableGEMEndcap, alignableNavigator, node, alignableObjectId); + else if (XMLString::equals(node->getNodeName(), str_GEMStation)) + return getGEMnode(align::AlignableGEMStation, alignableNavigator, node, alignableObjectId); + else if (XMLString::equals(node->getNodeName(), str_GEMRing)) + return getGEMnode(align::AlignableGEMRing, alignableNavigator, node, alignableObjectId); + else if (XMLString::equals(node->getNodeName(), str_GEMSuperChamber)) + return getGEMnode(align::AlignableGEMSuperChamber, alignableNavigator, node, alignableObjectId); + else if (XMLString::equals(node->getNodeName(), str_GEMChamber)) + return getGEMnode(align::AlignableGEMChamber, alignableNavigator, node, alignableObjectId); + else if (XMLString::equals(node->getNodeName(), str_GEMEtaPartition)) + return getGEMnode(align::AlignableDetUnit, alignableNavigator, node, alignableObjectId); else return nullptr; } @@ -662,6 +702,97 @@ Alignable *MuonAlignmentInputXML::getCSCnode(align::StructureType structureType, return ali; } +Alignable *MuonAlignmentInputXML::getGEMnode(align::StructureType structureType, + std::map &alignableNavigator, + const XERCES_CPP_NAMESPACE::DOMElement *node, + const AlignableObjectId &alignableObjectId) const { + unsigned int rawId; + + DOMAttr *node_rawId = node->getAttributeNode(str_rawId); + if (node_rawId != nullptr) { + try { + rawId = XMLString::parseInt(node_rawId->getValue()); + } catch (const XMLException &toCatch) { + throw cms::Exception("XMLException") << "Value of \"rawId\" must be an integer" << std::endl; + } + } else { + int endcap, station, ring, superChamber, chamber; + endcap = station = ring = superChamber = chamber = 1; + + DOMAttr *node_endcap = node->getAttributeNode(str_endcap); + if (node_endcap == nullptr) + throw cms::Exception("XMLException") << "GEM node is missing required \"endcap\" attribute" << std::endl; + try { + endcap = XMLString::parseInt(node_endcap->getValue()); + } catch (const XMLException &toCatch) { + throw cms::Exception("XMLException") << "Value of \"endcap\" must be an integer" << std::endl; + } + + if (structureType != align::AlignableGEMEndcap) { + DOMAttr *node_station = node->getAttributeNode(str_station); + if (node_station == nullptr) + throw cms::Exception("XMLException") << "GEM node is missing required \"station\" attribute" << std::endl; + try { + station = XMLString::parseInt(node_station->getValue()); + } catch (const XMLException &toCatch) { + throw cms::Exception("XMLException") << "Value of \"station\" must be an integer" << std::endl; + } + + if (structureType != align::AlignableGEMStation) { + DOMAttr *node_ring = node->getAttributeNode(str_ring); + if (node_ring == nullptr) + throw cms::Exception("XMLException") << "GEM node is missing required \"ring\" attribute" << std::endl; + try { + ring = XMLString::parseInt(node_ring->getValue()); + } catch (const XMLException &toCatch) { + throw cms::Exception("XMLException") << "Value of \"ring\" must be an integer" << std::endl; + } + + if (structureType != align::AlignableGEMRing) { + DOMAttr *node_superChamber = node->getAttributeNode(str_chamber); + if (node_superChamber == nullptr) + throw cms::Exception("XMLException") + << "GEM node is missing required \"superChamber\" attribute" << std::endl; + try { + superChamber = XMLString::parseInt(node_superChamber->getValue()); + } catch (const XMLException &toCatch) { + throw cms::Exception("XMLException") << "Value of \"superChamber\" must be an integer" << std::endl; + } + + if (structureType != align::AlignableGEMSuperChamber) { + DOMAttr *node_chamber = node->getAttributeNode(str_chamber); + if (node_chamber == nullptr) + throw cms::Exception("XMLException") << "GEM node is missing required \"chamber\" attribute" << std::endl; + try { + chamber = XMLString::parseInt(node_chamber->getValue()); + } catch (const XMLException &toCatch) { + throw cms::Exception("XMLException") << "Value of \"chamber\" must be an integer" << std::endl; + } + + } // end if we need a layer number + } // end if we need a chamber number + } // end if we need a ring number + } // end if we need a station number + + GEMDetId chamberId(endcap, station, ring, 0, chamber, 0); + rawId = chamberId.rawId(); + } // end if it's specified by endcap, station, ring, chamber, layer + + Alignable *ali = alignableNavigator[rawId]; + if (ali == nullptr) + throw cms::Exception("XMLException") << "rawId \"" << rawId << "\" is not recognized" << std::endl; + + while (ali->alignableObjectId() != structureType) { + ali = ali->mother(); + + if (ali == nullptr) { + throw cms::Exception("XMLException") + << "rawId \"" << rawId << "\" is not a " << alignableObjectId.idToString(structureType) << std::endl; + } + } + return ali; +} + double MuonAlignmentInputXML::parseDouble(const XMLCh *str, const char *attribute) const { unsigned int len = XMLString::stringLen(str); char *cstr = XMLString::transcode(str); diff --git a/Alignment/MuonAlignment/src/MuonAlignmentOutputXML.cc b/Alignment/MuonAlignment/src/MuonAlignmentOutputXML.cc index df148df1efc7e..cdcdd656551a6 100644 --- a/Alignment/MuonAlignment/src/MuonAlignmentOutputXML.cc +++ b/Alignment/MuonAlignment/src/MuonAlignmentOutputXML.cc @@ -39,7 +39,10 @@ // // constructors and destructor // -MuonAlignmentOutputXML::MuonAlignmentOutputXML(const edm::ParameterSet &iConfig) +MuonAlignmentOutputXML::MuonAlignmentOutputXML(const edm::ParameterSet &iConfig, + const DTGeometry *dtGeometry, + const CSCGeometry *cscGeometry, + const GEMGeometry *gemGeometry) : m_fileName(iConfig.getParameter("fileName")), m_survey(iConfig.getParameter("survey")), m_rawIds(iConfig.getParameter("rawIds")), @@ -56,7 +59,15 @@ MuonAlignmentOutputXML::MuonAlignmentOutputXML(const edm::ParameterSet &iConfig) m_suppressCSCRings(iConfig.getUntrackedParameter("suppressCSCRings", false)), m_suppressCSCChambers(iConfig.getUntrackedParameter("suppressCSCChambers", false)), m_suppressCSCLayers(iConfig.getUntrackedParameter("suppressCSCLayers", false)), - idealGeometryLabel("idealForOutputXML") { + m_suppressGEMEndcaps(iConfig.getUntrackedParameter("suppressGEMEndcaps", false)), + m_suppressGEMStations(iConfig.getUntrackedParameter("suppressGEMStations", false)), + m_suppressGEMRings(iConfig.getUntrackedParameter("suppressGEMRings", false)), + m_suppressGEMSuperChambers(iConfig.getUntrackedParameter("suppressGEMSuperChambers", false)), + m_suppressGEMChambers(iConfig.getUntrackedParameter("suppressGEMChambers", false)), + m_suppressGEMEtaPartitions(iConfig.getUntrackedParameter("suppressGEMEtaPartitions", false)), + dtGeometry_(dtGeometry), + cscGeometry_(cscGeometry), + gemGeometry_(gemGeometry) { std::string str_relativeto = iConfig.getParameter("relativeto"); if (str_relativeto == std::string("none")) { @@ -93,7 +104,7 @@ MuonAlignmentOutputXML::~MuonAlignmentOutputXML() {} // member functions // -void MuonAlignmentOutputXML::write(AlignableMuon *alignableMuon, const edm::EventSetup &iSetup) const { +void MuonAlignmentOutputXML::write(AlignableMuon *alignableMuon) const { std::ofstream outputFile(m_fileName.c_str()); outputFile << std::setprecision(m_precision) << std::fixed; @@ -104,6 +115,7 @@ void MuonAlignmentOutputXML::write(AlignableMuon *alignableMuon, const edm::Even std::map errors; AlignmentErrorsExtended *dtErrors = alignableMuon->dtAlignmentErrorsExtended(); AlignmentErrorsExtended *cscErrors = alignableMuon->cscAlignmentErrorsExtended(); + AlignmentErrorsExtended *gemErrors = alignableMuon->gemAlignmentErrorsExtended(); for (std::vector::const_iterator dtError = dtErrors->m_alignError.begin(); dtError != dtErrors->m_alignError.end(); ++dtError) { @@ -114,30 +126,32 @@ void MuonAlignmentOutputXML::write(AlignableMuon *alignableMuon, const edm::Even ++cscError) { errors[cscError->rawId()] = cscError->matrix(); } + for (std::vector::const_iterator gemError = gemErrors->m_alignError.begin(); + gemError != gemErrors->m_alignError.end(); + ++gemError) { + errors[gemError->rawId()] = gemError->matrix(); + } align::Alignables barrels = alignableMuon->DTBarrel(); align::Alignables endcaps = alignableMuon->CSCEndcaps(); + align::Alignables endcaps_GEM = alignableMuon->GEMEndcaps(); if (m_relativeto == 1) { - edm::ESHandle dtGeometry; - edm::ESHandle cscGeometry; - edm::ESHandle gemGeometry; - iSetup.get().get(idealGeometryLabel, dtGeometry); - iSetup.get().get(idealGeometryLabel, cscGeometry); - iSetup.get().get(idealGeometryLabel, gemGeometry); - - AlignableMuon ideal_alignableMuon(&(*dtGeometry), &(*cscGeometry), &(*gemGeometry)); + AlignableMuon ideal_alignableMuon(dtGeometry_, cscGeometry_, gemGeometry_); align::Alignables ideal_barrels = ideal_alignableMuon.DTBarrel(); align::Alignables ideal_endcaps = ideal_alignableMuon.CSCEndcaps(); + align::Alignables ideal_endcaps_GEM = ideal_alignableMuon.GEMEndcaps(); - writeComponents(barrels, ideal_barrels, errors, outputFile, true, alignableMuon->objectIdProvider()); - writeComponents(endcaps, ideal_endcaps, errors, outputFile, false, alignableMuon->objectIdProvider()); + writeComponents(barrels, ideal_barrels, errors, outputFile, doDT, alignableMuon->objectIdProvider()); + writeComponents(endcaps, ideal_endcaps, errors, outputFile, doCSC, alignableMuon->objectIdProvider()); + writeComponents(endcaps_GEM, ideal_endcaps_GEM, errors, outputFile, doGEM, alignableMuon->objectIdProvider()); } else { - align::Alignables empty1, empty2; + align::Alignables empty1, empty2, empty3; - writeComponents(barrels, empty1, errors, outputFile, true, alignableMuon->objectIdProvider()); - writeComponents(endcaps, empty2, errors, outputFile, false, alignableMuon->objectIdProvider()); + writeComponents(barrels, empty1, errors, outputFile, doDT, alignableMuon->objectIdProvider()); + writeComponents(endcaps, empty2, errors, outputFile, doCSC, alignableMuon->objectIdProvider()); + writeComponents(endcaps_GEM, empty3, errors, outputFile, doGEM, alignableMuon->objectIdProvider()); } outputFile << "" << std::endl; @@ -147,13 +161,13 @@ void MuonAlignmentOutputXML::writeComponents(align::Alignables &alignables, align::Alignables &ideals, std::map &errors, std::ofstream &outputFile, - bool DT, + const int doDet, const AlignableObjectId &objectIdProvider) const { align::Alignables::const_iterator ideal = ideals.begin(); for (align::Alignables::const_iterator alignable = alignables.begin(); alignable != alignables.end(); ++alignable) { if (m_survey && (*alignable)->survey() == nullptr) { throw cms::Exception("Alignment") << "SurveyDets must all be defined when writing to XML" << std::endl; - } // now I can assume it's okay everywhere + } align::StructureType alignableObjectId = (*alignable)->alignableObjectId(); @@ -161,17 +175,26 @@ void MuonAlignmentOutputXML::writeComponents(align::Alignables &alignables, (alignableObjectId == align::AlignableDTWheel && !m_suppressDTWheels) || (alignableObjectId == align::AlignableDTStation && !m_suppressDTStations) || (alignableObjectId == align::AlignableDTChamber && !m_suppressDTChambers) || - (DT && alignableObjectId == align::AlignableDTSuperLayer && !m_suppressDTSuperLayers) || - (DT && alignableObjectId == align::AlignableDetUnit && !m_suppressDTLayers) || + (doDet == doDT && alignableObjectId == align::AlignableDTSuperLayer && !m_suppressDTSuperLayers) || + (doDet == doDT && alignableObjectId == align::AlignableDetUnit && !m_suppressDTLayers) || (alignableObjectId == align::AlignableCSCEndcap && !m_suppressCSCEndcaps) || (alignableObjectId == align::AlignableCSCStation && !m_suppressCSCStations) || (alignableObjectId == align::AlignableCSCRing && !m_suppressCSCRings) || (alignableObjectId == align::AlignableCSCChamber && !m_suppressCSCChambers) || - (!DT && alignableObjectId == align::AlignableDetUnit && !m_suppressCSCLayers)) { + (alignableObjectId == align::AlignableGEMEndcap && !m_suppressGEMEndcaps) || + (alignableObjectId == align::AlignableGEMStation && !m_suppressGEMStations) || + (alignableObjectId == align::AlignableGEMRing && !m_suppressGEMRings) || + (alignableObjectId == align::AlignableGEMSuperChamber && !m_suppressGEMSuperChambers) || + (alignableObjectId == align::AlignableGEMChamber && !m_suppressGEMChambers) || + (alignableObjectId == align::AlignableGEMEtaPartition && !m_suppressGEMEtaPartitions) || + (doDet != doDT && doDet != doGEM && doDet == doCSC && alignableObjectId == align::AlignableDetUnit && + !m_suppressCSCLayers) || + (doDet != doDT && doDet != doCSC && doDet == doGEM && alignableObjectId == align::AlignableDetUnit && + !m_suppressGEMEtaPartitions)) { unsigned int rawId = (*alignable)->geomDetId().rawId(); outputFile << "" << std::endl; - if (DT) { + if (doDet == doDT) { if (m_rawIds && rawId != 0) { std::string typeName = objectIdProvider.idToString(alignableObjectId); if (alignableObjectId == align::AlignableDTSuperLayer) @@ -193,9 +216,7 @@ void MuonAlignmentOutputXML::writeComponents(align::Alignables &alignables, DTChamberId id(rawId); outputFile << " " << std::endl; - } - - else { + } else { DTChamberId id((*alignable)->id()); if (alignableObjectId == align::AlignableDTStation) { outputFile << " " @@ -211,7 +232,7 @@ void MuonAlignmentOutputXML::writeComponents(align::Alignables &alignables, } // end if not rawId } // end if DT - else { // CSC + if (doDet == doCSC) { // CSC if (m_rawIds && rawId != 0) { std::string typeName = objectIdProvider.idToString(alignableObjectId); if (alignableObjectId == align::AlignableDetUnit) @@ -244,6 +265,39 @@ void MuonAlignmentOutputXML::writeComponents(align::Alignables &alignables, } // end if not rawId } // end if CSC + if (doDet == doGEM) { // GEM + if (m_rawIds && rawId != 0) { + std::string typeName = objectIdProvider.idToString(alignableObjectId); + if (alignableObjectId == align::AlignableDetUnit) + typeName = std::string("GEMChambers"); + outputFile << " <" << typeName << " rawId=\"" << rawId << "\" />" << std::endl; + } else { + if (alignableObjectId == align::AlignableDetUnit) { + GEMDetId id(rawId); + outputFile << " " << std::endl; + } else if (alignableObjectId == align::AlignableGEMSuperChamber) { + GEMDetId id(rawId); + outputFile << " " << std::endl; + } else { + GEMDetId id((*alignable)->id()); + if (alignableObjectId == align::AlignableGEMRing) { + outputFile << " " << std::endl; + } else if (alignableObjectId == align::AlignableGEMStation) { + outputFile << " " + << std::endl; + } else if (alignableObjectId == align::AlignableGEMEndcap) { + outputFile << " " << std::endl; + } else + throw cms::Exception("Alignment") << "Unknown GEM Alignable StructureType" << std::endl; + } + + } // end if not rawId + } // end if GEM + align::PositionType pos = (*alignable)->globalPosition(); align::RotationType rot = (*alignable)->globalRotation(); @@ -272,7 +326,7 @@ void MuonAlignmentOutputXML::writeComponents(align::Alignables &alignables, str_relativeto = std::string("ideal"); bool csc_debug = false; - if (csc_debug && !DT) { + if (csc_debug && doDet == doCSC) { CSCDetId id(rawId); if (id.endcap() == 1 && id.station() == 1 && id.ring() == 1 && id.chamber() == 33) { std::cout << " investigating " << id << std::endl @@ -325,7 +379,7 @@ void MuonAlignmentOutputXML::writeComponents(align::Alignables &alignables, else { // the angle convention originally used in alignment, also known as "non-standard Euler angles with a Z-Y-X convention" - // this also gets the sign convention right + // // this also gets the sign convention right double phix = atan2(rot.yz(), rot.zz()); double phiy = asin(-rot.xz()); double phiz = atan2(rot.xy(), rot.xx()); @@ -366,14 +420,13 @@ void MuonAlignmentOutputXML::writeComponents(align::Alignables &alignables, if (ideal != ideals.end()) { align::Alignables components = (*alignable)->components(); align::Alignables ideal_components = (*ideal)->components(); - writeComponents(components, ideal_components, errors, outputFile, DT, objectIdProvider); + writeComponents(components, ideal_components, errors, outputFile, doDet, objectIdProvider); ++ideal; // important for synchronization in the "for" loop! } else { align::Alignables components = (*alignable)->components(); align::Alignables dummy; - writeComponents(components, dummy, errors, outputFile, DT, objectIdProvider); + writeComponents(components, dummy, errors, outputFile, doDet, objectIdProvider); } - } // end loop over alignables } diff --git a/Alignment/MuonAlignment/test/MuonGeometryArrange.py b/Alignment/MuonAlignment/test/MuonGeometryArrange.py index dba3cf1182aec..c2395db06fede 100644 --- a/Alignment/MuonAlignment/test/MuonGeometryArrange.py +++ b/Alignment/MuonAlignment/test/MuonGeometryArrange.py @@ -3,70 +3,56 @@ #Ideal geometry process.load("Geometry.CMSCommonData.cmsIdealGeometryXML_cfi") -process.load("Geometry.TrackerNumberingBuilder.trackerNumberingGeometry_cfi") +process.load('Configuration.Geometry.GeometryExtended2021_cff') process.load("Geometry.MuonNumbering.muonNumberingInitialization_cfi") -process.load("Geometry.MuonNumbering.muonGeometryConstants_cff") +process.load("Configuration.StandardSequences.FrontierConditions_GlobalTag_cff") +from Configuration.AlCa.GlobalTag import GlobalTag +process.GlobalTag = GlobalTag(process.GlobalTag, "auto:phase1_2021_design") -process.DTGeometryMuonGeometryArrange1 = cms.ESProducer("DTGeometryESModule", - appendToDataLabel = cms.string('MuonGeometryArrangeLabel1'), - applyAlignment = cms.bool(False), - alignmentsLabel = cms.string(''), - fromDDD = cms.bool(True) -) +import Geometry.DTGeometryBuilder.dtGeometryDB_cfi +import Geometry.CSCGeometryBuilder.cscGeometryDB_cfi +import Geometry.GEMGeometryBuilder.gemGeometryDB_cfi -process.CSCGeometryMuonGeometryArrange1 = cms.ESProducer("CSCGeometryESModule", - appendToDataLabel = cms.string('MuonGeometryArrangeLabel1'), - debugV = cms.untracked.bool(False), - useGangedStripsInME1a = cms.bool(False), - alignmentsLabel = cms.string(''), - useOnlyWiresInME1a = cms.bool(False), - useRealWireGeometry = cms.bool(True), - useCentreTIOffsets = cms.bool(False), - applyAlignment = cms.bool(False), - fromDDD = cms.bool(True), - fromDD4hep = cms.bool(False) -) +process.DTGeometryIdeal = Geometry.DTGeometryBuilder.dtGeometryDB_cfi.DTGeometryESModule.clone() +process.DTGeometryIdeal.appendToDataLabel = 'MuonGeometryArrangeGeomIdeal' +process.DTGeometryIdeal.applyAlignment = cms.bool(False) +process.CSCGeometryIdeal = Geometry.CSCGeometryBuilder.cscGeometryDB_cfi.CSCGeometryESModule.clone() +process.CSCGeometryIdeal.appendToDataLabel = 'MuonGeometryArrangeGeomIdeal' +process.CSCGeometryIdeal.applyAlignment = cms.bool(False) +process.GEMGeometryIdeal = Geometry.GEMGeometryBuilder.gemGeometryDB_cfi.GEMGeometryESModule.clone() +process.GEMGeometryIdeal.appendToDataLabel = 'MuonGeometryArrangeGeomIdeal' +process.GEMGeometryIdeal.applyAlignment = cms.bool(False) -process.DTGeometryMuonGeometryArrange2 = cms.ESProducer("DTGeometryESModule", - appendToDataLabel = cms.string('MuonGeometryArrangeLabel2'), - applyAlignment = cms.bool(False), - alignmentsLabel = cms.string(''), - fromDDD = cms.bool(True) -) - -process.CSCGeometryMuonGeometryArrange2 = cms.ESProducer("CSCGeometryESModule", - appendToDataLabel = cms.string('MuonGeometryArrangeLabel2'), - debugV = cms.untracked.bool(False), - useGangedStripsInME1a = cms.bool(False), - alignmentsLabel = cms.string(''), - useOnlyWiresInME1a = cms.bool(False), - useRealWireGeometry = cms.bool(True), - useCentreTIOffsets = cms.bool(False), - applyAlignment = cms.bool(False), - fromDDD = cms.bool(True), - fromDD4hep = cms.bool(False) -) +process.DTGeometryMuonGeometryArrange1 = Geometry.DTGeometryBuilder.dtGeometryDB_cfi.DTGeometryESModule.clone() +process.DTGeometryMuonGeometryArrange1.appendToDataLabel = 'MuonGeometryArrangeLabel1' +process.DTGeometryMuonGeometryArrange1.applyAlignment = cms.bool(False) +process.CSCGeometryMuonGeometryArrange1 = Geometry.CSCGeometryBuilder.cscGeometryDB_cfi.CSCGeometryESModule.clone() +process.CSCGeometryMuonGeometryArrange1.appendToDataLabel = 'MuonGeometryArrangeLabel1' +process.CSCGeometryMuonGeometryArrange1.applyAlignment = cms.bool(False) +process.GEMGeometryMuonGeometryArrange1 = Geometry.GEMGeometryBuilder.gemGeometryDB_cfi.GEMGeometryESModule.clone() +process.GEMGeometryMuonGeometryArrange1.appendToDataLabel = 'MuonGeometryArrangeLabel1' +process.GEMGeometryMuonGeometryArrange1.applyAlignment = cms.bool(False) -process.DTGeometryMuonGeometryArrange2a = cms.ESProducer("DTGeometryESModule", - appendToDataLabel = cms.string('MuonGeometryArrangeLabel2a'), - applyAlignment = cms.bool(False), - alignmentsLabel = cms.string(''), - fromDDD = cms.bool(True) -) +process.DTGeometryMuonGeometryArrange2 = Geometry.DTGeometryBuilder.dtGeometryDB_cfi.DTGeometryESModule.clone() +process.DTGeometryMuonGeometryArrange2.appendToDataLabel = 'MuonGeometryArrangeLabel2' +process.DTGeometryMuonGeometryArrange2.applyAlignment = cms.bool(False) +process.CSCGeometryMuonGeometryArrange2 = Geometry.CSCGeometryBuilder.cscGeometryDB_cfi.CSCGeometryESModule.clone() +process.CSCGeometryMuonGeometryArrange2.appendToDataLabel = 'MuonGeometryArrangeLabel2' +process.CSCGeometryMuonGeometryArrange2.applyAlignment = cms.bool(False) +process.GEMGeometryMuonGeometryArrange2 = Geometry.GEMGeometryBuilder.gemGeometryDB_cfi.GEMGeometryESModule.clone() +process.GEMGeometryMuonGeometryArrange2.appendToDataLabel = 'MuonGeometryArrangeLabel2' +process.GEMGeometryMuonGeometryArrange2.applyAlignment = cms.bool(False) -process.CSCGeometryMuonGeometryArrange2a = cms.ESProducer("CSCGeometryESModule", - appendToDataLabel = cms.string('MuonGeometryArrangeLabel2a'), - debugV = cms.untracked.bool(False), - useGangedStripsInME1a = cms.bool(False), - alignmentsLabel = cms.string(''), - useOnlyWiresInME1a = cms.bool(False), - useRealWireGeometry = cms.bool(True), - useCentreTIOffsets = cms.bool(False), - applyAlignment = cms.bool(False), - fromDDD = cms.bool(True), - fromDD4hep = cms.bool(False) -) +process.DTGeometryMuonGeometryArrange2a = Geometry.DTGeometryBuilder.dtGeometryDB_cfi.DTGeometryESModule.clone() +process.DTGeometryMuonGeometryArrange2a.appendToDataLabel = 'MuonGeometryArrangeLabel2a' +process.DTGeometryMuonGeometryArrange2a.applyAlignment = cms.bool(False) +process.CSCGeometryMuonGeometryArrange2a = Geometry.CSCGeometryBuilder.cscGeometryDB_cfi.CSCGeometryESModule.clone() +process.CSCGeometryMuonGeometryArrange2a.appendToDataLabel = 'MuonGeometryArrangeLabel2a' +process.CSCGeometryMuonGeometryArrange2a.applyAlignment = cms.bool(False) +process.GEMGeometryMuonGeometryArrange2a = Geometry.GEMGeometryBuilder.gemGeometryDB_cfi.GEMGeometryESModule.clone() +process.GEMGeometryMuonGeometryArrange2a.appendToDataLabel = 'MuonGeometryArrangeLabel2a' +process.GEMGeometryMuonGeometryArrange2a.applyAlignment = cms.bool(False) process.MessageLogger = cms.Service("MessageLogger", cerr = cms.untracked.PSet( @@ -117,7 +103,4 @@ ) process.p = cms.Path( process.MuonGeometryCompare ) - - - diff --git a/Alignment/MuonAlignment/test/TestAlign.cpp b/Alignment/MuonAlignment/test/TestAlign.cpp deleted file mode 100644 index 9261be996bd66..0000000000000 --- a/Alignment/MuonAlignment/test/TestAlign.cpp +++ /dev/null @@ -1,95 +0,0 @@ -// -*- C++ -*- -// -// Package: TestAlign -// Class: TestAlign -// -// -// Description: Module to test the Alignment software -// -// -// system include files -#include - -// user include files -#include "FWCore/MessageLogger/interface/MessageLogger.h" -#include "FWCore/Framework/interface/EDAnalyzer.h" - -#include "FWCore/Framework/interface/MakerMacros.h" - -#include "Alignment/MuonAlignment/interface/MuonAlignment.h" -#include "Alignment/MuonAlignment/interface/AlignableMuon.h" - -#include "DataFormats/GeometrySurface/interface/Surface.h" - -#include - -// -// -// class declaration -// - -class TestAlign : public edm::EDAnalyzer { -public: - explicit TestAlign(const edm::ParameterSet&); - - virtual ~TestAlign(); - - virtual void analyze(const edm::Event&, const edm::EventSetup&); - -private: - //typedef Surface::RotationType RotationType; - //typedef Surface::PositionType PositionType; -}; - -// -// constructors and destructor -// -TestAlign::TestAlign(const edm::ParameterSet& iConfig) { edm::LogInfo("MuonAlignment") << "Starting!"; } - -TestAlign::~TestAlign() { edm::LogInfo("MuonAlignment") << "Ending!"; } - -void TestAlign::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) { - // Instantiate the helper class - MuonAlignment align(iSetup); - - // Get the AlignableMuon pointer - AlignableMuon* theAlignableMuon = align.getAlignableMuon(); - - // Apply alignment - std::vector displacement; - displacement.push_back(1.0); - displacement.push_back(0.0); - displacement.push_back(0.0); - - std::vector rotation; - rotation.push_back(0.0); - rotation.push_back(0.0); - rotation.push_back(1.64); - - // Loop over DT chamber to apply alignment corrections - for (const auto& iter : theAlignableMuon->DTChambers()) { - // Print inital position/orientation - align::GlobalPoint pos_i = iter->globalPosition(); - align::RotationType dir_i = iter->globalRotation(); - - std::cout << "Initial pos: x=" << pos_i.x() << ", y=" << pos_i.y() << ", z=" << pos_i.z() << std::endl; - std::cout << "Initial ori: x=" << dir_i.xx() << ", y=" << dir_i.yy() << ", z=" << dir_i.zz() << std::endl; - - // Move DT chamber - DetId detid = iter->geomDetId(); - align.moveAlignableGlobalCoord(detid, displacement, rotation); - - // Print final position/orientation - align::GlobalPoint pos_f = iter->globalPosition(); - align::RotationType dir_f = iter->globalRotation(); - - std::cout << "Final pos: x=" << pos_f.x() << ", y=" << pos_f.y() << ", z=" << pos_f.z() << std::endl; - std::cout << "Final ori: x=" << dir_f.xx() << ", y=" << dir_f.yy() << ", z=" << dir_f.zz() << std::endl; - std::cout << "------------------------" << std::endl; - } - - // Saves to DB - // align.saveToDB(); -} -//define this as a plug-in -DEFINE_FWK_MODULE(TestAlign); diff --git a/Alignment/MuonAlignment/test/convertSQLitetoXML_cfg.py b/Alignment/MuonAlignment/test/convertSQLitetoXML_cfg.py index 3a3ac8ee39380..0059151a8f986 100644 --- a/Alignment/MuonAlignment/test/convertSQLitetoXML_cfg.py +++ b/Alignment/MuonAlignment/test/convertSQLitetoXML_cfg.py @@ -31,7 +31,7 @@ process.GEMGeometryAlInputDB = cms.ESProducer("GEMGeometryESModule", appendToDataLabel = cms.string('idealForInputDB'), fromDDD = cms.bool(True), - fromDD4Hep = cms.bool(False), + fromDD4hep = cms.bool(False), alignmentsLabel = cms.string(''), applyAlignment = cms.bool(False) ) @@ -59,7 +59,7 @@ process.GEMGeometryAlOutputXML = cms.ESProducer("GEMGeometryESModule", appendToDataLabel = cms.string('idealForOutputXML'), fromDDD = cms.bool(True), - fromDD4Hep = cms.bool(False), + fromDD4hep = cms.bool(False), alignmentsLabel = cms.string(''), applyAlignment = cms.bool(False) ) diff --git a/Alignment/MuonAlignment/test/muonGeometryDBConverter_cfg.py b/Alignment/MuonAlignment/test/muonGeometryDBConverter_cfg.py index c3aa0073be6eb..b5add71845553 100644 --- a/Alignment/MuonAlignment/test/muonGeometryDBConverter_cfg.py +++ b/Alignment/MuonAlignment/test/muonGeometryDBConverter_cfg.py @@ -34,124 +34,38 @@ process.load("Configuration.StandardSequences.FrontierConditions_GlobalTag_cff") process.load("Alignment.MuonAlignment.muonGeometryDBConverter_cfi") -process.DTGeometryAlInputMethod = cms.ESProducer("DTGeometryESModule", - appendToDataLabel = cms.string('idealForInputMethod'), - applyAlignment = cms.bool(False), - alignmentsLabel = cms.string(''), - fromDDD = cms.bool(True) -) - -process.CSCGeometryAlInputMethod = cms.ESProducer("CSCGeometryESModule", - appendToDataLabel = cms.string('idealForInputMethod'), - debugV = cms.untracked.bool(False), - useGangedStripsInME1a = cms.bool(False), - alignmentsLabel = cms.string(''), - useOnlyWiresInME1a = cms.bool(False), - useRealWireGeometry = cms.bool(True), - useCentreTIOffsets = cms.bool(False), - applyAlignment = cms.bool(False), - fromDDD = cms.bool(True), - fromDD4hep = cms.bool(False) -) - -process.GEMGeometryAlInputMethod = cms.ESProducer("GEMGeometryESModule", - appendToDataLabel = cms.string('idealForInputMethod'), - fromDDD = cms.bool(True), - fromDD4Hep = cms.bool(False), - alignmentsLabel = cms.string(''), - applyAlignment = cms.bool(False) -) - -process.DTGeometryAlInputDB = cms.ESProducer("DTGeometryESModule", - appendToDataLabel = cms.string('idealForInputDB'), - applyAlignment = cms.bool(False), - alignmentsLabel = cms.string(''), - fromDDD = cms.bool(True) -) - -process.CSCGeometryAlInputDB = cms.ESProducer("CSCGeometryESModule", - appendToDataLabel = cms.string('idealForInputDB'), - debugV = cms.untracked.bool(False), - useGangedStripsInME1a = cms.bool(False), - alignmentsLabel = cms.string(''), - useOnlyWiresInME1a = cms.bool(False), - useRealWireGeometry = cms.bool(True), - useCentreTIOffsets = cms.bool(False), - applyAlignment = cms.bool(False), - fromDDD = cms.bool(True), - fromDD4hep = cms.bool(False) -) - -process.GEMGeometryAlInputDB = cms.ESProducer("GEMGeometryESModule", - appendToDataLabel = cms.string('idealForInputDB'), - fromDDD = cms.bool(True), - fromDD4Hep = cms.bool(False), - alignmentsLabel = cms.string(''), - applyAlignment = cms.bool(False) -) - -process.DTGeometryAlOutputXML = cms.ESProducer("DTGeometryESModule", - appendToDataLabel = cms.string('idealForOutputXML'), - applyAlignment = cms.bool(False), - alignmentsLabel = cms.string(''), - fromDDD = cms.bool(True) -) - -process.CSCGeometryAlOutputXML = cms.ESProducer("CSCGeometryESModule", - appendToDataLabel = cms.string('idealForOutputXML'), - debugV = cms.untracked.bool(False), - useGangedStripsInME1a = cms.bool(False), - alignmentsLabel = cms.string(''), - useOnlyWiresInME1a = cms.bool(False), - useRealWireGeometry = cms.bool(True), - useCentreTIOffsets = cms.bool(False), - applyAlignment = cms.bool(False), - fromDDD = cms.bool(True), - fromDD4hep = cms.bool(False) -) - -process.GEMGeometryAlOutputXML = cms.ESProducer("GEMGeometryESModule", - appendToDataLabel = cms.string('idealForOutputXML'), - fromDDD = cms.bool(True), - fromDD4Hep = cms.bool(False), - alignmentsLabel = cms.string(''), - applyAlignment = cms.bool(False) -) - -process.DTGeometryAlInputXML = cms.ESProducer("DTGeometryESModule", - appendToDataLabel = cms.string('idealForInputXML'), - applyAlignment = cms.bool(False), - alignmentsLabel = cms.string(''), - fromDDD = cms.bool(True) -) - -process.CSCGeometryAlInputXML = cms.ESProducer("CSCGeometryESModule", - appendToDataLabel = cms.string('idealForInputXML'), - debugV = cms.untracked.bool(False), - useGangedStripsInME1a = cms.bool(False), - alignmentsLabel = cms.string(''), - useOnlyWiresInME1a = cms.bool(False), - useRealWireGeometry = cms.bool(True), - useCentreTIOffsets = cms.bool(False), - applyAlignment = cms.bool(False), - fromDDD = cms.bool(True), - fromDD4hep = cms.bool(False) -) - -process.GEMGeometryAlInputXML = cms.ESProducer("GEMGeometryESModule", - appendToDataLabel = cms.string('idealForInputXML'), - fromDDD = cms.bool(True), - fromDD4Hep = cms.bool(False), - alignmentsLabel = cms.string(''), - applyAlignment = cms.bool(False) -) ################################################################################ # parameters to configure: from Configuration.AlCa.GlobalTag import GlobalTag -process.GlobalTag = GlobalTag(process.GlobalTag, "auto:phase1_2017_design") +process.GlobalTag = GlobalTag(process.GlobalTag, "auto:phase1_2021_design") process.muonGeometryDBConverter.input = options.input process.muonGeometryDBConverter.output = options.output + +import Geometry.DTGeometryBuilder.dtGeometryDB_cfi +import Geometry.CSCGeometryBuilder.cscGeometryDB_cfi +import Geometry.GEMGeometryBuilder.gemGeometryDB_cfi +process.DTGeometryIdeal = Geometry.DTGeometryBuilder.dtGeometryDB_cfi.DTGeometryESModule.clone() +process.DTGeometryIdeal.appendToDataLabel = 'idealGeometry' +process.DTGeometryIdeal.applyAlignment = cms.bool(False) +process.CSCGeometryIdeal = Geometry.CSCGeometryBuilder.cscGeometryDB_cfi.CSCGeometryESModule.clone() +process.CSCGeometryIdeal.appendToDataLabel = 'idealGeometry' +process.CSCGeometryIdeal.applyAlignment = cms.bool(False) +process.GEMGeometryIdeal = Geometry.GEMGeometryBuilder.gemGeometryDB_cfi.GEMGeometryESModule.clone() +process.GEMGeometryIdeal.appendToDataLabel = 'idealGeometry' +process.GEMGeometryIdeal.applyAlignment = cms.bool(False) + +process.DTGeometryIdealForInputXML = Geometry.DTGeometryBuilder.dtGeometryDB_cfi.DTGeometryESModule.clone() +process.DTGeometryIdealForInputXML.appendToDataLabel = 'idealForInputXML' +process.DTGeometryIdealForInputXML.applyAlignment = cms.bool(False) +process.CSCGeometryIdealForInputXML = Geometry.CSCGeometryBuilder.cscGeometryDB_cfi.CSCGeometryESModule.clone() +process.CSCGeometryIdealForInputXML.appendToDataLabel = 'idealForInputXML' +process.CSCGeometryIdealForInputXML.applyAlignment = cms.bool(False) +process.GEMGeometryIdealForInputXML = Geometry.GEMGeometryBuilder.gemGeometryDB_cfi.GEMGeometryESModule.clone() +process.GEMGeometryIdealForInputXML.appendToDataLabel = 'idealForInputXML' +process.GEMGeometryIdealForInputXML.applyAlignment = cms.bool(False) + + if options.input == "db": process.GlobalTag.toGet.extend( [cms.PSet(connect = cms.string("sqlite_file:"+options.inputFile), @@ -177,26 +91,36 @@ process.muonGeometryDBConverter.fileName = options.inputFile if options.output == "db": - from CondCore.CondDB.CondDB_cfi import CondDB - process.PoolDBOutputService = cms.Service( - "PoolDBOutputService", - CondDB, - toPut = cms.VPSet( - cms.PSet(record = cms.string("DTAlignmentRcd"), - tag = cms.string("DTAlignmentRcd")), - cms.PSet(record = cms.string("DTAlignmentErrorExtendedRcd"), - tag = cms.string("DTAlignmentErrorExtendedRcd")), - cms.PSet(record = cms.string("CSCAlignmentRcd"), - tag = cms.string("CSCAlignmentRcd")), - cms.PSet(record = cms.string("CSCAlignmentErrorExtendedRcd"), - tag = cms.string("CSCAlignmentErrorExtendedRcd")), - cms.PSet(record = cms.string("GEMAlignmentRcd"), - tag = cms.string("GEMAlignmentRcd")), - cms.PSet(record = cms.string("GEMAlignmentErrorExtendedRcd"), - tag = cms.string("GEMAlignmentErrorExtendedRcd")) - ) + from CondCore.DBCommon.CondDBSetup_cfi import CondDBSetup + process.PoolDBOutputService = cms.Service("PoolDBOutputService", + CondDBSetup, + toPut = cms.VPSet(cms.PSet( + record = cms.string('DTAlignmentRcd'), + tag = cms.string('DTAlignmentRcd') + ), + cms.PSet( + record = cms.string('DTAlignmentErrorExtendedRcd'), + tag = cms.string('DTAlignmentErrorExtendedRcd') + ), + cms.PSet( + record = cms.string('CSCAlignmentRcd'), + tag = cms.string('CSCAlignmentRcd') + ), + cms.PSet( + record = cms.string('CSCAlignmentErrorExtendedRcd'), + tag = cms.string('CSCAlignmentErrorExtendedRcd') + ), + cms.PSet( + record = cms.string('GEMAlignmentRcd'), + tag = cms.string('GEMAlignmentRcd') + ), + cms.PSet( + record = cms.string('GEMAlignmentErrorExtendedRcd'), + tag = cms.string('GEMAlignmentErrorExtendedRcd') + )), + + connect = cms.string('sqlite_file:'+options.outputFile) ) - process.PoolDBOutputService.connect = "sqlite_file:"+options.outputFile elif options.output == "xml": process.muonGeometryDBConverter.outputXML.fileName = options.outputFile process.muonGeometryDBConverter.outputXML.suppressDTSuperLayers = True diff --git a/Alignment/MuonAlignment/test/test-misalign_cfg.py b/Alignment/MuonAlignment/test/test-misalign_cfg.py index 89ca87c3b2824..f114d8a21fdf1 100644 --- a/Alignment/MuonAlignment/test/test-misalign_cfg.py +++ b/Alignment/MuonAlignment/test/test-misalign_cfg.py @@ -49,7 +49,7 @@ process.GEMGeometryMisalignedMuonProducer = cms.ESProducer("GEMGeometryESModule", appendToDataLabel = cms.string('idealForMuonMisalignedProducer'), fromDDD = cms.bool(True), - fromDD4Hep = cms.bool(False), + fromDD4hep = cms.bool(False), alignmentsLabel = cms.string(''), applyAlignment = cms.bool(False) ) diff --git a/Alignment/MuonAlignment/test/test_MuonGeometryDBConverter.sh b/Alignment/MuonAlignment/test/test_MuonGeometryDBConverter.sh index 6812688034544..f7144de166356 100755 --- a/Alignment/MuonAlignment/test/test_MuonGeometryDBConverter.sh +++ b/Alignment/MuonAlignment/test/test_MuonGeometryDBConverter.sh @@ -18,6 +18,5 @@ mkdir -p ${TEST_DIR} check_for_success cmsRun ${TEST_CFG} input=ideal output=db outputFile=${TEST_DIR}/ideal.db check_for_success cmsRun ${TEST_CFG} input=db output=xml inputFile=${TEST_DIR}/ideal.db outputFile=${TEST_DIR}/ideal.xml -check_for_success cmsRun ${TEST_CFG} input=xml output=none inputFile=${TEST_DIR}/ideal.xml - +check_for_success cmsRun ${TEST_CFG} input=xml output=db inputFile=${TEST_DIR}/ideal.xml outputFile=${TEST_DIR}/idealXML.db clean_up diff --git a/Alignment/MuonAlignmentAlgorithms/interface/MuonResidualsFromTrack.h b/Alignment/MuonAlignmentAlgorithms/interface/MuonResidualsFromTrack.h index 686e6341ba1d5..d3461ac33a3b7 100644 --- a/Alignment/MuonAlignmentAlgorithms/interface/MuonResidualsFromTrack.h +++ b/Alignment/MuonAlignmentAlgorithms/interface/MuonResidualsFromTrack.h @@ -51,8 +51,11 @@ class MuonResidualsFromTrack { public: + using BuilderToken = edm::ESGetToken; + static edm::ESInputTag builderESInputTag(); + // residuals from global muon trajectories - MuonResidualsFromTrack(const edm::EventSetup &iSetup, + MuonResidualsFromTrack(edm::ESHandle builder, edm::ESHandle magneticField, edm::ESHandle globalGeometry, edm::ESHandle muonDetIdAssociator_, diff --git a/Alignment/MuonAlignmentAlgorithms/interface/SegmentToTrackAssociator.h b/Alignment/MuonAlignmentAlgorithms/interface/SegmentToTrackAssociator.h index 88072b833d85b..f929407b367a0 100644 --- a/Alignment/MuonAlignmentAlgorithms/interface/SegmentToTrackAssociator.h +++ b/Alignment/MuonAlignmentAlgorithms/interface/SegmentToTrackAssociator.h @@ -19,6 +19,8 @@ #include "RecoMuon/TransientTrackingRecHit/interface/MuonTransientTrackingRecHit.h" #include "DataFormats/TrackReco/interface/TrackFwd.h" #include "DataFormats/TrackReco/interface/Track.h" +#include "Geometry/Records/interface/GlobalTrackingGeometryRecord.h" +#include "Geometry/CommonDetUnit/interface/GlobalTrackingGeometry.h" namespace edm { class ParameterSet; @@ -31,7 +33,7 @@ class SegmentToTrackAssociator { typedef std::vector > intDVector; //constructor - SegmentToTrackAssociator(const edm::ParameterSet&); + SegmentToTrackAssociator(const edm::ParameterSet&, const GlobalTrackingGeometry* GlobalTrackingGeometry); //destructor virtual ~SegmentToTrackAssociator(); @@ -51,6 +53,8 @@ class SegmentToTrackAssociator { edm::InputTag theDTSegmentLabel; edm::InputTag theCSCSegmentLabel; + + const GlobalTrackingGeometry* globalTrackingGeometry_; }; #endif diff --git a/Alignment/MuonAlignmentAlgorithms/plugins/CSCOverlapsAlignmentAlgorithm.cc b/Alignment/MuonAlignmentAlgorithms/plugins/CSCOverlapsAlignmentAlgorithm.cc index 0667893937ac8..3b7c793ada5ba 100644 --- a/Alignment/MuonAlignmentAlgorithms/plugins/CSCOverlapsAlignmentAlgorithm.cc +++ b/Alignment/MuonAlignmentAlgorithms/plugins/CSCOverlapsAlignmentAlgorithm.cc @@ -55,7 +55,7 @@ CSCOverlapsAlignmentAlgorithm::CSCOverlapsAlignmentAlgorithm(const edm::Paramete } if (m_slopeFromTrackRefit) { - m_trackTransformer = new TrackTransformer(iConfig.getParameter("TrackTransformer")); + m_trackTransformer = new TrackTransformer(iConfig.getParameter("TrackTransformer"), iC); } else { m_trackTransformer = nullptr; } diff --git a/Alignment/MuonAlignmentAlgorithms/plugins/CSCOverlapsTrackPreparation.cc b/Alignment/MuonAlignmentAlgorithms/plugins/CSCOverlapsTrackPreparation.cc index 15fa7ffd608f7..88f21ed574ce2 100644 --- a/Alignment/MuonAlignmentAlgorithms/plugins/CSCOverlapsTrackPreparation.cc +++ b/Alignment/MuonAlignmentAlgorithms/plugins/CSCOverlapsTrackPreparation.cc @@ -22,7 +22,7 @@ // user include files #include "FWCore/Framework/interface/Frameworkfwd.h" -#include "FWCore/Framework/interface/EDProducer.h" +#include "FWCore/Framework/interface/one/EDProducer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/EventSetup.h" #include "FWCore/Framework/interface/ESHandle.h" @@ -59,7 +59,7 @@ // class decleration // -class CSCOverlapsTrackPreparation : public edm::EDProducer { +class CSCOverlapsTrackPreparation : public edm::one::EDProducer<> { public: explicit CSCOverlapsTrackPreparation(const edm::ParameterSet&); ~CSCOverlapsTrackPreparation() override; @@ -73,6 +73,10 @@ class CSCOverlapsTrackPreparation : public edm::EDProducer { // ----------member data --------------------------- edm::InputTag m_src; + + const edm::ESGetToken cscGeomToken_; + const edm::ESGetToken magneticFieldToken_; + const edm::ESGetToken globalGeomToken_; }; // @@ -87,7 +91,10 @@ class CSCOverlapsTrackPreparation : public edm::EDProducer { // constructors and destructor // CSCOverlapsTrackPreparation::CSCOverlapsTrackPreparation(const edm::ParameterSet& iConfig) - : m_src(iConfig.getParameter("src")) { + : m_src(iConfig.getParameter("src")), + cscGeomToken_(esConsumes()), + magneticFieldToken_(esConsumes()), + globalGeomToken_(esConsumes()) { produces>(); produces(); } @@ -106,14 +113,9 @@ void CSCOverlapsTrackPreparation::produce(edm::Event& iEvent, const edm::EventSe edm::Handle tracks; iEvent.getByLabel(m_src, tracks); - edm::ESHandle cscGeometry; - iSetup.get().get(cscGeometry); - - edm::ESHandle magneticField; - iSetup.get().get(magneticField); - - edm::ESHandle globalGeometry; - iSetup.get().get(globalGeometry); + const CSCGeometry* cscGeometry = &iSetup.getData(cscGeomToken_); + const MagneticField* magneticField = &iSetup.getData(magneticFieldToken_); + const GlobalTrackingGeometry* globalGeometry = &iSetup.getData(globalGeomToken_); MuonTransientTrackingRecHitBuilder muonTransBuilder; diff --git a/Alignment/MuonAlignmentAlgorithms/plugins/MuonAlignmentFromReference.cc b/Alignment/MuonAlignmentAlgorithms/plugins/MuonAlignmentFromReference.cc index 1aa072191e10d..55e8b092b9fe4 100644 --- a/Alignment/MuonAlignmentAlgorithms/plugins/MuonAlignmentFromReference.cc +++ b/Alignment/MuonAlignmentAlgorithms/plugins/MuonAlignmentFromReference.cc @@ -116,6 +116,7 @@ class MuonAlignmentFromReference : public AlignmentAlgorithmBase { const edm::ESGetToken m_MagFieldToken; const edm::ESGetToken m_propToken; const edm::ESGetToken m_DetIdToken; + const MuonResidualsFromTrack::BuilderToken m_builderToken; // configutarion paramenters: edm::InputTag m_muonCollectionTag; @@ -199,6 +200,7 @@ MuonAlignmentFromReference::MuonAlignmentFromReference(const edm::ParameterSet& m_MagFieldToken(iC.esConsumes()), m_propToken(iC.esConsumes(edm::ESInputTag("", "SteppingHelixPropagatorAny"))), m_DetIdToken(iC.esConsumes(edm::ESInputTag("", "MuonDetIdAssociator"))), + m_builderToken(iC.esConsumes(MuonResidualsFromTrack::builderESInputTag())), m_muonCollectionTag(cfg.getParameter("muonCollectionTag")), m_reference(cfg.getParameter >("reference")), m_minTrackPt(cfg.getParameter("minTrackPt")), @@ -445,6 +447,7 @@ void MuonAlignmentFromReference::run(const edm::EventSetup& iSetup, const EventI const MagneticField* magneticField = &iSetup.getData(m_MagFieldToken); const Propagator* prop = &iSetup.getData(m_propToken); const DetIdAssociator* muonDetIdAssociator = &iSetup.getData(m_DetIdToken); + auto builder = iSetup.getHandle(m_builderToken); if (m_muonCollectionTag.label().empty()) // use trajectories { @@ -468,7 +471,7 @@ void MuonAlignmentFromReference::run(const edm::EventSetup& iSetup, const EventI m_counter_trackdxy++; if (m_debug) std::cout << "JUST BEFORE muonResidualsFromTrack" << std::endl; - MuonResidualsFromTrack muonResidualsFromTrack(iSetup, + MuonResidualsFromTrack muonResidualsFromTrack(builder, magneticField, globalGeometry, muonDetIdAssociator, diff --git a/Alignment/MuonAlignmentAlgorithms/src/MuonResidualsFromTrack.cc b/Alignment/MuonAlignmentAlgorithms/src/MuonResidualsFromTrack.cc index d845e80d2f81a..ea2d098795c1e 100644 --- a/Alignment/MuonAlignmentAlgorithms/src/MuonResidualsFromTrack.cc +++ b/Alignment/MuonAlignmentAlgorithms/src/MuonResidualsFromTrack.cc @@ -19,7 +19,9 @@ #include "TDecompChol.h" #include -MuonResidualsFromTrack::MuonResidualsFromTrack(const edm::EventSetup& iSetup, +edm::ESInputTag MuonResidualsFromTrack::builderESInputTag() { return edm::ESInputTag("", "WithTrackAngle"); } + +MuonResidualsFromTrack::MuonResidualsFromTrack(edm::ESHandle trackerRecHitBuilder, edm::ESHandle magneticField, edm::ESHandle globalGeometry, edm::ESHandle muonDetIdAssociator_, @@ -39,8 +41,6 @@ MuonResidualsFromTrack::MuonResidualsFromTrack(const edm::EventSetup& iSetup, clear(); - edm::ESHandle theTrackerRecHitBuilder; - iSetup.get().get("WithTrackAngle", theTrackerRecHitBuilder); reco::TransientTrack track(*m_recoTrack, &*magneticField, globalGeometry); TransientTrackingRecHit::ConstRecHitContainer recHitsForRefit; int iT = 0, iM = 0; @@ -52,7 +52,7 @@ MuonResidualsFromTrack::MuonResidualsFromTrack(const edm::EventSetup& iSetup, if (m_debug) std::cout << "Tracker Hit " << iT << " is found. Add to refit. Dimension: " << hit->dimension() << std::endl; - recHitsForRefit.push_back(theTrackerRecHitBuilder->build(&*hit)); + recHitsForRefit.push_back(trackerRecHitBuilder->build(&*hit)); } else if (hitId.det() == DetId::Muon) { // if ( hit->geographicalId().subdetId() == 3 && !theRPCInTheFit ) { // LogTrace("Reco|TrackingTools|TrackTransformer") << "RPC Rec Hit discarged"; diff --git a/Alignment/MuonAlignmentAlgorithms/src/SegmentToTrackAssociator.cc b/Alignment/MuonAlignmentAlgorithms/src/SegmentToTrackAssociator.cc index 5c93ae36a0434..906d12d461b2b 100644 --- a/Alignment/MuonAlignmentAlgorithms/src/SegmentToTrackAssociator.cc +++ b/Alignment/MuonAlignmentAlgorithms/src/SegmentToTrackAssociator.cc @@ -32,7 +32,9 @@ #include -SegmentToTrackAssociator::SegmentToTrackAssociator(const edm::ParameterSet& iConfig) { +SegmentToTrackAssociator::SegmentToTrackAssociator(const edm::ParameterSet& iConfig, + const GlobalTrackingGeometry* GlobalTrackingGeometry) + : globalTrackingGeometry_(GlobalTrackingGeometry) { theDTSegmentLabel = iConfig.getParameter("segmentsDT"); theCSCSegmentLabel = iConfig.getParameter("segmentsCSC"); } @@ -55,9 +57,6 @@ MuonTransientTrackingRecHit::MuonRecHitContainer SegmentToTrackAssociator::assoc edm::Handle CSCSegments; iEvent.getByLabel(theCSCSegmentLabel, CSCSegments); - edm::ESHandle theTrackingGeometry; - iSetup.get().get(theTrackingGeometry); - MuonTransientTrackingRecHit::MuonRecHitContainer SelectedSegments; DTRecSegment4DCollection::const_iterator segmentDT; @@ -72,7 +71,7 @@ MuonTransientTrackingRecHit::MuonRecHitContainer SegmentToTrackAssociator::assoc TrackingRecHitRef myRef = track.recHit(counter); const TrackingRecHit* rechit = myRef.get(); - const GeomDet* geomDet = theTrackingGeometry->idToDet(rechit->geographicalId()); + const GeomDet* geomDet = globalTrackingGeometry_->idToDet(rechit->geographicalId()); //It's a DT Hit if (geomDet->subDetector() == GeomDetEnumerators::DT) { @@ -113,7 +112,7 @@ MuonTransientTrackingRecHit::MuonRecHitContainer SegmentToTrackAssociator::assoc myLayer.sector() == myChamber.sector()) { //push position of the segment and tracking rechit positionDT.push_back(NumberOfDTSegment); - const GeomDet* DTgeomDet = theTrackingGeometry->idToDet(myChamber); + const GeomDet* DTgeomDet = globalTrackingGeometry_->idToDet(myChamber); SelectedSegments.push_back( MuonTransientTrackingRecHit::specificBuild(DTgeomDet, (TrackingRecHit*)&*segmentDT)); @@ -158,7 +157,7 @@ MuonTransientTrackingRecHit::MuonRecHitContainer SegmentToTrackAssociator::assoc if (myLayer.chamberId() == myChamber.chamberId()) { //push positionCSC.push_back(NumberOfCSCSegment); - const GeomDet* CSCgeomDet = theTrackingGeometry->idToDet(myChamber); + const GeomDet* CSCgeomDet = globalTrackingGeometry_->idToDet(myChamber); SelectedSegments.push_back( MuonTransientTrackingRecHit::specificBuild(CSCgeomDet, (TrackingRecHit*)&*segmentCSC)); } diff --git a/Alignment/MuonAlignmentAlgorithms/test/BuildFile.xml b/Alignment/MuonAlignmentAlgorithms/test/BuildFile.xml deleted file mode 100644 index 8adb25215f548..0000000000000 --- a/Alignment/MuonAlignmentAlgorithms/test/BuildFile.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - - - - - - - - - - - diff --git a/Alignment/MuonAlignmentAlgorithms/test/StandAloneTest.cc b/Alignment/MuonAlignmentAlgorithms/test/StandAloneTest.cc deleted file mode 100644 index 33b988ead96a9..0000000000000 --- a/Alignment/MuonAlignmentAlgorithms/test/StandAloneTest.cc +++ /dev/null @@ -1,214 +0,0 @@ -// -*- C++ -*- -// -// Package: StandAloneTest -// Class: StandAloneTest -// -/**\class StandAloneTest StandAloneTest.cc Dummy/StandAloneTest/src/StandAloneTest.cc - - Description: - - Implementation: - -*/ -// -// Original Author: Jim Pivarski -// Created: Sat Sep 26 02:50:24 CEST 2009 -// $Id: StandAloneTest.cc,v 1.2 2010/01/06 15:38:44 mussgill Exp $ -// -// - -// system include files -#include - -// user include files -#include "FWCore/Framework/interface/Frameworkfwd.h" -#include "FWCore/Framework/interface/EDAnalyzer.h" -#include "FWCore/Framework/interface/Event.h" -#include "FWCore/Framework/interface/MakerMacros.h" -#include "FWCore/ParameterSet/interface/ParameterSet.h" -#include "FWCore/Framework/interface/ESHandle.h" - -#include "FWCore/ServiceRegistry/interface/Service.h" -#include "CommonTools/UtilAlgos/interface/TFileService.h" -#include "TTree.h" - -#include "DataFormats/TrackReco/interface/Track.h" -#include "DataFormats/TrackReco/interface/TrackFwd.h" -#include "DataFormats/TrackingRecHit/interface/TrackingRecHitFwd.h" -#include "DataFormats/DetId/interface/DetId.h" -#include "DataFormats/MuonDetId/interface/MuonSubdetId.h" -#include "DataFormats/MuonDetId/interface/CSCDetId.h" -#include "Geometry/CSCGeometry/interface/CSCGeometry.h" -#include "Geometry/Records/interface/MuonGeometryRecord.h" -#include "TrackingTools/PatternTools/interface/TrajTrackAssociation.h" -#include "TrackingTools/PatternTools/interface/Trajectory.h" -#include "Geometry/CommonDetUnit/interface/GlobalTrackingGeometry.h" -#include "Geometry/Records/interface/GlobalTrackingGeometryRecord.h" -#include "Alignment/MuonAlignment/interface/MuonAlignment.h" -#include "Alignment/MuonAlignmentAlgorithms/interface/MuonResidualsFromTrack.h" - -#include "TrackingTools/Records/interface/TrackingComponentsRecord.h" -#include "TrackingTools/Records/interface/DetIdAssociatorRecord.h" -#include "TrackingTools/GeomPropagators/interface/Propagator.h" -#include "MagneticField/Records/interface/IdealMagneticFieldRecord.h" -#include "MagneticField/Engine/interface/MagneticField.h" - -// -// class decleration -// - -class StandAloneTest : public edm::EDAnalyzer { -public: - explicit StandAloneTest(const edm::ParameterSet &); - ~StandAloneTest(); - -private: - virtual void beginJob(); - virtual void analyze(const edm::Event &, const edm::EventSetup &); - virtual void endJob(); - - // ----------member data --------------------------- - - edm::InputTag m_Tracks; - - // declare the TTree - TTree *m_ttree; - Int_t m_ttree_station; - Int_t m_ttree_chamber; - Float_t m_ttree_resid; - Float_t m_ttree_residslope; - Float_t m_ttree_phi; - Float_t m_ttree_qoverpt; - - MuonAlignment *m_muonAlignment; -}; - -// -// constants, enums and typedefs -// - -// -// static data member definitions -// - -// -// constructors and destructor -// -StandAloneTest::StandAloneTest(const edm::ParameterSet &iConfig) - : m_Tracks(iConfig.getParameter("Tracks")) { - edm::Service tFileService; - - // book the TTree - m_ttree = tFileService->make("ttree", "ttree"); - m_ttree->Branch("station", &m_ttree_station, "station/I"); - m_ttree->Branch("chamber", &m_ttree_chamber, "chamber/I"); - m_ttree->Branch("resid", &m_ttree_resid, "resid/F"); - m_ttree->Branch("residslope", &m_ttree_residslope, "residslope/F"); - m_ttree->Branch("phi", &m_ttree_phi, "phi/F"); - m_ttree->Branch("qoverpt", &m_ttree_qoverpt, "qoverpt/F"); - - m_muonAlignment = NULL; -} - -StandAloneTest::~StandAloneTest() { - // do anything here that needs to be done at desctruction time - // (e.g. close files, deallocate resources etc.) -} - -// -// member functions -// - -// ------------ method called to for each event ------------ -void StandAloneTest::analyze(const edm::Event &iEvent, const edm::EventSetup &iSetup) { - // create a muon alignment object ONCE (not used for much, only a formalilty for MuonResidualsFromTrack) - if (m_muonAlignment == NULL) { - m_muonAlignment = new MuonAlignment(iSetup); - } - - // get tracks and refitted from the Event - edm::Handle tracks; - iEvent.getByLabel(m_Tracks, tracks); - edm::Handle trajtracksmap; - iEvent.getByLabel("TrackRefitter", "Refitted", trajtracksmap); - - // get all tracking and CSC geometries from the EventSetup - edm::ESHandle globalGeometry; - iSetup.get().get(globalGeometry); - edm::ESHandle cscGeometry; - iSetup.get().get(cscGeometry); - - edm::ESHandle prop; - iSetup.get().get("SteppingHelixPropagatorAny", prop); - edm::ESHandle magneticField; - iSetup.get().get(magneticField); - edm::ESHandle muonDetIdAssociator_; - iSetup.get().get("MuonDetIdAssociator", muonDetIdAssociator_); - - // loop over tracks - for (reco::TrackCollection::const_iterator track = tracks->begin(); track != tracks->end(); ++track) { - // find the corresponding refitted trajectory - const Trajectory *traj = NULL; - for (TrajTrackAssociationCollection::const_iterator iPair = trajtracksmap->begin(); iPair != trajtracksmap->end(); - ++iPair) { - if (&(*(iPair->val)) == &(*track)) { - traj = &(*(iPair->key)); - } - } - - // if good track, good trajectory - if (track->pt() > 20. && traj != NULL && traj->isValid()) { - // calculate all residuals on this track - MuonResidualsFromTrack muonResidualsFromTrack(iSetup, - magneticField, - globalGeometry, - muonDetIdAssociator_, - prop, - traj, - &(*track), - m_muonAlignment->getAlignableNavigator(), - 1000.); - std::vector chamberIds = muonResidualsFromTrack.chamberIds(); - - // if the tracker part of refit is okay - if (muonResidualsFromTrack.trackerNumHits() >= 10 && muonResidualsFromTrack.trackerRedChi2() < 10.) { - // loop over ALL chambers - for (std::vector::const_iterator chamberId = chamberIds.begin(); chamberId != chamberIds.end(); - ++chamberId) { - // if CSC - if (chamberId->det() == DetId::Muon && chamberId->subdetId() == MuonSubdetId::CSC) { - CSCDetId cscid(chamberId->rawId()); - int station = (cscid.endcap() == 1 ? 1 : -1) * (10 * cscid.station() + cscid.ring()); - MuonChamberResidual *csc = muonResidualsFromTrack.chamberResidual(*chamberId, MuonChamberResidual::kCSC); - - // if this segment is okay and has 6 hits - if (csc != NULL && csc->numHits() >= 6) { - // fill the TTree - m_ttree_station = station; - m_ttree_chamber = cscid.chamber(); - m_ttree_resid = csc->residual(); - m_ttree_residslope = csc->resslope(); - m_ttree_phi = csc->global_trackpos().phi(); - m_ttree_qoverpt = double(track->charge()) / track->pt(); - m_ttree->Fill(); - } // end if CSC is okay - - } // end if CSC - - } // end loop over all chambers - - } // end if tracker part of refit is okay - - } // end if good track, good track refit - - } // end loop over tracks -} - -// ------------ method called once each job just before starting event loop ------------ -void StandAloneTest::beginJob() {} - -// ------------ method called once each job just after ending the event loop ------------ -void StandAloneTest::endJob() {} - -//define this as a plug-in -DEFINE_FWK_MODULE(StandAloneTest); diff --git a/Alignment/MuonAlignmentAlgorithms/test/standAloneTest_cfg.py b/Alignment/MuonAlignmentAlgorithms/test/standAloneTest_cfg.py deleted file mode 100644 index 5c331fcdc4511..0000000000000 --- a/Alignment/MuonAlignmentAlgorithms/test/standAloneTest_cfg.py +++ /dev/null @@ -1,64 +0,0 @@ -import FWCore.ParameterSet.Config as cms - -process = cms.Process("TEST") -process.source = cms.Source("PoolSource", fileNames = cms.untracked.vstring( - "/store/data/CRAFT09/Cosmics/RAW-RECO/GR09_31X_V5P_CSCSkim_BFieldStudies-332_v4/0021/FAF8A711-C297-DE11-A00E-001731AF66AF.root", - "/store/data/CRAFT09/Cosmics/RAW-RECO/GR09_31X_V5P_CSCSkim_BFieldStudies-332_v4/0021/FAB8A245-D996-DE11-A866-003048678A6A.root", - "/store/data/CRAFT09/Cosmics/RAW-RECO/GR09_31X_V5P_CSCSkim_BFieldStudies-332_v4/0021/F8D6CB8E-CD96-DE11-A8D2-003048678FFA.root", - "/store/data/CRAFT09/Cosmics/RAW-RECO/GR09_31X_V5P_CSCSkim_BFieldStudies-332_v4/0021/F8349AAD-C297-DE11-99E3-0030486792BA.root", - "/store/data/CRAFT09/Cosmics/RAW-RECO/GR09_31X_V5P_CSCSkim_BFieldStudies-332_v4/0021/F8251242-DA96-DE11-B26B-003048678FC6.root", - "/store/data/CRAFT09/Cosmics/RAW-RECO/GR09_31X_V5P_CSCSkim_BFieldStudies-332_v4/0021/F49C816C-D796-DE11-AC34-003048D15DDA.root", - "/store/data/CRAFT09/Cosmics/RAW-RECO/GR09_31X_V5P_CSCSkim_BFieldStudies-332_v4/0021/F288C73C-C297-DE11-9F00-001731AF684D.root", - "/store/data/CRAFT09/Cosmics/RAW-RECO/GR09_31X_V5P_CSCSkim_BFieldStudies-332_v4/0021/F0BBFDE1-D496-DE11-8E1B-003048678FE6.root", - "/store/data/CRAFT09/Cosmics/RAW-RECO/GR09_31X_V5P_CSCSkim_BFieldStudies-332_v4/0021/EE1592A7-C297-DE11-8679-0030486792AC.root", - "/store/data/CRAFT09/Cosmics/RAW-RECO/GR09_31X_V5P_CSCSkim_BFieldStudies-332_v4/0021/E2938851-CF96-DE11-8330-0017312B5651.root", - )) -process.maxEvents = cms.untracked.PSet(input = cms.untracked.int32(100)) - -process.StandAloneTest = cms.EDAnalyzer("StandAloneTest", Tracks = cms.InputTag("")) - -process.load("Configuration.StandardSequences.MagneticField_cff") -process.load("Geometry.CMSCommonData.cmsIdealGeometryXML_cfi") -process.load("Geometry.CommonTopologies.bareGlobalTrackingGeometry_cfi") -process.load("Geometry.MuonNumbering.muonNumberingInitialization_cfi") -process.load("Geometry.DTGeometry.dtGeometry_cfi") -process.load("Geometry.CSCGeometry.cscGeometry_cfi") -process.load("Geometry.RPCGeometry.rpcGeometry_cfi") -process.load("Geometry.TrackerNumberingBuilder.trackerNumberingGeometry_cfi") -process.load("Geometry.TrackerGeometryBuilder.trackerGeometry_cfi") - -### for cosmic rays (only use one) -process.load("TrackingTools.TrackRefitter.globalCosmicMuonTrajectories_cff") -process.TrackRefitter = process.globalCosmicMuons.clone() -process.TrackRefitter.Tracks = cms.InputTag("globalCosmicMuons") -process.StandAloneTest.Tracks = cms.InputTag("globalCosmicMuons") - -### for collisions (only use one) -# process.load("TrackingTools.TrackRefitter.globalMuonTrajectories_cff") -# process.TrackRefitter = process.globalCosmicMuons.clone() -# process.TrackRefitter.Tracks = cms.InputTag("globalMuons") -# process.StandAloneTest.Tracks = cms.InputTag("globalMuons") - -process.load("Configuration.StandardSequences.FrontierConditions_GlobalTag_cff") -process.GlobalTag.globaltag = cms.string("CRAFT0831X_V1::All") - -process.load("CondCore.DBCommon.CondDBSetup_cfi") - -### for assigning a custom muon alignment -# process.MuonAlignment = cms.ESSource("PoolDBESSource", -# process.CondDBSetup, -# connect = cms.string("sqlite_file:customMuonAlignment.db"), -# toGet = cms.VPSet(cms.PSet(record = cms.string("DTAlignmentRcd"), tag = cms.string("DTAlignmentRcd")), -# cms.PSet(record = cms.string("CSCAlignmentRcd"), tag = cms.string("CSCAlignmentRcd")))) -# process.es_prefer_MuonAlignment = cms.ESPrefer("PoolDBESSource", "MuonAlignment") - -### it is important to refit with zero weights ("infinite" APEs) -process.MuonAlignmentErrorsExtended = cms.ESSource("PoolDBESSource", - process.CondDBSetup, - connect = cms.string("sqlite_file:APE1000cm.db"), - toGet = cms.VPSet(cms.PSet(record = cms.string("DTAlignmentErrorExtendedRcd"), tag = cms.string("DTAlignmentErrorExtendedRcd")), - cms.PSet(record = cms.string("CSCAlignmentErrorExtendedRcd"), tag = cms.string("CSCAlignmentErrorExtendedRcd")))) -process.es_prefer_MuonAlignmentErrorsExtended = cms.ESPrefer("PoolDBESSource", "MuonAlignmentErrorsExtended") - -process.TFileService = cms.Service("TFileService", fileName = cms.string("standAloneTest.root")) -process.Path = cms.Path(process.TrackRefitter * process.StandAloneTest) diff --git a/Alignment/OfflineValidation/macros/CMS_lumi.h b/Alignment/OfflineValidation/macros/CMS_lumi.h index b04f5cc8bc8d8..392f704d49f2b 100644 --- a/Alignment/OfflineValidation/macros/CMS_lumi.h +++ b/Alignment/OfflineValidation/macros/CMS_lumi.h @@ -35,6 +35,7 @@ float extraOverCmsTextSize = 0.76; TString lumi_13TeV = "20.1 fb^{-1}"; TString lumi_8TeV = "19.7 fb^{-1}"; TString lumi_7TeV = "5.1 fb^{-1}"; +TString lumi_0p9TeV = ""; TString lumi_sqrtS = ""; bool drawLogo = false; @@ -88,6 +89,9 @@ void CMS_lumi(TPad* pad, int iPeriod, int iPosX) { } else if (iPeriod == 4) { lumiText += lumi_13TeV; lumiText += " (#sqrt{s} = 13 TeV)"; + } else if (iPeriod == 5) { + lumiText += lumi_0p9TeV; + lumiText += " (#sqrt{s} = 0.9 TeV)"; } else if (iPeriod == 7) { if (outOfFrame) lumiText += "#scale[0.85]{"; diff --git a/Alignment/OfflineValidation/macros/FitPVResiduals.C b/Alignment/OfflineValidation/macros/FitPVResiduals.C index 7a163036dd865..dbd5b029fe1f7 100644 --- a/Alignment/OfflineValidation/macros/FitPVResiduals.C +++ b/Alignment/OfflineValidation/macros/FitPVResiduals.C @@ -4200,17 +4200,17 @@ params::measurement getTheRangeUser(TH1F *thePlot, Limits *lims, bool tag) if (theTitle.Contains("norm")) { if (theTitle.Contains("means")) { if (theTitle.Contains("dxy") || theTitle.Contains("dx") || theTitle.Contains("dy")) { - if (theTitle.Contains("phi") || theTitle.Contains("pT")) { + if (theTitle.Contains("phi") || theTitle.Contains("pT") || theTitle.Contains("ladder")) { result = std::make_pair(-lims->get_dxyPhiNormMax().first, lims->get_dxyPhiNormMax().first); - } else if (theTitle.Contains("eta")) { + } else if (theTitle.Contains("eta") || theTitle.Contains("mod")) { result = std::make_pair(-lims->get_dxyEtaNormMax().first, lims->get_dxyEtaNormMax().first); } else { result = std::make_pair(-0.8, 0.8); } } else if (theTitle.Contains("dz")) { - if (theTitle.Contains("phi") || theTitle.Contains("pT")) { + if (theTitle.Contains("phi") || theTitle.Contains("pT") || theTitle.Contains("ladder")) { result = std::make_pair(-lims->get_dzPhiNormMax().first, lims->get_dzPhiNormMax().first); - } else if (theTitle.Contains("eta")) { + } else if (theTitle.Contains("eta") || theTitle.Contains("mod")) { result = std::make_pair(-lims->get_dzEtaNormMax().first, lims->get_dzEtaNormMax().first); } else { result = std::make_pair(-0.8, 0.8); @@ -4218,17 +4218,17 @@ params::measurement getTheRangeUser(TH1F *thePlot, Limits *lims, bool tag) } } else if (theTitle.Contains("widths")) { if (theTitle.Contains("dxy") || theTitle.Contains("dx") || theTitle.Contains("dy")) { - if (theTitle.Contains("phi")) { + if (theTitle.Contains("phi") || theTitle.Contains("ladder")) { result = std::make_pair(0., lims->get_dxyPhiNormMax().second); - } else if (theTitle.Contains("eta")) { + } else if (theTitle.Contains("eta") || theTitle.Contains("mod")) { result = std::make_pair(0., lims->get_dxyEtaNormMax().second); } else { result = std::make_pair(0., 2.); } } else if (theTitle.Contains("dz")) { - if (theTitle.Contains("phi")) { + if (theTitle.Contains("phi") || theTitle.Contains("ladder")) { result = std::make_pair(0., lims->get_dzPhiNormMax().second); - } else if (theTitle.Contains("eta")) { + } else if (theTitle.Contains("eta") || theTitle.Contains("mod")) { result = std::make_pair(0., lims->get_dzEtaNormMax().second); } else { result = std::make_pair(0., 2.); @@ -4238,17 +4238,17 @@ params::measurement getTheRangeUser(TH1F *thePlot, Limits *lims, bool tag) } else { if (theTitle.Contains("means")) { if (theTitle.Contains("dxy") || theTitle.Contains("dx") || theTitle.Contains("dy")) { - if (theTitle.Contains("phi") || theTitle.Contains("pT")) { + if (theTitle.Contains("phi") || theTitle.Contains("pT") || theTitle.Contains("ladder")) { result = std::make_pair(-lims->get_dxyPhiMax().first, lims->get_dxyPhiMax().first); - } else if (theTitle.Contains("eta")) { + } else if (theTitle.Contains("eta") || theTitle.Contains("mod")) { result = std::make_pair(-lims->get_dxyEtaMax().first, lims->get_dxyEtaMax().first); } else { result = std::make_pair(-40., 40.); } } else if (theTitle.Contains("dz")) { - if (theTitle.Contains("phi") || theTitle.Contains("pT")) { + if (theTitle.Contains("phi") || theTitle.Contains("pT") || theTitle.Contains("ladder")) { result = std::make_pair(-lims->get_dzPhiMax().first, lims->get_dzPhiMax().first); - } else if (theTitle.Contains("eta")) { + } else if (theTitle.Contains("eta") || theTitle.Contains("mod")) { result = std::make_pair(-lims->get_dzEtaMax().first, lims->get_dzEtaMax().first); } else { result = std::make_pair(-80., 80.); @@ -4256,17 +4256,17 @@ params::measurement getTheRangeUser(TH1F *thePlot, Limits *lims, bool tag) } } else if (theTitle.Contains("widths")) { if (theTitle.Contains("dxy") || theTitle.Contains("dx") || theTitle.Contains("dy")) { - if (theTitle.Contains("phi")) { + if (theTitle.Contains("phi") || theTitle.Contains("ladder")) { result = std::make_pair(0., lims->get_dxyPhiMax().second); - } else if (theTitle.Contains("eta")) { + } else if (theTitle.Contains("eta") || theTitle.Contains("mod")) { result = std::make_pair(0., lims->get_dxyEtaMax().second); } else { result = std::make_pair(0., 150.); } } else if (theTitle.Contains("dz")) { - if (theTitle.Contains("phi")) { + if (theTitle.Contains("phi") || theTitle.Contains("ladder")) { result = std::make_pair(0., lims->get_dzPhiMax().second); - } else if (theTitle.Contains("eta")) { + } else if (theTitle.Contains("eta") || theTitle.Contains("mod")) { result = std::make_pair(0., lims->get_dzEtaMax().second); } else { result = std::make_pair(0., 300.); diff --git a/Alignment/OfflineValidation/plugins/DMRChecker.cc b/Alignment/OfflineValidation/plugins/DMRChecker.cc index 2d4bc4b3fe7d2..a3d985a712e2f 100644 --- a/Alignment/OfflineValidation/plugins/DMRChecker.cc +++ b/Alignment/OfflineValidation/plugins/DMRChecker.cc @@ -54,6 +54,7 @@ #include "CommonTools/UtilAlgos/interface/TFileService.h" #include "CommonTools/Utils/interface/TFileDirectory.h" #include "DQM/TrackerRemapper/interface/Phase1PixelMaps.h" +#include "DQM/TrackerRemapper/interface/Phase1PixelSummaryMap.h" #include "CondCore/SiPixelPlugins/interface/PixelRegionContainers.h" #include "CondCore/SiPixelPlugins/interface/SiPixelPayloadInspectorHelper.h" #include "CondFormats/DataRecord/interface/RunSummaryRcd.h" @@ -158,16 +159,16 @@ class DMRChecker : public edm::one::EDAnalyzer { usesResource(TFileService::kSharedResource); TkTag_ = pset.getParameter("TkTag"); - theTrackCollectionToken = consumes(TkTag_); + theTrackCollectionToken_ = consumes(TkTag_); TriggerResultsTag_ = pset.getParameter("TriggerResultsTag"); - hltresultsToken = consumes(TriggerResultsTag_); + hltresultsToken_ = consumes(TriggerResultsTag_); BeamSpotTag_ = pset.getParameter("BeamSpotTag"); - beamspotToken = consumes(BeamSpotTag_); + beamspotToken_ = consumes(BeamSpotTag_); VerticesTag_ = pset.getParameter("VerticesTag"); - vertexToken = consumes(VerticesTag_); + vertexToken_ = consumes(VerticesTag_); // initialize conventional Tracker maps @@ -191,6 +192,10 @@ class DMRChecker : public edm::one::EDAnalyzer { // set no rescale pixelmap->setNoRescale(); + + // initialize Full Pixel Map + fullPixelmapXDMR = std::make_unique("", "DMR-x", "median of residuals [#mum]"); + fullPixelmapYDMR = std::make_unique("", "DMR-y", "median of residuals [#mum]"); } static void fillDescriptions(edm::ConfigurationDescriptions &); @@ -225,6 +230,9 @@ class DMRChecker : public edm::one::EDAnalyzer { edm::Service fs; std::unique_ptr pixelmap; + std::unique_ptr fullPixelmapXDMR; + std::unique_ptr fullPixelmapYDMR; + std::unique_ptr PixelDMRS_x_ByLayer; std::unique_ptr PixelDMRS_y_ByLayer; @@ -455,10 +463,10 @@ class DMRChecker : public edm::one::EDAnalyzer { edm::InputTag BeamSpotTag_; edm::InputTag VerticesTag_; - edm::EDGetTokenT theTrackCollectionToken; - edm::EDGetTokenT hltresultsToken; - edm::EDGetTokenT beamspotToken; - edm::EDGetTokenT vertexToken; + edm::EDGetTokenT theTrackCollectionToken_; + edm::EDGetTokenT hltresultsToken_; + edm::EDGetTokenT beamspotToken_; + edm::EDGetTokenT vertexToken_; std::map > triggerMap_; std::map > conditionsMap_; @@ -484,8 +492,7 @@ class DMRChecker : public edm::one::EDAnalyzer { void analyze(const edm::Event &event, const edm::EventSetup &setup) override { ievt++; - edm::Handle trackCollection; - event.getByToken(theTrackCollectionToken, trackCollection); + edm::Handle trackCollection = event.getHandle(theTrackCollectionToken_); // magnetic field setup const MagneticField *magneticField_ = &setup.getData(magFieldToken_); @@ -547,8 +554,7 @@ class DMRChecker : public edm::one::EDAnalyzer { //edm::LogVerbatim("DMRChecker") << "Reconstructed "<< tC.size() << " tracks" << std::endl ; - edm::Handle hltresults; - event.getByToken(hltresultsToken, hltresults); + edm::Handle hltresults = event.getHandle(hltresultsToken_); if (hltresults.isValid()) { const edm::TriggerNames &triggerNames_ = event.triggerNames(*hltresults); int ntrigs = hltresults->size(); @@ -1021,8 +1027,7 @@ class DMRChecker : public edm::one::EDAnalyzer { //dxy with respect to the beamspot reco::BeamSpot beamSpot; - edm::Handle beamSpotHandle; - event.getByToken(beamspotToken, beamSpotHandle); + edm::Handle beamSpotHandle = event.getHandle(beamspotToken_); if (beamSpotHandle.isValid()) { beamSpot = *beamSpotHandle; math::XYZPoint point(beamSpot.x0(), beamSpot.y0(), beamSpot.z0()); @@ -1035,9 +1040,7 @@ class DMRChecker : public edm::one::EDAnalyzer { //dxy with respect to the primary vertex reco::Vertex pvtx; - edm::Handle vertexHandle; - reco::VertexCollection vertexCollection; - event.getByLabel("offlinePrimaryVertices", vertexHandle); + edm::Handle vertexHandle = event.getHandle(vertexToken_); double mindxy = 100.; double dz = 100; if (vertexHandle.isValid()) { @@ -1330,6 +1333,10 @@ class DMRChecker : public edm::one::EDAnalyzer { firstEvent_ = true; + // create the full maps + fullPixelmapXDMR->createTrackerBaseMap(); + fullPixelmapYDMR->createTrackerBaseMap(); + } //beginJob void endJob() override { @@ -1525,8 +1532,10 @@ class DMRChecker : public edm::one::EDAnalyzer { for (auto &bpixid : resDetailsBPixX_) { DMRBPixX_->Fill(bpixid.second.runningMeanOfRes_); - if (phase_ == SiPixelPI::phase::one) + if (phase_ == SiPixelPI::phase::one) { pixelmap->fillBarrelBin("DMRsX", bpixid.first, bpixid.second.runningMeanOfRes_); + fullPixelmapXDMR->fillTrackerMap(bpixid.first, bpixid.second.runningMeanOfRes_); + } //auto myLocalTopo = PixelDMRS_x_ByLayer->getTheTopo(); //edm::LogPrint("DMRChecker") << myLocalTopo->print(bpixid.first) << std::endl; @@ -1548,8 +1557,11 @@ class DMRChecker : public edm::one::EDAnalyzer { for (auto &bpixid : resDetailsBPixY_) { DMRBPixY_->Fill(bpixid.second.runningMeanOfRes_); - if (phase_ == SiPixelPI::phase::one) + if (phase_ == SiPixelPI::phase::one) { pixelmap->fillBarrelBin("DMRsY", bpixid.first, bpixid.second.runningMeanOfRes_); + fullPixelmapYDMR->fillTrackerMap(bpixid.first, bpixid.second.runningMeanOfRes_); + } + PixelDMRS_y_ByLayer->fill(bpixid.first, bpixid.second.runningMeanOfRes_); // split DMR @@ -1567,8 +1579,10 @@ class DMRChecker : public edm::one::EDAnalyzer { for (auto &fpixid : resDetailsFPixX_) { DMRFPixX_->Fill(fpixid.second.runningMeanOfRes_); - if (phase_ == SiPixelPI::phase::one) + if (phase_ == SiPixelPI::phase::one) { pixelmap->fillForwardBin("DMRsX", fpixid.first, fpixid.second.runningMeanOfRes_); + fullPixelmapXDMR->fillTrackerMap(fpixid.first, fpixid.second.runningMeanOfRes_); + } PixelDMRS_x_ByLayer->fill(fpixid.first, fpixid.second.runningMeanOfRes_); // split DMR @@ -1586,8 +1600,10 @@ class DMRChecker : public edm::one::EDAnalyzer { for (auto &fpixid : resDetailsFPixY_) { DMRFPixY_->Fill(fpixid.second.runningMeanOfRes_); - if (phase_ == SiPixelPI::phase::one) + if (phase_ == SiPixelPI::phase::one) { pixelmap->fillForwardBin("DMRsY", fpixid.first, fpixid.second.runningMeanOfRes_); + fullPixelmapXDMR->fillTrackerMap(fpixid.first, fpixid.second.runningMeanOfRes_); + } PixelDMRS_y_ByLayer->fill(fpixid.first, fpixid.second.runningMeanOfRes_); // split DMR @@ -1685,6 +1701,14 @@ class DMRChecker : public edm::one::EDAnalyzer { TCanvas cFY("CanvXForward", "CanvXForward", 1600, 1000); pixelmap->drawForwardMaps("DMRsY", cFY); cFY.SaveAs("pixelForwardDMR_y.png"); + + TCanvas cFullPixelxDMR("CanvFullPixelX", "CanvFullPixelX", 3000, 2000); + fullPixelmapXDMR->printTrackerMap(cFullPixelxDMR); + cFullPixelxDMR.SaveAs("fullPixelDMR_x.png"); + + TCanvas cFullPixelyDMR("CanvFullPixelX", "CanvFullPixelY", 3000, 2000); + fullPixelmapXDMR->printTrackerMap(cFullPixelyDMR); + cFullPixelyDMR.SaveAs("fullPixelDMR_y.png"); } // take care now of the 1D histograms diff --git a/Alignment/OfflineValidation/plugins/GeneralPurposeTrackAnalyzer.cc b/Alignment/OfflineValidation/plugins/GeneralPurposeTrackAnalyzer.cc index eb080b217c6fa..a55a4e57a6c01 100644 --- a/Alignment/OfflineValidation/plugins/GeneralPurposeTrackAnalyzer.cc +++ b/Alignment/OfflineValidation/plugins/GeneralPurposeTrackAnalyzer.cc @@ -97,16 +97,16 @@ class GeneralPurposeTrackAnalyzer : public edm::one::EDAnalyzer("TkTag"); - theTrackCollectionToken = consumes(TkTag_); + theTrackCollectionToken_ = consumes(TkTag_); TriggerResultsTag_ = pset.getParameter("TriggerResultsTag"); - hltresultsToken = consumes(TriggerResultsTag_); + hltresultsToken_ = consumes(TriggerResultsTag_); BeamSpotTag_ = pset.getParameter("BeamSpotTag"); - beamspotToken = consumes(BeamSpotTag_); + beamspotToken_ = consumes(BeamSpotTag_); VerticesTag_ = pset.getParameter("VerticesTag"); - vertexToken = consumes(VerticesTag_); + vertexToken_ = consumes(VerticesTag_); isCosmics_ = pset.getParameter("isCosmics"); @@ -289,10 +289,10 @@ class GeneralPurposeTrackAnalyzer : public edm::one::EDAnalyzer theTrackCollectionToken; - edm::EDGetTokenT hltresultsToken; - edm::EDGetTokenT beamspotToken; - edm::EDGetTokenT vertexToken; + edm::EDGetTokenT theTrackCollectionToken_; + edm::EDGetTokenT hltresultsToken_; + edm::EDGetTokenT beamspotToken_; + edm::EDGetTokenT vertexToken_; std::map > triggerMap_; std::map > conditionsMap_; @@ -304,12 +304,10 @@ class GeneralPurposeTrackAnalyzer : public edm::one::EDAnalyzer trackCollection; - event.getByToken(theTrackCollectionToken, trackCollection); + edm::Handle trackCollection = event.getHandle(theTrackCollectionToken_); // geometry setup - edm::ESHandle geometry = setup.getHandle(geomToken_); - const TrackerGeometry *theGeometry = &(*geometry); + const TrackerGeometry *theGeometry = &setup.getData(geomToken_); // switch on the phase1 if ((theGeometry->isThere(GeomDetEnumerators::P1PXB)) || (theGeometry->isThere(GeomDetEnumerators::P1PXEC))) { @@ -329,8 +327,7 @@ class GeneralPurposeTrackAnalyzer : public edm::one::EDAnalyzer hltresults; - event.getByToken(hltresultsToken, hltresults); + edm::Handle hltresults = event.getHandle(hltresultsToken_); if (hltresults.isValid()) { const edm::TriggerNames &triggerNames_ = event.triggerNames(*hltresults); int ntrigs = hltresults->size(); @@ -641,8 +638,7 @@ class GeneralPurposeTrackAnalyzer : public edm::one::EDAnalyzer beamSpotHandle; - event.getByToken(beamspotToken, beamSpotHandle); + edm::Handle beamSpotHandle = event.getHandle(beamspotToken_); if (beamSpotHandle.isValid()) { beamSpot = *beamSpotHandle; math::XYZPoint point(beamSpot.x0(), beamSpot.y0(), beamSpot.z0()); @@ -655,9 +651,7 @@ class GeneralPurposeTrackAnalyzer : public edm::one::EDAnalyzer vertexHandle; - reco::VertexCollection vertexCollection; - event.getByLabel("offlinePrimaryVertices", vertexHandle); + edm::Handle vertexHandle = event.getHandle(vertexToken_); double mindxy = 100.; double dz = 100; if (vertexHandle.isValid() && !isCosmics_) { diff --git a/Alignment/OfflineValidation/plugins/PrimaryVertexValidation.cc b/Alignment/OfflineValidation/plugins/PrimaryVertexValidation.cc index fe2a9b3d0a809..2eb13bccda175 100644 --- a/Alignment/OfflineValidation/plugins/PrimaryVertexValidation.cc +++ b/Alignment/OfflineValidation/plugins/PrimaryVertexValidation.cc @@ -52,6 +52,7 @@ #include "Geometry/CommonDetUnit/interface/GeomDet.h" #include "Geometry/Records/interface/TrackerDigiGeometryRecord.h" #include "Geometry/TrackerGeometryBuilder/interface/TrackerGeometry.h" +#include "Geometry/TrackerGeometryBuilder/interface/PixelTopologyMap.h" #include "Geometry/Records/interface/TrackerTopologyRcd.h" #include "RecoVertex/PrimaryVertexProducer/interface/TrackFilterForPVFinding.h" #include "RecoVertex/PrimaryVertexProducer/interface/DAClusterizerInZ_vect.h" @@ -67,10 +68,11 @@ const int PrimaryVertexValidation::nMaxtracks_; PrimaryVertexValidation::PrimaryVertexValidation(const edm::ParameterSet& iConfig) : magFieldToken_(esConsumes()), trackingGeomToken_(esConsumes()), - geomToken_(esConsumes()), ttkToken_(esConsumes(edm::ESInputTag("", "TransientTrackBuilder"))), topoToken_(esConsumes()), - runInfoToken_(esConsumes()), + topoTokenBR_(esConsumes()), + geomTokenBR_(esConsumes()), + runInfoTokenBR_(esConsumes()), compressionSettings_(iConfig.getUntrackedParameter("compressionSettings", -1)), storeNtuple_(iConfig.getParameter("storeNtuple")), lightNtupleSwitch_(iConfig.getParameter("isLightNtuple")), @@ -100,13 +102,13 @@ PrimaryVertexValidation::PrimaryVertexValidation(const edm::ParameterSet& iConfi runControlNumbers_ = iConfig.getUntrackedParameter>("runControlNumber", defaultRuns); edm::InputTag TrackCollectionTag_ = iConfig.getParameter("TrackCollectionTag"); - theTrackCollectionToken = consumes(TrackCollectionTag_); + theTrackCollectionToken_ = consumes(TrackCollectionTag_); edm::InputTag VertexCollectionTag_ = iConfig.getParameter("VertexCollectionTag"); - theVertexCollectionToken = consumes(VertexCollectionTag_); + theVertexCollectionToken_ = consumes(VertexCollectionTag_); edm::InputTag BeamspotTag_ = iConfig.getParameter("BeamSpotTag"); - theBeamspotToken = consumes(BeamspotTag_); + theBeamspotToken_ = consumes(BeamspotTag_); // select and configure the track filter theTrackFilter_ = @@ -200,11 +202,7 @@ PrimaryVertexValidation::PrimaryVertexValidation(const edm::ParameterSet& iConfi } // Destructor -PrimaryVertexValidation::~PrimaryVertexValidation() { - // do anything here that needs to be done at desctruction time - // (e.g. close files, deallocate resources etc.) -} - +PrimaryVertexValidation::~PrimaryVertexValidation() = default; // // member functions // @@ -215,16 +213,6 @@ void PrimaryVertexValidation::analyze(const edm::Event& iEvent, const edm::Event using namespace reco; using namespace IPTools; - if (!isBFieldConsistentWithMode(iSetup)) { - edm::LogWarning("PrimaryVertexValidation") - << "*********************************************************************************\n" - << "* The configuration (ptOfProbe > " << ptOfProbe_ - << "GeV) is not correctly set for current value of magnetic field \n" - << "* Switching it to 0. !!! \n" - << "*********************************************************************************" << std::endl; - ptOfProbe_ = 0.; - } - if (nBins_ != 24 && debug_) { edm::LogInfo("PrimaryVertexValidation") << "Using: " << nBins_ << " bins plots"; } @@ -255,129 +243,22 @@ void PrimaryVertexValidation::analyze(const edm::Event& iEvent, const edm::Event SetVarToZero(); //======================================================= - // Retrieve the Magnetic Field information + // Retrieve tracker topology from geometry //======================================================= - edm::ESHandle theMGField = iSetup.getHandle(magFieldToken_); + const TrackerTopology* const tTopo = &iSetup.getData(topoToken_); //======================================================= - // Retrieve the Tracking Geometry information + // Retrieve the Magnetic Field information //======================================================= - edm::ESHandle theTrackingGeometry = iSetup.getHandle(trackingGeomToken_); + edm::ESHandle theMGField = iSetup.getHandle(magFieldToken_); //======================================================= - // Retrieve geometry information + // Retrieve the Tracking Geometry information //======================================================= - edm::LogInfo("read tracker geometry..."); - edm::ESHandle pDD = iSetup.getHandle(geomToken_); - edm::LogInfo("tracker geometry read") << "There are: " << pDD->dets().size() << " detectors"; - - // switch on the phase2 - if ((pDD->isThere(GeomDetEnumerators::P2PXB)) || (pDD->isThere(GeomDetEnumerators::P2PXEC))) { - phase_ = PVValHelper::phase2; - nLadders_ = 12; - nModZ_ = 9; - - if (h_dxy_ladderOverlap_.size() != nLadders_) { - PVValHelper::shrinkHistVectorToFit(h_dxy_ladderOverlap_, nLadders_); - PVValHelper::shrinkHistVectorToFit(h_dxy_ladderNoOverlap_, nLadders_); - PVValHelper::shrinkHistVectorToFit(h_dxy_ladder_, nLadders_); - PVValHelper::shrinkHistVectorToFit(h_dz_ladder_, nLadders_); - PVValHelper::shrinkHistVectorToFit(h_norm_dxy_ladder_, nLadders_); - PVValHelper::shrinkHistVectorToFit(h_norm_dz_ladder_, nLadders_); - - if (debug_) { - edm::LogInfo("PrimaryVertexValidation") << "checking size:" << h_dxy_ladder_.size() << std::endl; - } - } - - if (debug_) { - edm::LogInfo("PrimaryVertexValidation") - << " pixel phase2 setup, nLadders: " << nLadders_ << " nModules:" << nModZ_; - } - - } else if ((pDD->isThere(GeomDetEnumerators::P1PXB)) || (pDD->isThere(GeomDetEnumerators::P1PXEC))) { - // switch on the phase1 - phase_ = PVValHelper::phase1; - nLadders_ = 12; - nModZ_ = 8; - - if (h_dxy_ladderOverlap_.size() != nLadders_) { - PVValHelper::shrinkHistVectorToFit(h_dxy_ladderOverlap_, nLadders_); - PVValHelper::shrinkHistVectorToFit(h_dxy_ladderNoOverlap_, nLadders_); - PVValHelper::shrinkHistVectorToFit(h_dxy_ladder_, nLadders_); - PVValHelper::shrinkHistVectorToFit(h_dz_ladder_, nLadders_); - PVValHelper::shrinkHistVectorToFit(h_norm_dxy_ladder_, nLadders_); - PVValHelper::shrinkHistVectorToFit(h_norm_dz_ladder_, nLadders_); - - if (debug_) { - edm::LogInfo("PrimaryVertexValidation") << "checking size:" << h_dxy_ladder_.size() << std::endl; - } - } - - if (h_dxy_modZ_.size() != nModZ_) { - PVValHelper::shrinkHistVectorToFit(h_dxy_modZ_, nModZ_); - PVValHelper::shrinkHistVectorToFit(h_dz_modZ_, nModZ_); - PVValHelper::shrinkHistVectorToFit(h_norm_dxy_modZ_, nModZ_); - PVValHelper::shrinkHistVectorToFit(h_norm_dxy_modZ_, nModZ_); - - if (debug_) { - edm::LogInfo("PrimaryVertexValidation") << "checking size:" << h_dxy_modZ_.size() << std::endl; - } - } - - if (debug_) { - edm::LogInfo("PrimaryVertexValidation") - << " pixel phase1 setup, nLadders: " << nLadders_ << " nModules:" << nModZ_; - } - - } else { - phase_ = PVValHelper::phase0; - nLadders_ = 20; - nModZ_ = 8; - - if (h_dxy_modZ_.size() != nModZ_) { - PVValHelper::shrinkHistVectorToFit(h_dxy_modZ_, nModZ_); - PVValHelper::shrinkHistVectorToFit(h_dz_modZ_, nModZ_); - PVValHelper::shrinkHistVectorToFit(h_norm_dxy_modZ_, nModZ_); - PVValHelper::shrinkHistVectorToFit(h_norm_dxy_modZ_, nModZ_); - - if (debug_) { - edm::LogInfo("PrimaryVertexValidation") << "checking size:" << h_dxy_modZ_.size() << std::endl; - } - } - - if (debug_) { - edm::LogInfo("PrimaryVertexValidation") - << " pixel phase0 setup, nLadders: " << nLadders_ << " nModules:" << nModZ_; - } - } - - switch (phase_) { - case PVValHelper::phase0: - etaOfProbe_ = std::min(etaOfProbe_, PVValHelper::max_eta_phase0); - break; - case PVValHelper::phase1: - etaOfProbe_ = std::min(etaOfProbe_, PVValHelper::max_eta_phase1); - break; - case PVValHelper::phase2: - etaOfProbe_ = std::min(etaOfProbe_, PVValHelper::max_eta_phase2); - break; - default: - edm::LogWarning("LogicError") << "Unknown detector phase: " << phase_; - } - - if (h_etaMax->GetEntries() == 0.) { - h_etaMax->SetBinContent(1., etaOfProbe_); - h_nbins->SetBinContent(1., nBins_); - h_nLadders->SetBinContent(1., nLadders_); - h_nModZ->SetBinContent(1., nModZ_); - h_pTinfo->SetBinContent(1., mypT_bins_.size()); - h_pTinfo->SetBinContent(2., minPt_); - h_pTinfo->SetBinContent(3., maxPt_); - } + edm::ESHandle theTrackingGeometry = iSetup.getHandle(trackingGeomToken_); //======================================================= // Retrieve the Transient Track Builder information @@ -390,19 +271,11 @@ void PrimaryVertexValidation::analyze(const edm::Event& iEvent, const edm::Event // Retrieve the Track information //======================================================= - edm::Handle trackCollectionHandle; - iEvent.getByToken(theTrackCollectionToken, trackCollectionHandle); + edm::Handle trackCollectionHandle = iEvent.getHandle(theTrackCollectionToken_); if (!trackCollectionHandle.isValid()) return; auto const& tracks = *trackCollectionHandle; - //======================================================= - // Retrieve tracker topology from geometry - //======================================================= - - edm::ESHandle tTopoHandle = iSetup.getHandle(topoToken_); - const TrackerTopology* const tTopo = tTopoHandle.product(); - //======================================================= // Retrieve offline vartex information (only for reco) //======================================================= @@ -411,7 +284,7 @@ void PrimaryVertexValidation::analyze(const edm::Event& iEvent, const edm::Event edm::Handle> vertices; try { - iEvent.getByToken(theVertexCollectionToken, vertices); + vertices = iEvent.getHandle(theVertexCollectionToken_); } catch (cms::Exception& er) { LogTrace("PrimaryVertexValidation") << "caught std::exception " << er.what() << std::endl; } @@ -536,8 +409,7 @@ void PrimaryVertexValidation::analyze(const edm::Event& iEvent, const edm::Event //======================================================= BeamSpot beamSpot; - edm::Handle beamSpotHandle; - iEvent.getByToken(theBeamspotToken, beamSpotHandle); + edm::Handle beamSpotHandle = iEvent.getHandle(theBeamspotToken_); if (beamSpotHandle.isValid()) { beamSpot = *beamSpotHandle; @@ -570,26 +442,6 @@ void PrimaryVertexValidation::analyze(const edm::Event& iEvent, const edm::Event //======================================================= RunNumber_ = iEvent.eventAuxiliary().run(); - h_runNumber->Fill(RunNumber_); - - if (!runNumbersTimesLog_.count(RunNumber_)) { - auto times = getRunTime(iSetup); - - if (debug_) { - const time_t start_time = times.first / 1000000; - edm::LogInfo("PrimaryVertexValidation") - << RunNumber_ << " has start time: " << times.first << " - " << times.second << std::endl; - edm::LogInfo("PrimaryVertexValidation") - << "human readable time: " << std::asctime(std::gmtime(&start_time)) << std::endl; - } - - runNumbersTimesLog_[RunNumber_] = times; - } - - if (h_runFromEvent->GetEntries() == 0) { - h_runFromEvent->SetBinContent(1, RunNumber_); - } - LuminosityBlockNumber_ = iEvent.eventAuxiliary().luminosityBlock(); EventNumber_ = iEvent.eventAuxiliary().id().event(); @@ -2663,6 +2515,142 @@ void PrimaryVertexValidation::beginJob() { highedge); } } + +// ------------ method called once every run before doing the event loop ---------------- +void PrimaryVertexValidation::beginRun(edm::Run const& iRun, edm::EventSetup const& iSetup) { + //======================================================= + // check on the b-field consistency + //======================================================= + + if (!isBFieldConsistentWithMode(iSetup)) { + edm::LogWarning("PrimaryVertexValidation") + << "*********************************************************************************\n" + << "* The configuration (ptOfProbe > " << ptOfProbe_ + << "GeV) is not correctly set for current value of magnetic field \n" + << "* Switching it to 0. !!! \n" + << "*********************************************************************************" << std::endl; + ptOfProbe_ = 0.; + } + + //======================================================= + // Run numbers analysis + //======================================================= + + const auto runNumber_ = iRun.run(); + h_runNumber->Fill(runNumber_); + + if (!runNumbersTimesLog_.count(runNumber_)) { + auto times = getRunTime(iSetup); + + if (debug_) { + const time_t start_time = times.first / 1000000; + edm::LogInfo("PrimaryVertexValidation") + << runNumber_ << " has start time: " << times.first << " - " << times.second << std::endl; + edm::LogInfo("PrimaryVertexValidation") + << "human readable time: " << std::asctime(std::gmtime(&start_time)) << std::endl; + } + + runNumbersTimesLog_[runNumber_] = times; + } + + if (h_runFromEvent->GetEntries() == 0) { + h_runFromEvent->SetBinContent(1, RunNumber_); + } + + //======================================================= + // Retrieve tracker topology from geometry + //======================================================= + + const TrackerTopology* const tTopo = &iSetup.getData(topoTokenBR_); + + //======================================================= + // Retrieve geometry information + //======================================================= + + edm::LogInfo("read tracker geometry..."); + edm::ESHandle pDD = iSetup.getHandle(geomTokenBR_); + edm::LogInfo("tracker geometry read") << "There are: " << pDD->dets().size() << " detectors"; + + PixelTopologyMap PTMap = PixelTopologyMap(pDD.product(), tTopo); + nLadders_ = PTMap.getPXBLadders(1); + nModZ_ = PTMap.getPXBModules(1); + + //======================================================= + // shrink to fit + //======================================================= + + if (h_dxy_ladderOverlap_.size() != nLadders_) { + PVValHelper::shrinkHistVectorToFit(h_dxy_ladderOverlap_, nLadders_); + PVValHelper::shrinkHistVectorToFit(h_dxy_ladderNoOverlap_, nLadders_); + PVValHelper::shrinkHistVectorToFit(h_dxy_ladder_, nLadders_); + PVValHelper::shrinkHistVectorToFit(h_dz_ladder_, nLadders_); + PVValHelper::shrinkHistVectorToFit(h_norm_dxy_ladder_, nLadders_); + PVValHelper::shrinkHistVectorToFit(h_norm_dz_ladder_, nLadders_); + + if (debug_) { + edm::LogInfo("PrimaryVertexValidation") << "checking size:" << h_dxy_ladder_.size() << std::endl; + } + } + + if (h_dxy_modZ_.size() != nModZ_) { + PVValHelper::shrinkHistVectorToFit(h_dxy_modZ_, nModZ_); + PVValHelper::shrinkHistVectorToFit(h_dz_modZ_, nModZ_); + PVValHelper::shrinkHistVectorToFit(h_norm_dxy_modZ_, nModZ_); + PVValHelper::shrinkHistVectorToFit(h_norm_dxy_modZ_, nModZ_); + + if (debug_) { + edm::LogInfo("PrimaryVertexValidation") << "checking size:" << h_dxy_modZ_.size() << std::endl; + } + } + + if ((pDD->isThere(GeomDetEnumerators::P2PXB)) || (pDD->isThere(GeomDetEnumerators::P2PXEC))) { + // switch on the phase-2 + phase_ = PVValHelper::phase2; + if (debug_) { + edm::LogInfo("PrimaryVertexValidation") + << " pixel phase2 setup, nLadders: " << nLadders_ << " nModules:" << nModZ_; + } + + } else if ((pDD->isThere(GeomDetEnumerators::P1PXB)) || (pDD->isThere(GeomDetEnumerators::P1PXEC))) { + // switch on the phase-1 + if (debug_) { + edm::LogInfo("PrimaryVertexValidation") + << " pixel phase1 setup, nLadders: " << nLadders_ << " nModules:" << nModZ_; + } + } else { + // switch on the phase-0 + phase_ = PVValHelper::phase0; + if (debug_) { + edm::LogInfo("PrimaryVertexValidation") + << " pixel phase0 setup, nLadders: " << nLadders_ << " nModules:" << nModZ_; + } + } + + switch (phase_) { + case PVValHelper::phase0: + etaOfProbe_ = std::min(etaOfProbe_, PVValHelper::max_eta_phase0); + break; + case PVValHelper::phase1: + etaOfProbe_ = std::min(etaOfProbe_, PVValHelper::max_eta_phase1); + break; + case PVValHelper::phase2: + etaOfProbe_ = std::min(etaOfProbe_, PVValHelper::max_eta_phase2); + break; + default: + edm::LogWarning("LogicError") << "Unknown detector phase: " << phase_; + } + + if (h_etaMax->GetEntries() == 0.) { + h_etaMax->SetBinContent(1., etaOfProbe_); + h_nbins->SetBinContent(1., nBins_); + h_nLadders->SetBinContent(1., nLadders_); + h_nModZ->SetBinContent(1., nModZ_); + h_pTinfo->SetBinContent(1., mypT_bins_.size()); + h_pTinfo->SetBinContent(2., minPt_); + h_pTinfo->SetBinContent(3., maxPt_); + } +} + // ------------ method called once each job just after ending the event loop ------------ void PrimaryVertexValidation::endJob() { // shring the histograms to fit @@ -3040,7 +3028,7 @@ void PrimaryVertexValidation::endJob() { std::pair PrimaryVertexValidation::getRunTime(const edm::EventSetup& iSetup) const //************************************************************* { - edm::ESHandle runInfo = iSetup.getHandle(runInfoToken_); + edm::ESHandle runInfo = iSetup.getHandle(runInfoTokenBR_); if (debug_) { edm::LogInfo("PrimaryVertexValidation") << runInfo.product()->m_start_time_str << " " << runInfo.product()->m_stop_time_str << std::endl; @@ -3052,7 +3040,7 @@ std::pair PrimaryVertexValidation::getRunTime(const edm::E bool PrimaryVertexValidation::isBFieldConsistentWithMode(const edm::EventSetup& iSetup) const //************************************************************* { - edm::ESHandle runInfo = iSetup.getHandle(runInfoToken_); + edm::ESHandle runInfo = iSetup.getHandle(runInfoTokenBR_); double average_current = runInfo.product()->m_avg_current; bool isOn = (average_current > 2000.); bool is0T = (ptOfProbe_ == 0.); diff --git a/Alignment/OfflineValidation/plugins/PrimaryVertexValidation.h b/Alignment/OfflineValidation/plugins/PrimaryVertexValidation.h index 3d5f4603fd18a..8d962fa678b82 100644 --- a/Alignment/OfflineValidation/plugins/PrimaryVertexValidation.h +++ b/Alignment/OfflineValidation/plugins/PrimaryVertexValidation.h @@ -70,16 +70,21 @@ // class decleration // -class PrimaryVertexValidation : public edm::one::EDAnalyzer { +class PrimaryVertexValidation : public edm::one::EDAnalyzer { public: explicit PrimaryVertexValidation(const edm::ParameterSet&); ~PrimaryVertexValidation() override; static void fillDescriptions(edm::ConfigurationDescriptions& descriptions); private: + // framework provided methods void beginJob() override; + void beginRun(edm::Run const& iRun, edm::EventSetup const& iSetup) override; void analyze(const edm::Event&, const edm::EventSetup&) override; + void endRun(edm::Run const&, edm::EventSetup const&) override{}; void endJob() override; + + // user defined methods bool isBFieldConsistentWithMode(const edm::EventSetup& iSetup) const; std::pair getRunTime(const edm::EventSetup& iSetup) const; bool isHit2D(const TrackingRecHit& hit, const PVValHelper::detectorPhase& thePhase) const; @@ -148,10 +153,11 @@ class PrimaryVertexValidation : public edm::one::EDAnalyzer magFieldToken_; const edm::ESGetToken trackingGeomToken_; - const edm::ESGetToken geomToken_; const edm::ESGetToken ttkToken_; const edm::ESGetToken topoToken_; - const edm::ESGetToken runInfoToken_; + const edm::ESGetToken topoTokenBR_; + const edm::ESGetToken geomTokenBR_; + const edm::ESGetToken runInfoTokenBR_; const int compressionSettings_; // determines the ROOT compression settings in TFileService bool storeNtuple_; @@ -192,9 +198,9 @@ class PrimaryVertexValidation : public edm::one::EDAnalyzer theTrackCollectionToken; - edm::EDGetTokenT theVertexCollectionToken; - edm::EDGetTokenT theBeamspotToken; + edm::EDGetTokenT theTrackCollectionToken_; + edm::EDGetTokenT theVertexCollectionToken_; + edm::EDGetTokenT theBeamspotToken_; TTree* rootTree_; diff --git a/Alignment/OfflineValidation/plugins/SplitVertexResolution.cc b/Alignment/OfflineValidation/plugins/SplitVertexResolution.cc index 17a5fbee2b3ed..31cfe37cee3bc 100644 --- a/Alignment/OfflineValidation/plugins/SplitVertexResolution.cc +++ b/Alignment/OfflineValidation/plugins/SplitVertexResolution.cc @@ -290,7 +290,7 @@ SplitVertexResolution::SplitVertexResolution(const edm::ParameterSet& iConfig) std::copy(vect.begin(), vect.begin() + nVtxBins_ + 1, myNVtx_bins_.begin()); } -SplitVertexResolution::~SplitVertexResolution() {} +SplitVertexResolution::~SplitVertexResolution() = default; // ------------ method called for each event ------------ void SplitVertexResolution::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) { diff --git a/Alignment/OfflineValidation/plugins/TrackerGeometryCompare.cc b/Alignment/OfflineValidation/plugins/TrackerGeometryCompare.cc index db2bb31492f23..7e18306f624bb 100644 --- a/Alignment/OfflineValidation/plugins/TrackerGeometryCompare.cc +++ b/Alignment/OfflineValidation/plugins/TrackerGeometryCompare.cc @@ -54,7 +54,7 @@ TrackerGeometryCompare::TrackerGeometryCompare(const edm::ParameterSet& cfg) : cpvTokenDDD_(esConsumes()), - cpvTokenDD4Hep_(esConsumes()), + cpvTokenDD4hep_(esConsumes()), topoToken_(esConsumes()), geomDetToken_(esConsumes()), ptpToken_(esConsumes()), @@ -363,7 +363,7 @@ void TrackerGeometryCompare::createROOTGeometry(const edm::EventSetup& iSetup) { if (!fromDD4hep_) { edm::ESTransientHandle cpv = iSetup.getTransientHandle(cpvTokenDDD_); } else { - edm::ESTransientHandle cpv = iSetup.getTransientHandle(cpvTokenDD4Hep_); + edm::ESTransientHandle cpv = iSetup.getTransientHandle(cpvTokenDD4hep_); } const GeometricDet* theGeometricDet = &iSetup.getData(geomDetToken_); diff --git a/Alignment/OfflineValidation/plugins/TrackerGeometryCompare.h b/Alignment/OfflineValidation/plugins/TrackerGeometryCompare.h index 33547a383fe6b..8dba3aab28c9b 100644 --- a/Alignment/OfflineValidation/plugins/TrackerGeometryCompare.h +++ b/Alignment/OfflineValidation/plugins/TrackerGeometryCompare.h @@ -85,7 +85,7 @@ class TrackerGeometryCompare : public edm::one::EDAnalyzer<> { bool passIdCut(uint32_t); const edm::ESGetToken cpvTokenDDD_; - const edm::ESGetToken cpvTokenDD4Hep_; + const edm::ESGetToken cpvTokenDD4hep_; const edm::ESGetToken topoToken_; const edm::ESGetToken geomDetToken_; const edm::ESGetToken ptpToken_; diff --git a/Alignment/OfflineValidation/python/TkAlAllInOneTool/dataset.py b/Alignment/OfflineValidation/python/TkAlAllInOneTool/dataset.py index a6790bb04a1d5..7c3fd08b497b3 100644 --- a/Alignment/OfflineValidation/python/TkAlAllInOneTool/dataset.py +++ b/Alignment/OfflineValidation/python/TkAlAllInOneTool/dataset.py @@ -753,7 +753,7 @@ def datasetSnippet( self, jsonPath = None, begin = None, end = None, if self.__predefined: snippet = ("process.load(\"Alignment.OfflineValidation.%s_cff\")\n" "process.maxEvents = cms.untracked.PSet(\n" - " input = cms.untracked.int32(.oO[nEvents]Oo. / .oO[parallelJobs]Oo.)\n" + " input = cms.untracked.int32(int(.oO[nEvents]Oo. / .oO[parallelJobs]Oo.))\n" ")\n" "process.source.skipEvents=cms.untracked.uint32(int(.oO[nIndex]Oo.*.oO[nEvents]Oo./.oO[parallelJobs]Oo.))" %(self.__name)) diff --git a/Alignment/OfflineValidation/scripts/validateAlignments.py b/Alignment/OfflineValidation/scripts/validateAlignments.py index dbcc0756efa65..9b4df8579c336 100755 --- a/Alignment/OfflineValidation/scripts/validateAlignments.py +++ b/Alignment/OfflineValidation/scripts/validateAlignments.py @@ -646,7 +646,7 @@ def main(argv = None): (options, args) = optParser.parse_args(argv) if not options.dryRun: - schedinfo = subprocess.check_output(["myschedd","show"]) + schedinfo = subprocess.check_output(["myschedd","show"]).decode() if not 'tzero' in schedinfo: print("\nAll-In-One Tool: you need to call `module load lxbatch/tzero` before trying to submit jobs. Please do so and try again") exit(1) diff --git a/Alignment/ReferenceTrajectories/interface/TrajectoryFactoryBase.h b/Alignment/ReferenceTrajectories/interface/TrajectoryFactoryBase.h index 191d29d92726c..54ffd052b2aa5 100644 --- a/Alignment/ReferenceTrajectories/interface/TrajectoryFactoryBase.h +++ b/Alignment/ReferenceTrajectories/interface/TrajectoryFactoryBase.h @@ -10,6 +10,7 @@ #include "FWCore/ParameterSet/interface/ParameterSet.h" +#include "FWCore/Framework/interface/ConsumesCollector.h" /// Base class for factories producing reference trajectories, i.e. instances of classes deriving from /// ReferenceTrajectoryBase, from a TrajTrackPairCollection. @@ -27,8 +28,10 @@ class TrajectoryFactoryBase { typedef std::pair TrajectoryInput; typedef std::vector ExternalPredictionCollection; - TrajectoryFactoryBase(const edm::ParameterSet& config); - TrajectoryFactoryBase(const edm::ParameterSet& config, unsigned int tracksPerTrajectory); + TrajectoryFactoryBase(const edm::ParameterSet& config, const edm::ConsumesCollector& iC); + TrajectoryFactoryBase(const edm::ParameterSet& config, + unsigned int tracksPerTrajectory, + const edm::ConsumesCollector& iC); virtual ~TrajectoryFactoryBase(void); virtual const ReferenceTrajectoryCollection trajectories(const edm::EventSetup& setup, diff --git a/Alignment/ReferenceTrajectories/interface/TrajectoryFactoryPlugin.h b/Alignment/ReferenceTrajectories/interface/TrajectoryFactoryPlugin.h index 4ce8bfa38c038..3288e6f56d58c 100644 --- a/Alignment/ReferenceTrajectories/interface/TrajectoryFactoryPlugin.h +++ b/Alignment/ReferenceTrajectories/interface/TrajectoryFactoryPlugin.h @@ -8,6 +8,7 @@ /// A PluginFactory that produces factories that inherit from TrajectoryFactoryBase. -typedef edmplugin::PluginFactory TrajectoryFactoryPlugin; +typedef edmplugin::PluginFactory + TrajectoryFactoryPlugin; #endif diff --git a/Alignment/ReferenceTrajectories/plugins/BzeroReferenceTrajectoryFactory.cc b/Alignment/ReferenceTrajectories/plugins/BzeroReferenceTrajectoryFactory.cc index b237810c4fe90..2000da10c8962 100644 --- a/Alignment/ReferenceTrajectories/plugins/BzeroReferenceTrajectoryFactory.cc +++ b/Alignment/ReferenceTrajectories/plugins/BzeroReferenceTrajectoryFactory.cc @@ -20,8 +20,10 @@ ///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// -BzeroReferenceTrajectoryFactory::BzeroReferenceTrajectoryFactory(const edm::ParameterSet &config) - : TrajectoryFactoryBase(config), +BzeroReferenceTrajectoryFactory::BzeroReferenceTrajectoryFactory(const edm::ParameterSet &config, + edm::ConsumesCollector &iC) + : TrajectoryFactoryBase(config, iC), + m_MagFieldToken(iC.esConsumes()), theMass(config.getParameter("ParticleMass")), theMomentumEstimate(config.getParameter("MomentumEstimate")) { edm::LogInfo("Alignment") << "@SUB=BzeroReferenceTrajectoryFactory" @@ -35,8 +37,7 @@ const BzeroReferenceTrajectoryFactory::ReferenceTrajectoryCollection BzeroRefere const edm::EventSetup &setup, const ConstTrajTrackPairCollection &tracks, const reco::BeamSpot &beamSpot) const { ReferenceTrajectoryCollection trajectories; - edm::ESHandle magneticField; - setup.get().get(magneticField); + const MagneticField *magneticField = &setup.getData(m_MagFieldToken); ConstTrajTrackPairCollection::const_iterator itTracks = tracks.begin(); @@ -51,7 +52,7 @@ const BzeroReferenceTrajectoryFactory::ReferenceTrajectoryCollection BzeroRefere // set the flag for reversing the RecHits to false, since they are already in the correct order. config.hitsAreReverse = false; trajectories.push_back(ReferenceTrajectoryPtr( - new BzeroReferenceTrajectory(input.first, input.second, magneticField.product(), beamSpot, config))); + new BzeroReferenceTrajectory(input.first, input.second, magneticField, beamSpot, config))); } ++itTracks; @@ -76,8 +77,7 @@ const BzeroReferenceTrajectoryFactory::ReferenceTrajectoryCollection BzeroRefere return trajectories; } - edm::ESHandle magneticField; - setup.get().get(magneticField); + const MagneticField *magneticField = &setup.getData(m_MagFieldToken); ConstTrajTrackPairCollection::const_iterator itTracks = tracks.begin(); ExternalPredictionCollection::const_iterator itExternal = external.begin(); @@ -94,7 +94,7 @@ const BzeroReferenceTrajectoryFactory::ReferenceTrajectoryCollection BzeroRefere // set the flag for reversing the RecHits to false, since they are already in the correct order. config.hitsAreReverse = false; ReferenceTrajectoryPtr refTraj( - new BzeroReferenceTrajectory(*itExternal, input.second, magneticField.product(), beamSpot, config)); + new BzeroReferenceTrajectory(*itExternal, input.second, magneticField, beamSpot, config)); AlgebraicSymMatrix externalParamErrors(asHepMatrix<5>((*itExternal).localError().matrix())); refTraj->setParameterErrors(externalParamErrors.sub(2, 5)); @@ -108,7 +108,7 @@ const BzeroReferenceTrajectoryFactory::ReferenceTrajectoryCollection BzeroRefere // set the flag for reversing the RecHits to false, since they are already in the correct order. config.hitsAreReverse = false; trajectories.push_back(ReferenceTrajectoryPtr( - new BzeroReferenceTrajectory(input.first, input.second, magneticField.product(), beamSpot, config))); + new BzeroReferenceTrajectory(input.first, input.second, magneticField, beamSpot, config))); } } diff --git a/Alignment/ReferenceTrajectories/plugins/BzeroReferenceTrajectoryFactory.h b/Alignment/ReferenceTrajectories/plugins/BzeroReferenceTrajectoryFactory.h index eba346053f071..a64abf0260df4 100644 --- a/Alignment/ReferenceTrajectories/plugins/BzeroReferenceTrajectoryFactory.h +++ b/Alignment/ReferenceTrajectories/plugins/BzeroReferenceTrajectoryFactory.h @@ -1,4 +1,5 @@ #include "Alignment/ReferenceTrajectories/interface/TrajectoryFactoryBase.h" +#include "MagneticField/Records/interface/IdealMagneticFieldRecord.h" namespace edm { class ParameterSet; @@ -13,9 +14,8 @@ namespace reco { class BzeroReferenceTrajectoryFactory : public TrajectoryFactoryBase { public: - BzeroReferenceTrajectoryFactory(const edm::ParameterSet &config); + BzeroReferenceTrajectoryFactory(const edm::ParameterSet &config, edm::ConsumesCollector &iC); ~BzeroReferenceTrajectoryFactory() override; - /// Produce the reference trajectories. const ReferenceTrajectoryCollection trajectories(const edm::EventSetup &setup, const ConstTrajTrackPairCollection &tracks, @@ -28,6 +28,8 @@ class BzeroReferenceTrajectoryFactory : public TrajectoryFactoryBase { BzeroReferenceTrajectoryFactory *clone() const override { return new BzeroReferenceTrajectoryFactory(*this); } + const edm::ESGetToken m_MagFieldToken; + private: double theMass; double theMomentumEstimate; diff --git a/Alignment/ReferenceTrajectories/plugins/CombinedTrajectoryFactory.cc b/Alignment/ReferenceTrajectories/plugins/CombinedTrajectoryFactory.cc index 91d9adee5c7af..699678cbb5460 100644 --- a/Alignment/ReferenceTrajectories/plugins/CombinedTrajectoryFactory.cc +++ b/Alignment/ReferenceTrajectories/plugins/CombinedTrajectoryFactory.cc @@ -23,7 +23,7 @@ class CombinedTrajectoryFactory : public TrajectoryFactoryBase { public: - CombinedTrajectoryFactory(const edm::ParameterSet &config); + CombinedTrajectoryFactory(const edm::ParameterSet &config, edm::ConsumesCollector &iC); ~CombinedTrajectoryFactory() override; const ReferenceTrajectoryCollection trajectories(const edm::EventSetup &setup, @@ -56,8 +56,8 @@ class CombinedTrajectoryFactory : public TrajectoryFactoryBase { using namespace std; -CombinedTrajectoryFactory::CombinedTrajectoryFactory(const edm::ParameterSet &config) - : TrajectoryFactoryBase(config), theUseAllFactories(config.getParameter("useAllFactories")) { +CombinedTrajectoryFactory::CombinedTrajectoryFactory(const edm::ParameterSet &config, edm::ConsumesCollector &iC) + : TrajectoryFactoryBase(config, iC), theUseAllFactories(config.getParameter("useAllFactories")) { vector factoryNames = config.getParameter>("TrajectoryFactoryNames"); for (auto const &factoryName : factoryNames) { // auto_ptr to avoid missing a delete due to throw... @@ -68,7 +68,7 @@ CombinedTrajectoryFactory::CombinedTrajectoryFactory(const edm::ParameterSet &co << "separated strings, but is '" << factoryName << "'"; } const edm::ParameterSet factoryCfg = config.getParameter(namePset->At(1)->GetName()); - theFactories.emplace_back(TrajectoryFactoryPlugin::get()->create(namePset->At(0)->GetName(), factoryCfg)); + theFactories.emplace_back(TrajectoryFactoryPlugin::get()->create(namePset->At(0)->GetName(), factoryCfg, iC)); } } diff --git a/Alignment/ReferenceTrajectories/plugins/DualBzeroTrajectoryFactory.cc b/Alignment/ReferenceTrajectories/plugins/DualBzeroTrajectoryFactory.cc index 81918c252ed86..b2ab00fb83bab 100644 --- a/Alignment/ReferenceTrajectories/plugins/DualBzeroTrajectoryFactory.cc +++ b/Alignment/ReferenceTrajectories/plugins/DualBzeroTrajectoryFactory.cc @@ -16,8 +16,9 @@ class DualBzeroTrajectoryFactory : public TrajectoryFactoryBase { public: - DualBzeroTrajectoryFactory(const edm::ParameterSet &config); + DualBzeroTrajectoryFactory(const edm::ParameterSet &config, edm::ConsumesCollector &iC); ~DualBzeroTrajectoryFactory() override; + const edm::ESGetToken m_MagFieldToken; /// Produce the reference trajectories. const ReferenceTrajectoryCollection trajectories(const edm::EventSetup &setup, @@ -52,8 +53,8 @@ class DualBzeroTrajectoryFactory : public TrajectoryFactoryBase { //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -DualBzeroTrajectoryFactory::DualBzeroTrajectoryFactory(const edm::ParameterSet &config) - : TrajectoryFactoryBase(config) { +DualBzeroTrajectoryFactory::DualBzeroTrajectoryFactory(const edm::ParameterSet &config, edm::ConsumesCollector &iC) + : TrajectoryFactoryBase(config, iC), m_MagFieldToken(iC.esConsumes()) { theMass = config.getParameter("ParticleMass"); theMomentumEstimate = config.getParameter("MomentumEstimate"); } @@ -64,8 +65,7 @@ const DualBzeroTrajectoryFactory::ReferenceTrajectoryCollection DualBzeroTraject const edm::EventSetup &setup, const ConstTrajTrackPairCollection &tracks, const reco::BeamSpot &beamSpot) const { ReferenceTrajectoryCollection trajectories; - edm::ESHandle magneticField; - setup.get().get(magneticField); + const MagneticField *magneticField = &setup.getData(m_MagFieldToken); ConstTrajTrackPairCollection::const_iterator itTracks = tracks.begin(); @@ -78,7 +78,7 @@ const DualBzeroTrajectoryFactory::ReferenceTrajectoryCollection DualBzeroTraject config.includeAPEs = includeAPEs_; config.allowZeroMaterial = allowZeroMaterial_; ReferenceTrajectoryPtr ptr(new DualBzeroReferenceTrajectory( - input.refTsos, input.fwdRecHits, input.bwdRecHits, magneticField.product(), beamSpot, config)); + input.refTsos, input.fwdRecHits, input.bwdRecHits, magneticField, beamSpot, config)); trajectories.push_back(ptr); } @@ -103,8 +103,7 @@ const DualBzeroTrajectoryFactory::ReferenceTrajectoryCollection DualBzeroTraject return trajectories; } - edm::ESHandle magneticField; - setup.get().get(magneticField); + const MagneticField *magneticField = &setup.getData(m_MagFieldToken); ConstTrajTrackPairCollection::const_iterator itTracks = tracks.begin(); ExternalPredictionCollection::const_iterator itExternal = external.begin(); @@ -114,8 +113,7 @@ const DualBzeroTrajectoryFactory::ReferenceTrajectoryCollection DualBzeroTraject // Check input: If all hits were rejected, the TSOS is initialized as invalid. if (input.refTsos.isValid()) { if ((*itExternal).isValid()) { - TrajectoryStateOnSurface propExternal = - propagateExternal(*itExternal, input.refTsos.surface(), magneticField.product()); + TrajectoryStateOnSurface propExternal = propagateExternal(*itExternal, input.refTsos.surface(), magneticField); if (!propExternal.isValid()) continue; @@ -125,7 +123,7 @@ const DualBzeroTrajectoryFactory::ReferenceTrajectoryCollection DualBzeroTraject config.includeAPEs = includeAPEs_; config.allowZeroMaterial = allowZeroMaterial_; ReferenceTrajectoryPtr ptr(new DualBzeroReferenceTrajectory( - propExternal, input.fwdRecHits, input.bwdRecHits, magneticField.product(), beamSpot, config)); + propExternal, input.fwdRecHits, input.bwdRecHits, magneticField, beamSpot, config)); AlgebraicSymMatrix externalParamErrors(asHepMatrix<5>(propExternal.localError().matrix())); ptr->setParameterErrors(externalParamErrors.sub(2, 5)); @@ -136,7 +134,7 @@ const DualBzeroTrajectoryFactory::ReferenceTrajectoryCollection DualBzeroTraject config.includeAPEs = includeAPEs_; config.allowZeroMaterial = allowZeroMaterial_; ReferenceTrajectoryPtr ptr(new DualBzeroReferenceTrajectory( - input.refTsos, input.fwdRecHits, input.bwdRecHits, magneticField.product(), beamSpot, config)); + input.refTsos, input.fwdRecHits, input.bwdRecHits, magneticField, beamSpot, config)); trajectories.push_back(ptr); } diff --git a/Alignment/ReferenceTrajectories/plugins/DualTrajectoryFactory.cc b/Alignment/ReferenceTrajectories/plugins/DualTrajectoryFactory.cc index d4fd9a4cf3ab1..447152cd28f79 100644 --- a/Alignment/ReferenceTrajectories/plugins/DualTrajectoryFactory.cc +++ b/Alignment/ReferenceTrajectories/plugins/DualTrajectoryFactory.cc @@ -16,8 +16,9 @@ class DualTrajectoryFactory : public TrajectoryFactoryBase { public: - DualTrajectoryFactory(const edm::ParameterSet &config); + DualTrajectoryFactory(const edm::ParameterSet &config, edm::ConsumesCollector &iC); ~DualTrajectoryFactory() override; + const edm::ESGetToken m_MagFieldToken; /// Produce the reference trajectories. const ReferenceTrajectoryCollection trajectories(const edm::EventSetup &setup, @@ -51,8 +52,10 @@ class DualTrajectoryFactory : public TrajectoryFactoryBase { //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -DualTrajectoryFactory::DualTrajectoryFactory(const edm::ParameterSet &config) - : TrajectoryFactoryBase(config), theMass(config.getParameter("ParticleMass")) { +DualTrajectoryFactory::DualTrajectoryFactory(const edm::ParameterSet &config, edm::ConsumesCollector &iC) + : TrajectoryFactoryBase(config, iC), + m_MagFieldToken(iC.esConsumes()), + theMass(config.getParameter("ParticleMass")) { edm::LogInfo("Alignment") << "@SUB=DualTrajectoryFactory" << "mass: " << theMass; } @@ -63,8 +66,8 @@ const DualTrajectoryFactory::ReferenceTrajectoryCollection DualTrajectoryFactory const edm::EventSetup &setup, const ConstTrajTrackPairCollection &tracks, const reco::BeamSpot &beamSpot) const { ReferenceTrajectoryCollection trajectories; - edm::ESHandle magneticField; - setup.get().get(magneticField); + const MagneticField *magneticField = &setup.getData(m_MagFieldToken); + if (magneticField->inTesla(GlobalPoint(0., 0., 0.)).mag2() < 1.e-6) { edm::LogWarning("Alignment") << "@SUB=DualTrajectoryFactory::trajectories" << "B-field in z is " << magneticField->inTesla(GlobalPoint(0., 0., 0.)).z() @@ -83,7 +86,7 @@ const DualTrajectoryFactory::ReferenceTrajectoryCollection DualTrajectoryFactory config.includeAPEs = includeAPEs_; config.allowZeroMaterial = allowZeroMaterial_; ReferenceTrajectoryPtr ptr(new DualReferenceTrajectory( - input.refTsos, input.fwdRecHits, input.bwdRecHits, magneticField.product(), beamSpot, config)); + input.refTsos, input.fwdRecHits, input.bwdRecHits, magneticField, beamSpot, config)); trajectories.push_back(ptr); } @@ -107,9 +110,8 @@ const DualTrajectoryFactory::ReferenceTrajectoryCollection DualTrajectoryFactory << "\tnumber of tracks = " << tracks.size() << "\tnumber of external predictions = " << external.size(); return trajectories; } + const MagneticField *magneticField = &setup.getData(m_MagFieldToken); - edm::ESHandle magneticField; - setup.get().get(magneticField); if (magneticField->inTesla(GlobalPoint(0., 0., 0.)).mag2() < 1.e-6) { edm::LogWarning("Alignment") << "@SUB=DualTrajectoryFactory::trajectories" << "B-field in z is " << magneticField->inTesla(GlobalPoint(0., 0., 0.)).z() @@ -125,8 +127,7 @@ const DualTrajectoryFactory::ReferenceTrajectoryCollection DualTrajectoryFactory // Check input: If all hits were rejected, the TSOS is initialized as invalid. if (input.refTsos.isValid()) { if ((*itExternal).isValid()) { - TrajectoryStateOnSurface propExternal = - propagateExternal(*itExternal, input.refTsos.surface(), magneticField.product()); + TrajectoryStateOnSurface propExternal = propagateExternal(*itExternal, input.refTsos.surface(), magneticField); if (!propExternal.isValid()) continue; @@ -136,7 +137,7 @@ const DualTrajectoryFactory::ReferenceTrajectoryCollection DualTrajectoryFactory config.includeAPEs = includeAPEs_; config.allowZeroMaterial = allowZeroMaterial_; ReferenceTrajectoryPtr ptr(new DualReferenceTrajectory( - propExternal, input.fwdRecHits, input.bwdRecHits, magneticField.product(), beamSpot, config)); + propExternal, input.fwdRecHits, input.bwdRecHits, magneticField, beamSpot, config)); AlgebraicSymMatrix externalParamErrors(asHepMatrix<5>(propExternal.localError().matrix())); ptr->setParameterErrors(externalParamErrors); @@ -147,7 +148,7 @@ const DualTrajectoryFactory::ReferenceTrajectoryCollection DualTrajectoryFactory config.includeAPEs = includeAPEs_; config.allowZeroMaterial = allowZeroMaterial_; ReferenceTrajectoryPtr ptr(new DualReferenceTrajectory( - input.refTsos, input.fwdRecHits, input.bwdRecHits, magneticField.product(), beamSpot, config)); + input.refTsos, input.fwdRecHits, input.bwdRecHits, magneticField, beamSpot, config)); trajectories.push_back(ptr); } } diff --git a/Alignment/ReferenceTrajectories/plugins/ReferenceTrajectoryFactory.cc b/Alignment/ReferenceTrajectories/plugins/ReferenceTrajectoryFactory.cc index d592a39ce8e00..9e1fa615728ad 100644 --- a/Alignment/ReferenceTrajectories/plugins/ReferenceTrajectoryFactory.cc +++ b/Alignment/ReferenceTrajectories/plugins/ReferenceTrajectoryFactory.cc @@ -19,8 +19,9 @@ class ReferenceTrajectoryFactory : public TrajectoryFactoryBase { public: - ReferenceTrajectoryFactory(const edm::ParameterSet &config); + ReferenceTrajectoryFactory(const edm::ParameterSet &config, edm::ConsumesCollector &iC); ~ReferenceTrajectoryFactory() override; + const edm::ESGetToken m_MagFieldToken; /// Produce the reference trajectories. const ReferenceTrajectoryCollection trajectories(const edm::EventSetup &setup, @@ -37,9 +38,11 @@ class ReferenceTrajectoryFactory : public TrajectoryFactoryBase { protected: ReferenceTrajectoryFactory(const ReferenceTrajectoryFactory &other); const TrajectoryFactoryBase *bzeroFactory() const; + const TrajectoryFactoryBase *bzeroFactory(edm::ConsumesCollector &iC) const; double theMass; bool theUseBzeroIfFieldOff; + //edm::ParameterSet pset; mutable const TrajectoryFactoryBase *theBzeroFactory; }; @@ -47,14 +50,25 @@ class ReferenceTrajectoryFactory : public TrajectoryFactoryBase { //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -ReferenceTrajectoryFactory::ReferenceTrajectoryFactory(const edm::ParameterSet &config) - : TrajectoryFactoryBase(config), +ReferenceTrajectoryFactory::ReferenceTrajectoryFactory(const edm::ParameterSet &config, edm::ConsumesCollector &iC) + : TrajectoryFactoryBase(config, iC), + m_MagFieldToken(iC.esConsumes()), theMass(config.getParameter("ParticleMass")), theUseBzeroIfFieldOff(config.getParameter("UseBzeroIfFieldOff")), theBzeroFactory(nullptr) { edm::LogInfo("Alignment") << "@SUB=ReferenceTrajectoryFactory" << "mass: " << theMass << "\nusing Bzero if |B| = 0: " << (theUseBzeroIfFieldOff ? "yes" : "no"); + // We take the config of this factory, copy it, replace its name and add + // the momentum parameter as expected by BzeroReferenceTrajectoryFactory and create it: + // + edm::ParameterSet pset; + pset.copyForModify(config); + // next two lines not needed, but may help to better understand log file: + pset.eraseSimpleParameter("TrajectoryFactoryName"); + pset.addParameter("TrajectoryFactoryName", std::string("BzeroReferenceTrajectoryFactory")); + pset.addParameter("MomentumEstimate", config.getParameter("MomentumEstimateFieldOff")); + theBzeroFactory = new BzeroReferenceTrajectoryFactory(pset, iC); } ReferenceTrajectoryFactory::ReferenceTrajectoryFactory(const ReferenceTrajectoryFactory &other) @@ -68,8 +82,8 @@ ReferenceTrajectoryFactory::~ReferenceTrajectoryFactory(void) { delete theBzeroF const ReferenceTrajectoryFactory::ReferenceTrajectoryCollection ReferenceTrajectoryFactory::trajectories( const edm::EventSetup &setup, const ConstTrajTrackPairCollection &tracks, const reco::BeamSpot &beamSpot) const { - edm::ESHandle magneticField; - setup.get().get(magneticField); + const MagneticField *magneticField = &setup.getData(m_MagFieldToken); + if (theUseBzeroIfFieldOff && magneticField->inTesla(GlobalPoint(0., 0., 0.)).mag2() < 1.e-6) { return this->bzeroFactory()->trajectories(setup, tracks, beamSpot); } @@ -89,8 +103,8 @@ const ReferenceTrajectoryFactory::ReferenceTrajectoryCollection ReferenceTraject config.allowZeroMaterial = allowZeroMaterial_; // set the flag for reversing the RecHits to false, since they are already in the correct order. config.hitsAreReverse = false; - trajectories.push_back(ReferenceTrajectoryPtr( - new ReferenceTrajectory(input.first, input.second, magneticField.product(), beamSpot, config))); + trajectories.push_back( + ReferenceTrajectoryPtr(new ReferenceTrajectory(input.first, input.second, magneticField, beamSpot, config))); } ++itTracks; @@ -113,9 +127,8 @@ const ReferenceTrajectoryFactory::ReferenceTrajectoryCollection ReferenceTraject << "\tnumber of tracks = " << tracks.size() << "\tnumber of external predictions = " << external.size(); return trajectories; } + const MagneticField *magneticField = &setup.getData(m_MagFieldToken); - edm::ESHandle magneticField; - setup.get().get(magneticField); if (theUseBzeroIfFieldOff && magneticField->inTesla(GlobalPoint(0., 0., 0.)).mag2() < 1.e-6) { return this->bzeroFactory()->trajectories(setup, tracks, external, beamSpot); } @@ -135,7 +148,7 @@ const ReferenceTrajectoryFactory::ReferenceTrajectoryCollection ReferenceTraject // set the flag for reversing the RecHits to false, since they are already in the correct order. config.hitsAreReverse = false; ReferenceTrajectoryPtr refTraj( - new ReferenceTrajectory(*itExternal, input.second, magneticField.product(), beamSpot, config)); + new ReferenceTrajectory(*itExternal, input.second, magneticField, beamSpot, config)); AlgebraicSymMatrix externalParamErrors(asHepMatrix<5>((*itExternal).localError().matrix())); refTraj->setParameterErrors(externalParamErrors); @@ -147,7 +160,7 @@ const ReferenceTrajectoryFactory::ReferenceTrajectoryCollection ReferenceTraject config.allowZeroMaterial = allowZeroMaterial_; config.hitsAreReverse = false; trajectories.push_back(ReferenceTrajectoryPtr( - new ReferenceTrajectory(input.first, input.second, magneticField.product(), beamSpot, config))); + new ReferenceTrajectory(input.first, input.second, magneticField, beamSpot, config))); } } @@ -160,18 +173,8 @@ const ReferenceTrajectoryFactory::ReferenceTrajectoryCollection ReferenceTraject const TrajectoryFactoryBase *ReferenceTrajectoryFactory::bzeroFactory() const { if (!theBzeroFactory) { - const edm::ParameterSet &myPset = this->configuration(); edm::LogInfo("Alignment") << "@SUB=ReferenceTrajectoryFactory::bzeroFactory" << "Using BzeroReferenceTrajectoryFactory for some (all?) events."; - // We take the config of this factory, copy it, replace its name and add - // the momentum parameter as expected by BzeroReferenceTrajectoryFactory and create it: - edm::ParameterSet pset; - pset.copyForModify(myPset); - // next two lines not needed, but may help to better understand log file: - pset.eraseSimpleParameter("TrajectoryFactoryName"); - pset.addParameter("TrajectoryFactoryName", std::string("BzeroReferenceTrajectoryFactory")); - pset.addParameter("MomentumEstimate", myPset.getParameter("MomentumEstimateFieldOff")); - theBzeroFactory = new BzeroReferenceTrajectoryFactory(pset); } return theBzeroFactory; } diff --git a/Alignment/ReferenceTrajectories/plugins/TwoBodyDecayTrajectoryFactory.cc b/Alignment/ReferenceTrajectories/plugins/TwoBodyDecayTrajectoryFactory.cc index d7404d2074498..24c8bfaed960e 100644 --- a/Alignment/ReferenceTrajectories/plugins/TwoBodyDecayTrajectoryFactory.cc +++ b/Alignment/ReferenceTrajectories/plugins/TwoBodyDecayTrajectoryFactory.cc @@ -31,8 +31,10 @@ class TwoBodyDecayTrajectoryFactory : public TrajectoryFactoryBase { typedef TwoBodyDecayTrajectoryState::TsosContainer TsosContainer; typedef TwoBodyDecayTrajectory::ConstRecHitCollection ConstRecHitCollection; - TwoBodyDecayTrajectoryFactory(const edm::ParameterSet &config); + TwoBodyDecayTrajectoryFactory(const edm::ParameterSet &config, edm::ConsumesCollector &iC); ~TwoBodyDecayTrajectoryFactory() override; + const edm::ESGetToken m_MagFieldToken; + const edm::ESGetToken m_globTackingToken; /// Produce the trajectories. const ReferenceTrajectoryCollection trajectories(const edm::EventSetup &setup, @@ -71,8 +73,12 @@ class TwoBodyDecayTrajectoryFactory : public TrajectoryFactoryBase { //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -TwoBodyDecayTrajectoryFactory::TwoBodyDecayTrajectoryFactory(const edm::ParameterSet &config) - : TrajectoryFactoryBase(config, 2), theFitter(config) { +TwoBodyDecayTrajectoryFactory::TwoBodyDecayTrajectoryFactory(const edm::ParameterSet &config, + edm::ConsumesCollector &iC) + : TrajectoryFactoryBase(config, 2, iC), + m_MagFieldToken(iC.esConsumes()), + m_globTackingToken(iC.esConsumes()), + theFitter(config) { const edm::ParameterSet ppc = config.getParameter("ParticleProperties"); thePrimaryMass = ppc.getParameter("PrimaryMass"); thePrimaryWidth = ppc.getParameter("PrimaryWidth"); @@ -90,20 +96,16 @@ const TrajectoryFactoryBase::ReferenceTrajectoryCollection TwoBodyDecayTrajector const edm::EventSetup &setup, const ConstTrajTrackPairCollection &tracks, const reco::BeamSpot &beamSpot) const { ReferenceTrajectoryCollection trajectories; - edm::ESHandle magneticField; - setup.get().get(magneticField); - - edm::ESHandle trackingGeometry; - setup.get().get(trackingGeometry); - + const MagneticField *magneticField = &setup.getData(m_MagFieldToken); + const GlobalTrackingGeometry *trackingGeometry = &setup.getData(m_globTackingToken); if (tracks.size() == 2) { // produce transient tracks from persistent tracks std::vector transientTracks(2); - transientTracks[0] = reco::TransientTrack(*tracks[0].second, magneticField.product()); + transientTracks[0] = reco::TransientTrack(*tracks[0].second, magneticField); transientTracks[0].setTrackingGeometry(trackingGeometry); - transientTracks[1] = reco::TransientTrack(*tracks[1].second, magneticField.product()); + transientTracks[1] = reco::TransientTrack(*tracks[1].second, magneticField); transientTracks[1].setTrackingGeometry(trackingGeometry); // estimate the decay parameters @@ -115,7 +117,7 @@ const TrajectoryFactoryBase::ReferenceTrajectoryCollection TwoBodyDecayTrajector return trajectories; } - return constructTrajectories(tracks, tbd, magneticField.product(), beamSpot, false); + return constructTrajectories(tracks, tbd, magneticField, beamSpot, false); } else { edm::LogInfo("ReferenceTrajectories") << "@SUB=TwoBodyDecayTrajectoryFactory::trajectories" << "Need 2 tracks, got " << tracks.size() << ".\n"; @@ -131,11 +133,9 @@ const TrajectoryFactoryBase::ReferenceTrajectoryCollection TwoBodyDecayTrajector const reco::BeamSpot &beamSpot) const { ReferenceTrajectoryCollection trajectories; - edm::ESHandle magneticField; - setup.get().get(magneticField); + const MagneticField *magneticField = &setup.getData(m_MagFieldToken); - edm::ESHandle trackingGeometry; - setup.get().get(trackingGeometry); + const GlobalTrackingGeometry *trackingGeometry = &setup.getData(m_globTackingToken); if (tracks.size() == 2 && external.size() == 2) { if (external[0].isValid() && external[1].isValid()) // Include external estimates @@ -143,10 +143,10 @@ const TrajectoryFactoryBase::ReferenceTrajectoryCollection TwoBodyDecayTrajector // produce transient tracks from persistent tracks std::vector transientTracks(2); - transientTracks[0] = reco::TransientTrack(*tracks[0].second, magneticField.product()); + transientTracks[0] = reco::TransientTrack(*tracks[0].second, magneticField); transientTracks[0].setTrackingGeometry(trackingGeometry); - transientTracks[1] = reco::TransientTrack(*tracks[1].second, magneticField.product()); + transientTracks[1] = reco::TransientTrack(*tracks[1].second, magneticField); transientTracks[1].setTrackingGeometry(trackingGeometry); // estimate the decay parameters. the transient tracks are not really associated to the @@ -160,7 +160,7 @@ const TrajectoryFactoryBase::ReferenceTrajectoryCollection TwoBodyDecayTrajector return trajectories; } - return constructTrajectories(tracks, tbd, magneticField.product(), beamSpot, true); + return constructTrajectories(tracks, tbd, magneticField, beamSpot, true); } else { // Return without external estimate trajectories = this->trajectories(setup, tracks, beamSpot); diff --git a/Alignment/ReferenceTrajectories/src/TrajectoryFactoryBase.cc b/Alignment/ReferenceTrajectories/src/TrajectoryFactoryBase.cc index d382a43b920d8..9376bb966b098 100644 --- a/Alignment/ReferenceTrajectories/src/TrajectoryFactoryBase.cc +++ b/Alignment/ReferenceTrajectories/src/TrajectoryFactoryBase.cc @@ -6,9 +6,12 @@ #include "Alignment/ReferenceTrajectories/interface/TrajectoryFactoryBase.h" -TrajectoryFactoryBase::TrajectoryFactoryBase(const edm::ParameterSet& config) : TrajectoryFactoryBase(config, 1) {} +TrajectoryFactoryBase::TrajectoryFactoryBase(const edm::ParameterSet& config, const edm::ConsumesCollector& iC) + : TrajectoryFactoryBase(config, 1, iC) {} -TrajectoryFactoryBase::TrajectoryFactoryBase(const edm::ParameterSet& config, unsigned int tracksPerTrajectory) +TrajectoryFactoryBase::TrajectoryFactoryBase(const edm::ParameterSet& config, + unsigned int tracksPerTrajectory, + const edm::ConsumesCollector& iC) : cfg_(config), tracksPerTrajectory_(tracksPerTrajectory), materialEffects_(materialEffects(config.getParameter("MaterialEffects"))), diff --git a/Alignment/SurveyAnalysis/plugins/DTSurveyConvert.cc b/Alignment/SurveyAnalysis/plugins/DTSurveyConvert.cc index f2fcf700bd87d..d8bd8511976d2 100644 --- a/Alignment/SurveyAnalysis/plugins/DTSurveyConvert.cc +++ b/Alignment/SurveyAnalysis/plugins/DTSurveyConvert.cc @@ -6,7 +6,11 @@ #include "FWCore/Framework/interface/MakerMacros.h" #include "Alignment/SurveyAnalysis/plugins/DTSurveyConvert.h" -DTSurveyConvert::DTSurveyConvert(const edm::ParameterSet &iConfig) : muonGeoToken_(esConsumes()) { +DTSurveyConvert::DTSurveyConvert(const edm::ParameterSet &iConfig) + : muonGeoToken_(esConsumes()), + dtGeomToken_(esConsumes()), + cscGeomToken_(esConsumes()), + gemGeomToken_(esConsumes()) { //now do what ever initialization is needed nameWheel_m2 = iConfig.getUntrackedParameter("nameWheel_m2"); nameWheel_m1 = iConfig.getUntrackedParameter("nameWheel_m1"); @@ -75,7 +79,11 @@ void DTSurveyConvert::analyze(const edm::Event &, const edm::EventSetup &iSetup) if (WriteToDB == true) { // Instantiate the helper class - MuonAlignment align(iSetup); + const DTGeometry *dtGeometry = &iSetup.getData(dtGeomToken_); + const CSCGeometry *cscGeometry = &iSetup.getData(cscGeomToken_); + const GEMGeometry *gemGeometry = &iSetup.getData(gemGeomToken_); + + MuonAlignment align(&*dtGeometry, &*cscGeometry, &*gemGeometry); std::ifstream inFile(outputFileName.c_str()); while (!inFile.eof()) { float dx, dy, dz, sigma_dx, sigma_dy, sigma_dz; diff --git a/Alignment/SurveyAnalysis/plugins/DTSurveyConvert.h b/Alignment/SurveyAnalysis/plugins/DTSurveyConvert.h index 0ef4dbf25907a..02f2d3c010cee 100644 --- a/Alignment/SurveyAnalysis/plugins/DTSurveyConvert.h +++ b/Alignment/SurveyAnalysis/plugins/DTSurveyConvert.h @@ -52,6 +52,10 @@ class DTSurveyConvert : public edm::one::EDAnalyzer<> { bool wheel_p1; bool wheel_p2; bool WriteToDB; + + const edm::ESGetToken dtGeomToken_; + const edm::ESGetToken cscGeomToken_; + const edm::ESGetToken gemGeomToken_; }; #endif diff --git a/Alignment/TrackerAlignment/src/TrackerAlignment.cc b/Alignment/TrackerAlignment/src/TrackerAlignment.cc index 59a93005933cf..276a068371054 100644 --- a/Alignment/TrackerAlignment/src/TrackerAlignment.cc +++ b/Alignment/TrackerAlignment/src/TrackerAlignment.cc @@ -247,7 +247,8 @@ void TrackerAlignment::saveToDB(void) { // else // poolDbService->appendSinceTime( alignments, poolDbService->currentTime(), // theAlignRecordName ); - poolDbService->writeOne(alignments, poolDbService->currentTime(), theAlignRecordName); + // In the two calls below it is assumed that the delete of "theAlignableTracker" is also deleting the two concerned payloads... + poolDbService->writeOneIOV(*alignments, poolDbService->currentTime(), theAlignRecordName); // if ( poolDbService->isNewTagRequest(theErrorRecordName) ) // poolDbService->createNewIOV( alignmentErrors, // poolDbService->endOfTime(), @@ -256,5 +257,6 @@ void TrackerAlignment::saveToDB(void) { // poolDbService->appendSinceTime( alignmentErrors, // poolDbService->currentTime(), // theErrorRecordName ); - poolDbService->writeOne(alignmentErrors, poolDbService->currentTime(), theErrorRecordName); + poolDbService->writeOneIOV( + *alignmentErrors, poolDbService->currentTime(), theErrorRecordName); } diff --git a/Alignment/TrackerAlignment/test/ApeAdder.cpp b/Alignment/TrackerAlignment/test/ApeAdder.cpp index 2aab98decc539..5ace33fbb6bfb 100644 --- a/Alignment/TrackerAlignment/test/ApeAdder.cpp +++ b/Alignment/TrackerAlignment/test/ApeAdder.cpp @@ -91,8 +91,9 @@ void ApeAdder::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) if (!poolDbService.isAvailable()) // Die if not available throw cms::Exception("NotAvailable") << "PoolDBOutputService not available"; - // Save to DB - poolDbService->writeOne(alignmentErrors, poolDbService->beginOfTime(), theErrorRecordName); + // Save to DB (assuming that the delete below will also delete the concerned payload ) + poolDbService->writeOneIOV( + *alignmentErrors, poolDbService->beginOfTime(), theErrorRecordName); delete theAlignableTracker; } diff --git a/CalibCalorimetry/CaloMiscalibTools/test/make_ecal_miscaplibration.py b/CalibCalorimetry/CaloMiscalibTools/test/make_ecal_miscaplibration.py index 928ad34c9fe3b..2f29224a8cd06 100755 --- a/CalibCalorimetry/CaloMiscalibTools/test/make_ecal_miscaplibration.py +++ b/CalibCalorimetry/CaloMiscalibTools/test/make_ecal_miscaplibration.py @@ -1,6 +1,6 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 from __future__ import print_function -import commands,string,time,thread,random,math,sys +import string,time,thread,random,math,sys #global variables MINRES=0.02 diff --git a/CalibCalorimetry/CaloMiscalibTools/test/make_miscalibration.py b/CalibCalorimetry/CaloMiscalibTools/test/make_miscalibration.py index 7dd3f5622cfd5..08001752fdbc5 100755 --- a/CalibCalorimetry/CaloMiscalibTools/test/make_miscalibration.py +++ b/CalibCalorimetry/CaloMiscalibTools/test/make_miscalibration.py @@ -1,6 +1,6 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 from __future__ import print_function -import commands,string,time,thread,random,math,sys +import string,time,thread,random,math,sys #global variables MINRES=0.04 diff --git a/CalibCalorimetry/EcalTrivialCondModules/src/EcalLaserCondTools.cc b/CalibCalorimetry/EcalTrivialCondModules/src/EcalLaserCondTools.cc index 7a6c64d1f22de..72a11610128bb 100644 --- a/CalibCalorimetry/EcalTrivialCondModules/src/EcalLaserCondTools.cc +++ b/CalibCalorimetry/EcalTrivialCondModules/src/EcalLaserCondTools.cc @@ -244,7 +244,7 @@ void EcalLaserCondTools::from_hdf_to_db() { if (verb_ > 1) std::cout << "[" << timeToString(t.tv_sec) << "] " << "Write IOV " << iIov << " starting from " << timeToString(iovStart >> 32) << "... "; - db_->writeOne(corrSet.get(), iovStart, "EcalLaserAPDPNRatiosRcd"); + db_->writeOneIOV(*corrSet, iovStart, "EcalLaserAPDPNRatiosRcd"); } catch (const cms::Exception& e) { if (verb_ > 1) std::cout << "Failed. "; @@ -437,7 +437,7 @@ void EcalLaserCondTools::processIov(CorrReader& r, int t1, int t2[EcalLaserCondT if (verb_ > 1) std::cout << "[" << timeToString(t.tv_sec) << "] " << "Write IOV " << iIov << " starting from " << timeToString(iovStart >> 32) << "... "; - db_->writeOne(corrSet.get(), iovStart, "EcalLaserAPDPNRatiosRcd"); + db_->writeOneIOV(*corrSet, iovStart, "EcalLaserAPDPNRatiosRcd"); } catch (const cms::Exception& e) { std::cout << "Failed.\nException cathed while writting to cond DB" << e.what() << "\n"; } diff --git a/CalibCalorimetry/HcalAlgos/interface/HcalLedAnalysis.h b/CalibCalorimetry/HcalAlgos/interface/HcalLedAnalysis.h index cf48a1dd9adb2..fe0f900cb1ee0 100644 --- a/CalibCalorimetry/HcalAlgos/interface/HcalLedAnalysis.h +++ b/CalibCalorimetry/HcalAlgos/interface/HcalLedAnalysis.h @@ -2,11 +2,7 @@ #define HcalLedAnalysis_H #include "FWCore/Framework/interface/Frameworkfwd.h" -#include "FWCore/Framework/interface/EDAnalyzer.h" -#include "FWCore/Framework/interface/Event.h" -#include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" -#include "FWCore/ServiceRegistry/interface/Service.h" #include "DataFormats/HcalDigi/interface/HcalDigiCollections.h" diff --git a/CalibCalorimetry/HcalAlgos/interface/HcalPedestalAnalysis.h b/CalibCalorimetry/HcalAlgos/interface/HcalPedestalAnalysis.h index 12fb1b29495c3..6556b2ef0454a 100644 --- a/CalibCalorimetry/HcalAlgos/interface/HcalPedestalAnalysis.h +++ b/CalibCalorimetry/HcalAlgos/interface/HcalPedestalAnalysis.h @@ -2,11 +2,7 @@ #define HcalPedestalAnalysis_H #include "FWCore/Framework/interface/Frameworkfwd.h" -#include "FWCore/Framework/interface/EDAnalyzer.h" -#include "FWCore/Framework/interface/Event.h" -#include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" -#include "FWCore/ServiceRegistry/interface/Service.h" #include "DataFormats/HcalDetId/interface/HcalDetId.h" #include "DataFormats/HcalDigi/interface/HcalDigiCollections.h" diff --git a/CalibCalorimetry/HcalAlgos/test/MapTester.cc b/CalibCalorimetry/HcalAlgos/test/MapTester.cc index 3ae98d8ead613..16da3a4ee1051 100644 --- a/CalibCalorimetry/HcalAlgos/test/MapTester.cc +++ b/CalibCalorimetry/HcalAlgos/test/MapTester.cc @@ -25,7 +25,7 @@ // user include files #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" @@ -40,17 +40,17 @@ // class decleration // -class MapTester : public edm::EDAnalyzer { +class MapTester : public edm::one::EDAnalyzer<> { public: explicit MapTester(const edm::ParameterSet&); - ~MapTester(); + ~MapTester() override = default; private: unsigned int mapIOV_; //1 for first set, 2 for second, ... bool generateTextfiles_; bool generateEmap_; - virtual void analyze(const edm::Event&, const edm::EventSetup&); + void analyze(const edm::Event&, const edm::EventSetup&) override; // ----------member data --------------------------- const edm::ESGetToken tok_topo_; @@ -62,8 +62,6 @@ MapTester::MapTester(const edm::ParameterSet& iConfig) : tok_topo_(esConsumes("generateEmap"); } -MapTester::~MapTester() {} - // ------------ method called to for each event ------------ void MapTester::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) { char tempbuff[128]; diff --git a/CalibCalorimetry/HcalPlugins/python/Hcal_PCCUpdate_cff.py b/CalibCalorimetry/HcalPlugins/python/Hcal_PCCUpdate_cff.py new file mode 100644 index 0000000000000..a00b28b317c14 --- /dev/null +++ b/CalibCalorimetry/HcalPlugins/python/Hcal_PCCUpdate_cff.py @@ -0,0 +1,9 @@ +import FWCore.ParameterSet.Config as cms + +# Turn on the PCC update which synchronize timePhase in PCC as in SIM +PCCUpdate = cms.PSet( + applyFixPCC = cms.bool(False) +) + +from Configuration.Eras.Modifier_run3_common_cff import run3_common +run3_common.toModify(PCCUpdate, applyFixPCC = True) diff --git a/CalibCalorimetry/HcalPlugins/test/HcalDbAnalyzer.cc b/CalibCalorimetry/HcalPlugins/test/HcalDbAnalyzer.cc index 8e3b964fe190f..6ae8ea44e09f6 100644 --- a/CalibCalorimetry/HcalPlugins/test/HcalDbAnalyzer.cc +++ b/CalibCalorimetry/HcalPlugins/test/HcalDbAnalyzer.cc @@ -22,7 +22,7 @@ // user include files #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" @@ -77,12 +77,12 @@ namespace { } } // namespace -class HcalDbAnalyzer : public edm::EDAnalyzer { +class HcalDbAnalyzer : public edm::one::EDAnalyzer<> { public: explicit HcalDbAnalyzer(const edm::ParameterSet&); - ~HcalDbAnalyzer(); + ~HcalDbAnalyzer() override = default; - virtual void analyze(const edm::Event&, const edm::EventSetup&); + void analyze(const edm::Event&, const edm::EventSetup&) override; private: // ----------member data --------------------------- @@ -107,11 +107,6 @@ HcalDbAnalyzer::HcalDbAnalyzer(const edm::ParameterSet& iConfig) { //now do what ever initialization is needed } -HcalDbAnalyzer::~HcalDbAnalyzer() { - // do anything here that needs to be done at desctruction time - // (e.g. close files, deallocate resources etc.) -} - // // member functions // diff --git a/CalibCalorimetry/HcalTPGEventSetup/src/HcalTPGCoderULUT.cc b/CalibCalorimetry/HcalTPGEventSetup/src/HcalTPGCoderULUT.cc index d81cff7163dcf..70929abd31615 100644 --- a/CalibCalorimetry/HcalTPGEventSetup/src/HcalTPGCoderULUT.cc +++ b/CalibCalorimetry/HcalTPGEventSetup/src/HcalTPGCoderULUT.cc @@ -87,9 +87,9 @@ HcalTPGCoderULUT::HcalTPGCoderULUT(const edm::ParameterSet& iConfig) { contain1TSHE_ = iConfig.getParameter("contain1TSHE"); containPhaseNSHB_ = iConfig.getParameter("containPhaseNSHB"); containPhaseNSHE_ = iConfig.getParameter("containPhaseNSHE"); - applyFixPCC_ = iConfig.getParameter("applyFixPCC"); overrideDBweightsAndFilterHB_ = iConfig.getParameter("overrideDBweightsAndFilterHB"); overrideDBweightsAndFilterHE_ = iConfig.getParameter("overrideDBweightsAndFilterHE"); + applyFixPCC_ = iConfig.getParameter("applyFixPCC"); //the following line is needed to tell the framework what // data is being produced diff --git a/CalibCalorimetry/HcalTPGIO/src/HcalLuttoDB.cc b/CalibCalorimetry/HcalTPGIO/src/HcalLuttoDB.cc index de172b9785bad..16598765a8ac8 100644 --- a/CalibCalorimetry/HcalTPGIO/src/HcalLuttoDB.cc +++ b/CalibCalorimetry/HcalTPGIO/src/HcalLuttoDB.cc @@ -20,7 +20,7 @@ #include // user include files -#include "FWCore/Framework/interface/EDAnalyzer.h" +#include "FWCore/Framework/interface/one/EDAnalyzer.h" #include "FWCore/Framework/interface/EventSetup.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" @@ -51,7 +51,7 @@ using namespace std; // class decleration // -class HcalLuttoDB : public edm::EDAnalyzer { +class HcalLuttoDB : public edm::one::EDAnalyzer<> { public: explicit HcalLuttoDB(const edm::ParameterSet&); ~HcalLuttoDB() override; @@ -67,9 +67,11 @@ class HcalLuttoDB : public edm::EDAnalyzer { HcalElectronicsId eid, const std::vector& lut, std::ostream& os); - bool filePerCrate_; + const std::string creationtag_; + const std::string targetfirmware_; + const bool filePerCrate_; + const std::string fileformat_; std::string creationstamp_; - std::string fileformat_; std::ostream* openPerCrate(int crate); std::ostream* openPerLut1(HcalElectronicsId eid); std::ostream* openPerLut2(HcalElectronicsId eid); @@ -81,17 +83,15 @@ class HcalLuttoDB : public edm::EDAnalyzer { }; // ----------member data --------------------------- -std::string creationtag_; -std::string targetfirmware_; static const int formatRevision_ = 1; // constructors and destructor // -HcalLuttoDB::HcalLuttoDB(const edm::ParameterSet& iConfig) { - creationtag_ = iConfig.getParameter("creationtag"); - targetfirmware_ = iConfig.getParameter("targetfirmware"); - filePerCrate_ = iConfig.getUntrackedParameter("filePerCrate", true); - fileformat_ = iConfig.getParameter("filePrefix"); +HcalLuttoDB::HcalLuttoDB(const edm::ParameterSet& iConfig) + : creationtag_(iConfig.getParameter("creationtag")), + targetfirmware_(iConfig.getParameter("targetfirmware")), + filePerCrate_(iConfig.getUntrackedParameter("filePerCrate", true)), + fileformat_(iConfig.getParameter("filePrefix")) { tokdb_ = esConsumes(); tokhcalCode_ = esConsumes(); tokcaloCode_ = esConsumes(); diff --git a/CalibFormats/SiStripObjects/test/plugins/module.cc b/CalibFormats/SiStripObjects/test/plugins/module.cc deleted file mode 100644 index 5df9a54b05a9e..0000000000000 --- a/CalibFormats/SiStripObjects/test/plugins/module.cc +++ /dev/null @@ -1,4 +0,0 @@ -#include "FWCore/Framework/interface/MakerMacros.h" - -#include "CalibFormats/SiStripObjects/test/plugins/testSiStripHashedDetId.h" -DEFINE_FWK_MODULE(testSiStripHashedDetId); diff --git a/CalibFormats/SiStripObjects/test/plugins/testSiStripHashedDetId.cc b/CalibFormats/SiStripObjects/test/plugins/testSiStripHashedDetId.cc index a30e171e601c2..8ac39e91b12eb 100644 --- a/CalibFormats/SiStripObjects/test/plugins/testSiStripHashedDetId.cc +++ b/CalibFormats/SiStripObjects/test/plugins/testSiStripHashedDetId.cc @@ -1,9 +1,18 @@ +// system includes +#include +#include +#include +#include +#include +#include +// user includes #include "CalibFormats/SiStripObjects/interface/SiStripHashedDetId.h" -#include "CalibFormats/SiStripObjects/test/plugins/testSiStripHashedDetId.h" #include "DataFormats/SiStripCommon/interface/SiStripConstants.h" +#include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/Framework/interface/ESHandle.h" #include "FWCore/Framework/interface/Event.h" +#include "FWCore/Framework/interface/one/EDAnalyzer.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "Geometry/CommonDetUnit/interface/GeomDet.h" #include "Geometry/CommonDetUnit/interface/GeomDetType.h" @@ -12,18 +21,30 @@ #include "Geometry/TrackerGeometryBuilder/interface/StripGeomDetType.h" #include "Geometry/TrackerGeometryBuilder/interface/StripGeomDetUnit.h" #include "Geometry/TrackerGeometryBuilder/interface/TrackerGeometry.h" -#include -#include -#include -#include -#include -#include + +/** + @class test_SiStripHashedDetId + @author R.Bainbridge + @brief Simple class that tests SiStripHashedDetId. +*/ +class testSiStripHashedDetId : public edm::one::EDAnalyzer<> { +public: + testSiStripHashedDetId(const edm::ParameterSet &); + ~testSiStripHashedDetId(); + + void initialize(edm::EventSetup const &); + void analyze(const edm::Event &, const edm::EventSetup &); + +private: + //-------------- member data ----------------// + const edm::ESGetToken geomToken_; +}; using namespace sistrip; // ----------------------------------------------------------------------------- // -testSiStripHashedDetId::testSiStripHashedDetId(const edm::ParameterSet &pset) { +testSiStripHashedDetId::testSiStripHashedDetId(const edm::ParameterSet &pset) : geomToken_(esConsumes()) { edm::LogVerbatim(mlDqmCommon_) << "[testSiStripHashedDetId::" << __func__ << "]" << " Constructing object..."; } @@ -42,8 +63,7 @@ void testSiStripHashedDetId::initialize(const edm::EventSetup &setup) { << " Tests the generation of DetId hash map..."; // Retrieve geometry - edm::ESHandle geom; - setup.get().get(geom); + edm::ESHandle geom = setup.getHandle(geomToken_); // Build list of DetIds std::vector dets; @@ -182,3 +202,5 @@ void testSiStripHashedDetId::analyze(const edm::Event &event, const edm::EventSe LogTrace(mlDqmCommon_) << "[testSiStripHashedDetId::" << __func__ << "]" << " Analyzing run/event " << event.id().run() << "/" << event.id().event(); } + +DEFINE_FWK_MODULE(testSiStripHashedDetId); diff --git a/CalibFormats/SiStripObjects/test/plugins/testSiStripHashedDetId.h b/CalibFormats/SiStripObjects/test/plugins/testSiStripHashedDetId.h deleted file mode 100644 index aa7d028dd0ed4..0000000000000 --- a/CalibFormats/SiStripObjects/test/plugins/testSiStripHashedDetId.h +++ /dev/null @@ -1,23 +0,0 @@ -// Last commit: $Id $ - -#ifndef CalibFormats_SiStripObjects_test_SiStripHashedDetId_H -#define CalibFormats_SiStripObjects_test_SiStripHashedDetId_H - -#include "FWCore/Framework/interface/EDAnalyzer.h" - -/** - @class test_SiStripHashedDetId - @author R.Bainbridge - @brief Simple class that tests SiStripHashedDetId. -*/ -class testSiStripHashedDetId : public edm::EDAnalyzer { -public: - testSiStripHashedDetId(const edm::ParameterSet &); - ~testSiStripHashedDetId(); - - void initialize(edm::EventSetup const &); - void analyze(const edm::Event &, const edm::EventSetup &); - void endJob() { ; } -}; - -#endif // CalibFormats_SiStripObjects_test_SiStripHashedDetId_H diff --git a/CalibMuon/DTCalibration/interface/DTSegmentSelector.h b/CalibMuon/DTCalibration/interface/DTSegmentSelector.h index e9e9a5e93da9a..2dfba3be754d4 100644 --- a/CalibMuon/DTCalibration/interface/DTSegmentSelector.h +++ b/CalibMuon/DTCalibration/interface/DTSegmentSelector.h @@ -14,6 +14,8 @@ #include "FWCore/Utilities/interface/InputTag.h" #include "DataFormats/MuonReco/interface/Muon.h" #include "DataFormats/MuonReco/interface/MuonFwd.h" +#include "CondFormats/DataRecord/interface/DTStatusFlagRcd.h" +#include "CondFormats/DTObjects/interface/DTStatusFlag.h" #include @@ -38,6 +40,7 @@ class DTSegmentSelector { double maxChi2_; double maxAnglePhi_; double maxAngleZ_; + edm::ESGetToken theStatusMapToken_; }; #endif diff --git a/CalibMuon/DTCalibration/interface/DTT0CorrectionFactory.h b/CalibMuon/DTCalibration/interface/DTT0CorrectionFactory.h index 7045c644910c9..b78b4af508fc3 100644 --- a/CalibMuon/DTCalibration/interface/DTT0CorrectionFactory.h +++ b/CalibMuon/DTCalibration/interface/DTT0CorrectionFactory.h @@ -7,13 +7,16 @@ * */ #include "FWCore/PluginManager/interface/PluginFactory.h" +#include "FWCore/Framework/interface/ConsumesCollector.h" namespace edm { class ParameterSet; -} + class ConsumesCollector; +} // namespace edm namespace dtCalibration { class DTT0BaseCorrection; } -typedef edmplugin::PluginFactory DTT0CorrectionFactory; +typedef edmplugin::PluginFactory + DTT0CorrectionFactory; #endif diff --git a/CalibMuon/DTCalibration/interface/DTTTrigCorrectionFactory.h b/CalibMuon/DTCalibration/interface/DTTTrigCorrectionFactory.h index 3afe21e8a5c0f..f6d3af57a74d9 100644 --- a/CalibMuon/DTCalibration/interface/DTTTrigCorrectionFactory.h +++ b/CalibMuon/DTCalibration/interface/DTTTrigCorrectionFactory.h @@ -8,14 +8,17 @@ * \author A. Vilela Pereira */ #include "FWCore/PluginManager/interface/PluginFactory.h" +#include "FWCore/Framework/interface/ConsumesCollector.h" namespace edm { class ParameterSet; -} + class ConsumesCollector; +} // namespace edm namespace dtCalibration { class DTTTrigBaseCorrection; } -typedef edmplugin::PluginFactory +typedef edmplugin::PluginFactory DTTTrigCorrectionFactory; #endif diff --git a/CalibMuon/DTCalibration/interface/DTVDriftPluginFactory.h b/CalibMuon/DTCalibration/interface/DTVDriftPluginFactory.h index 29a238a9f2910..dd5f7155b3f6c 100644 --- a/CalibMuon/DTCalibration/interface/DTVDriftPluginFactory.h +++ b/CalibMuon/DTCalibration/interface/DTVDriftPluginFactory.h @@ -9,13 +9,16 @@ */ #include "FWCore/PluginManager/interface/PluginFactory.h" +#include "FWCore/Framework/interface/ConsumesCollector.h" namespace edm { class ParameterSet; -} + class ConsumesCollector; +} // namespace edm namespace dtCalibration { class DTVDriftBaseAlgo; } -typedef edmplugin::PluginFactory DTVDriftPluginFactory; +typedef edmplugin::PluginFactory + DTVDriftPluginFactory; #endif diff --git a/CalibMuon/DTCalibration/plugins/DTNoiseCalibration.cc b/CalibMuon/DTCalibration/plugins/DTNoiseCalibration.cc index 7291adf7f2543..d725e6a2526da 100644 --- a/CalibMuon/DTCalibration/plugins/DTNoiseCalibration.cc +++ b/CalibMuon/DTCalibration/plugins/DTNoiseCalibration.cc @@ -48,12 +48,12 @@ DTNoiseCalibration::DTNoiseCalibration(const edm::ParameterSet& pset) useAbsoluteRate_(pset.getParameter("useAbsoluteRate")), readDB_(true), defaultTtrig_(0), - dbLabel_(pset.getUntrackedParameter("dbLabel", "")), //fastAnalysis_( pset.getParameter("fastAnalysis", true) ), wireIdWithHisto_(std::vector()), lumiMax_(3000), - dtGeomToken_(esConsumes()), - ttrigToken_(esConsumes(edm::ESInputTag("", pset.getParameter("dbLabel")))) { + dtGeomToken_(esConsumes()), + ttrigToken_( + esConsumes(edm::ESInputTag("", pset.getUntrackedParameter("dbLabel")))) { // Get the debug parameter for verbose output //debug = ps.getUntrackedParameter("debug"); /*// The analysis type diff --git a/CalibMuon/DTCalibration/plugins/DTNoiseCalibration.h b/CalibMuon/DTCalibration/plugins/DTNoiseCalibration.h index 5c5f236f15d49..5cb49f566ddd1 100644 --- a/CalibMuon/DTCalibration/plugins/DTNoiseCalibration.h +++ b/CalibMuon/DTCalibration/plugins/DTNoiseCalibration.h @@ -64,7 +64,6 @@ class DTNoiseCalibration : public edm::EDAnalyzer { bool readDB_; int defaultTtrig_; - std::string dbLabel_; std::vector wireIdWithHisto_; unsigned int lumiMax_; diff --git a/CalibMuon/DTCalibration/plugins/DTResidualCalibration.cc b/CalibMuon/DTCalibration/plugins/DTResidualCalibration.cc index 1635d11f4c2d0..768f461701a85 100644 --- a/CalibMuon/DTCalibration/plugins/DTResidualCalibration.cc +++ b/CalibMuon/DTCalibration/plugins/DTResidualCalibration.cc @@ -36,7 +36,7 @@ DTResidualCalibration::DTResidualCalibration(const edm::ParameterSet& pset) segment4DLabel_(pset.getParameter("segment4DLabel")), rootBaseDir_(pset.getUntrackedParameter("rootBaseDir", "DT/Residuals")), detailedAnalysis_(pset.getUntrackedParameter("detailedAnalysis", false)), - dtGeomToken_(esConsumes()) { + dtGeomToken_(esConsumes()) { edm::ConsumesCollector collector(consumesCollector()); select_ = new DTSegmentSelector(pset, collector); diff --git a/CalibMuon/DTCalibration/plugins/DTT0AbsoluteReferenceCorrection.cc b/CalibMuon/DTCalibration/plugins/DTT0AbsoluteReferenceCorrection.cc index bff27dd1aa3ab..252b7f9fb964a 100644 --- a/CalibMuon/DTCalibration/plugins/DTT0AbsoluteReferenceCorrection.cc +++ b/CalibMuon/DTCalibration/plugins/DTT0AbsoluteReferenceCorrection.cc @@ -24,8 +24,10 @@ using namespace edm; namespace dtCalibration { - DTT0AbsoluteReferenceCorrection::DTT0AbsoluteReferenceCorrection(const ParameterSet& pset) - : calibChamber_(pset.getParameter("calibChamber")), reference_(pset.getParameter("reference")) { + DTT0AbsoluteReferenceCorrection::DTT0AbsoluteReferenceCorrection(const ParameterSet& pset, edm::ConsumesCollector cc) + : calibChamber_(pset.getParameter("calibChamber")), + reference_(pset.getParameter("reference")), + t0Token_(cc.esConsumes()) { //DTChamberId chosenChamberId; if (!calibChamber_.empty() && calibChamber_ != "None" && calibChamber_ != "All") { stringstream linestr; @@ -43,7 +45,7 @@ namespace dtCalibration { void DTT0AbsoluteReferenceCorrection::setES(const EventSetup& setup) { // Get t0 record from DB ESHandle t0H; - setup.get().get(t0H); + t0H = setup.getHandle(t0Token_); t0Map_ = &*t0H; LogVerbatim("Calibration") << "[DTT0AbsoluteReferenceCorrection] T0 version: " << t0H->version(); } diff --git a/CalibMuon/DTCalibration/plugins/DTT0AbsoluteReferenceCorrection.h b/CalibMuon/DTCalibration/plugins/DTT0AbsoluteReferenceCorrection.h index 88ebad24bba25..481e1fde64bb8 100644 --- a/CalibMuon/DTCalibration/plugins/DTT0AbsoluteReferenceCorrection.h +++ b/CalibMuon/DTCalibration/plugins/DTT0AbsoluteReferenceCorrection.h @@ -11,7 +11,10 @@ #include "CalibMuon/DTCalibration/interface/DTT0BaseCorrection.h" #include "DataFormats/MuonDetId/interface/DTChamberId.h" - +#include "FWCore/Framework/interface/ConsumesCollector.h" +#include "FWCore/Utilities/interface/ESGetToken.h" +#include "CondFormats/DataRecord/interface/DTT0Rcd.h" +#include "CondFormats/DTObjects/interface/DTT0.h" #include namespace edm { @@ -25,7 +28,7 @@ namespace dtCalibration { class DTT0AbsoluteReferenceCorrection : public DTT0BaseCorrection { public: // Constructor - DTT0AbsoluteReferenceCorrection(const edm::ParameterSet&); + DTT0AbsoluteReferenceCorrection(const edm::ParameterSet&, edm::ConsumesCollector); // Destructor ~DTT0AbsoluteReferenceCorrection() override; @@ -41,6 +44,7 @@ namespace dtCalibration { DTChamberId chosenChamberId_; const DTT0* t0Map_; + edm::ESGetToken t0Token_; }; } // namespace dtCalibration diff --git a/CalibMuon/DTCalibration/plugins/DTT0ChamberReferenceCorrection.cc b/CalibMuon/DTCalibration/plugins/DTT0ChamberReferenceCorrection.cc index bc9eae7e83648..bc164699a37dd 100644 --- a/CalibMuon/DTCalibration/plugins/DTT0ChamberReferenceCorrection.cc +++ b/CalibMuon/DTCalibration/plugins/DTT0ChamberReferenceCorrection.cc @@ -23,7 +23,7 @@ using namespace edm; namespace dtCalibration { DTT0ChamberReferenceCorrection::DTT0ChamberReferenceCorrection(const ParameterSet& pset, edm::ConsumesCollector cc) - : calibChamber_(pset.getParameter("calibChamber")), t0Token_(cc.esConsumes()) { + : calibChamber_(pset.getParameter("calibChamber")), t0Token_(cc.esConsumes()) { //DTChamberId chosenChamberId; if (!calibChamber_.empty() && calibChamber_ != "None" && calibChamber_ != "All") { stringstream linestr; diff --git a/CalibMuon/DTCalibration/plugins/DTT0Correction.cc b/CalibMuon/DTCalibration/plugins/DTT0Correction.cc index 7a55a301679ba..48d48d46bde1a 100644 --- a/CalibMuon/DTCalibration/plugins/DTT0Correction.cc +++ b/CalibMuon/DTCalibration/plugins/DTT0Correction.cc @@ -20,6 +20,7 @@ #include "CalibMuon/DTCalibration/interface/DTT0CorrectionFactory.h" #include "CalibMuon/DTCalibration/interface/DTT0BaseCorrection.h" +#include "FWCore/Framework/interface/ConsumesCollector.h" #include #include @@ -29,9 +30,10 @@ using namespace std; DTT0Correction::DTT0Correction(const ParameterSet& pset) : correctionAlgo_{DTT0CorrectionFactory::get()->create(pset.getParameter("correctionAlgo"), - pset.getParameter("correctionAlgoConfig"))}, - dtGeomToken_(esConsumes()), - t0Token_(esConsumes()) { + pset.getParameter("correctionAlgoConfig"), + consumesCollector())}, + dtGeomToken_(esConsumes()), + t0Token_(esConsumes()) { LogVerbatim("Calibration") << "[DTT0Correction] Constructor called" << endl; } diff --git a/CalibMuon/DTCalibration/plugins/DTT0FEBPathCorrection.cc b/CalibMuon/DTCalibration/plugins/DTT0FEBPathCorrection.cc index 89b6f9407f513..a6c21c66c7f68 100644 --- a/CalibMuon/DTCalibration/plugins/DTT0FEBPathCorrection.cc +++ b/CalibMuon/DTCalibration/plugins/DTT0FEBPathCorrection.cc @@ -26,7 +26,7 @@ using namespace edm; namespace dtCalibration { DTT0FEBPathCorrection::DTT0FEBPathCorrection(const ParameterSet& pset, edm::ConsumesCollector cc) - : calibChamber_(pset.getParameter("calibChamber")), t0Token_(cc.esConsumes()) { + : calibChamber_(pset.getParameter("calibChamber")), t0Token_(cc.esConsumes()) { //DTChamberId chosenChamberId; if (!calibChamber_.empty() && calibChamber_ != "None" && calibChamber_ != "All") { stringstream linestr; diff --git a/CalibMuon/DTCalibration/plugins/DTT0FillChamberFromDB.cc b/CalibMuon/DTCalibration/plugins/DTT0FillChamberFromDB.cc index ed23b73c9c4ac..002b079303168 100644 --- a/CalibMuon/DTCalibration/plugins/DTT0FillChamberFromDB.cc +++ b/CalibMuon/DTCalibration/plugins/DTT0FillChamberFromDB.cc @@ -24,8 +24,11 @@ using namespace edm; namespace dtCalibration { - DTT0FillChamberFromDB::DTT0FillChamberFromDB(const ParameterSet& pset) - : dbLabelRef_(pset.getParameter("dbLabelRef")), chamberRef_(pset.getParameter("chamberId")) { + DTT0FillChamberFromDB::DTT0FillChamberFromDB(const ParameterSet& pset, edm::ConsumesCollector cc) + : chamberRef_(pset.getParameter("chamberId")), + t0Token_(cc.esConsumes()), + t0RefToken_( + cc.esConsumes(edm::ESInputTag("", pset.getParameter("dbLabelRef")))) { //DTChamberId chosenChamberId; if (!chamberRef_.empty() && chamberRef_ != "None") { stringstream linestr; @@ -42,14 +45,12 @@ namespace dtCalibration { void DTT0FillChamberFromDB::setES(const EventSetup& setup) { // Get t0 record from DB - ESHandle t0H; - setup.get().get(t0H); + ESHandle t0H = setup.getHandle(t0Token_); t0Map_ = &*t0H; LogVerbatim("Calibration") << "[DTT0FillChamberFromDB] T0 version: " << t0H->version(); // Get reference t0 DB - ESHandle t0RefH; - setup.get().get(dbLabelRef_, t0RefH); + ESHandle t0RefH = setup.getHandle(t0RefToken_); t0MapRef_ = &*t0RefH; LogVerbatim("Calibration") << "[DTT0FillChamberFromDB] Reference T0 version: " << t0RefH->version(); } diff --git a/CalibMuon/DTCalibration/plugins/DTT0FillChamberFromDB.h b/CalibMuon/DTCalibration/plugins/DTT0FillChamberFromDB.h index e213816cb991a..dd08787246630 100644 --- a/CalibMuon/DTCalibration/plugins/DTT0FillChamberFromDB.h +++ b/CalibMuon/DTCalibration/plugins/DTT0FillChamberFromDB.h @@ -11,6 +11,9 @@ #include "CalibMuon/DTCalibration/interface/DTT0BaseCorrection.h" #include "DataFormats/MuonDetId/interface/DTChamberId.h" +#include "CondFormats/DataRecord/interface/DTT0Rcd.h" +#include "CondFormats/DTObjects/interface/DTT0.h" +#include "FWCore/Framework/interface/ConsumesCollector.h" #include @@ -25,7 +28,7 @@ namespace dtCalibration { class DTT0FillChamberFromDB : public DTT0BaseCorrection { public: // Constructor - DTT0FillChamberFromDB(const edm::ParameterSet &); + DTT0FillChamberFromDB(const edm::ParameterSet &, edm::ConsumesCollector cc); // Destructor ~DTT0FillChamberFromDB() override; @@ -34,13 +37,14 @@ namespace dtCalibration { DTT0Data correction(const DTWireId &) override; private: - std::string dbLabelRef_; std::string chamberRef_; DTChamberId chosenChamberId_; const DTT0 *t0MapRef_; const DTT0 *t0Map_; + edm::ESGetToken t0Token_; + edm::ESGetToken t0RefToken_; }; } // namespace dtCalibration diff --git a/CalibMuon/DTCalibration/plugins/DTT0FillDefaultFromDB.cc b/CalibMuon/DTCalibration/plugins/DTT0FillDefaultFromDB.cc index a244cc86a7eec..d35469099797d 100644 --- a/CalibMuon/DTCalibration/plugins/DTT0FillDefaultFromDB.cc +++ b/CalibMuon/DTCalibration/plugins/DTT0FillDefaultFromDB.cc @@ -19,21 +19,21 @@ using namespace edm; namespace dtCalibration { - DTT0FillDefaultFromDB::DTT0FillDefaultFromDB(const ParameterSet& pset) - : dbLabelRef_(pset.getParameter("dbLabelRef")) {} + DTT0FillDefaultFromDB::DTT0FillDefaultFromDB(const ParameterSet& pset, edm::ConsumesCollector cc) + : t0Token_(cc.esConsumes()), + t0RefToken_( + cc.esConsumes(edm::ESInputTag("", pset.getParameter("dbLabelRef")))) {} DTT0FillDefaultFromDB::~DTT0FillDefaultFromDB() {} void DTT0FillDefaultFromDB::setES(const EventSetup& setup) { // Get t0 record from DB - ESHandle t0H; - setup.get().get(t0H); + ESHandle t0H = setup.getHandle(t0Token_); t0Map_ = &*t0H; LogVerbatim("Calibration") << "[DTT0FillDefaultFromDB] T0 version: " << t0H->version(); // Get reference t0 DB - ESHandle t0RefH; - setup.get().get(dbLabelRef_, t0RefH); + ESHandle t0RefH = setup.getHandle(t0RefToken_); t0MapRef_ = &*t0RefH; LogVerbatim("Calibration") << "[DTT0FillDefaultFromDB] Reference T0 version: " << t0RefH->version(); } diff --git a/CalibMuon/DTCalibration/plugins/DTT0FillDefaultFromDB.h b/CalibMuon/DTCalibration/plugins/DTT0FillDefaultFromDB.h index 46410d03497e2..2e75a34cc71a6 100644 --- a/CalibMuon/DTCalibration/plugins/DTT0FillDefaultFromDB.h +++ b/CalibMuon/DTCalibration/plugins/DTT0FillDefaultFromDB.h @@ -10,6 +10,10 @@ */ #include "CalibMuon/DTCalibration/interface/DTT0BaseCorrection.h" +#include "DataFormats/MuonDetId/interface/DTChamberId.h" +#include "CondFormats/DataRecord/interface/DTT0Rcd.h" +#include "CondFormats/DTObjects/interface/DTT0.h" +#include "FWCore/Framework/interface/ConsumesCollector.h" #include @@ -24,7 +28,7 @@ namespace dtCalibration { class DTT0FillDefaultFromDB : public DTT0BaseCorrection { public: // Constructor - DTT0FillDefaultFromDB(const edm::ParameterSet &); + DTT0FillDefaultFromDB(const edm::ParameterSet &, edm::ConsumesCollector cc); // Destructor ~DTT0FillDefaultFromDB() override; @@ -33,10 +37,11 @@ namespace dtCalibration { DTT0Data correction(const DTWireId &) override; private: - std::string dbLabelRef_; - const DTT0 *t0MapRef_; const DTT0 *t0Map_; + + edm::ESGetToken t0Token_; + edm::ESGetToken t0RefToken_; }; } // namespace dtCalibration diff --git a/CalibMuon/DTCalibration/plugins/DTT0WireInChamberReferenceCorrection.cc b/CalibMuon/DTCalibration/plugins/DTT0WireInChamberReferenceCorrection.cc index a54ee88af8ce0..3445680fe7baa 100644 --- a/CalibMuon/DTCalibration/plugins/DTT0WireInChamberReferenceCorrection.cc +++ b/CalibMuon/DTCalibration/plugins/DTT0WireInChamberReferenceCorrection.cc @@ -16,6 +16,7 @@ #include "DataFormats/MuonDetId/interface/DTWireId.h" #include "CondFormats/DTObjects/interface/DTT0.h" #include "CondFormats/DataRecord/interface/DTT0Rcd.h" +#include "FWCore/Framework/interface/ConsumesCollector.h" #include #include @@ -25,8 +26,11 @@ using namespace edm; namespace dtCalibration { - DTT0WireInChamberReferenceCorrection::DTT0WireInChamberReferenceCorrection(const ParameterSet& pset) - : calibChamber_(pset.getParameter("calibChamber")) { + DTT0WireInChamberReferenceCorrection::DTT0WireInChamberReferenceCorrection(const ParameterSet& pset, + edm::ConsumesCollector cc) + : calibChamber_(pset.getParameter("calibChamber")), + t0Token_(cc.esConsumes()), + dtGeomToken_(cc.esConsumes()) { //DTChamberId chosenChamberId; if (!calibChamber_.empty() && calibChamber_ != "None" && calibChamber_ != "All") { stringstream linestr; @@ -44,13 +48,12 @@ namespace dtCalibration { void DTT0WireInChamberReferenceCorrection::setES(const EventSetup& setup) { // Get t0 record from DB - ESHandle t0H; - setup.get().get(t0H); + ESHandle t0H = setup.getHandle(t0Token_); t0Map_ = &*t0H; LogVerbatim("Calibration") << "[DTT0WireInChamberReferenceCorrection] T0 version: " << t0H->version(); // Get geometry from Event Setup - setup.get().get(dtGeom_); + dtGeom_ = setup.getHandle(dtGeomToken_); } DTT0Data DTT0WireInChamberReferenceCorrection::correction(const DTWireId& wireId) { diff --git a/CalibMuon/DTCalibration/plugins/DTT0WireInChamberReferenceCorrection.h b/CalibMuon/DTCalibration/plugins/DTT0WireInChamberReferenceCorrection.h index 75d51a1cf74b1..da63a46b7d6bb 100644 --- a/CalibMuon/DTCalibration/plugins/DTT0WireInChamberReferenceCorrection.h +++ b/CalibMuon/DTCalibration/plugins/DTT0WireInChamberReferenceCorrection.h @@ -12,7 +12,11 @@ #include "CalibMuon/DTCalibration/interface/DTT0BaseCorrection.h" #include "DataFormats/MuonDetId/interface/DTChamberId.h" #include "FWCore/Framework/interface/ESHandle.h" - +#include "CondFormats/DataRecord/interface/DTT0Rcd.h" +#include "CondFormats/DTObjects/interface/DTT0.h" +#include "Geometry/Records/interface/MuonGeometryRecord.h" +#include "FWCore/Framework/interface/ConsumesCollector.h" +#include "FWCore/Utilities/interface/ESGetToken.h" #include namespace edm { @@ -27,7 +31,7 @@ namespace dtCalibration { class DTT0WireInChamberReferenceCorrection : public DTT0BaseCorrection { public: // Constructor - DTT0WireInChamberReferenceCorrection(const edm::ParameterSet&); + DTT0WireInChamberReferenceCorrection(const edm::ParameterSet&, edm::ConsumesCollector); // Destructor ~DTT0WireInChamberReferenceCorrection() override; @@ -43,6 +47,9 @@ namespace dtCalibration { DTChamberId chosenChamberId_; const DTT0* t0Map_; edm::ESHandle dtGeom_; + + edm::ESGetToken t0Token_; + edm::ESGetToken dtGeomToken_; }; } // namespace dtCalibration diff --git a/CalibMuon/DTCalibration/plugins/DTTPDeadWriter.cc b/CalibMuon/DTCalibration/plugins/DTTPDeadWriter.cc index d3d88c3c073eb..5ccbe21132750 100644 --- a/CalibMuon/DTCalibration/plugins/DTTPDeadWriter.cc +++ b/CalibMuon/DTCalibration/plugins/DTTPDeadWriter.cc @@ -33,10 +33,10 @@ using namespace std; using namespace edm; // Constructor -DTTPDeadWriter::DTTPDeadWriter(const ParameterSet& pset) : dtGeomToken_(esConsumes()) { +DTTPDeadWriter::DTTPDeadWriter(const ParameterSet& pset) : dtGeomToken_(esConsumes()) { // get selected debug option debug = pset.getUntrackedParameter("debug", false); - t0Token_ = esConsumes(edm::ESInputTag("", pset.getParameter("debug"))); + t0Token_ = esConsumes(edm::ESInputTag("", pset.getParameter("debug"))); // Create the object to be written to DB tpDeadList = new DTDeadFlag(); diff --git a/CalibMuon/DTCalibration/plugins/DTTTrigConstantShift.cc b/CalibMuon/DTCalibration/plugins/DTTTrigConstantShift.cc index 0e421c2b2bc45..04e6cf074e49b 100644 --- a/CalibMuon/DTCalibration/plugins/DTTTrigConstantShift.cc +++ b/CalibMuon/DTCalibration/plugins/DTTTrigConstantShift.cc @@ -12,6 +12,7 @@ #include "DataFormats/MuonDetId/interface/DTSuperLayerId.h" #include "CondFormats/DTObjects/interface/DTTtrig.h" #include "CondFormats/DataRecord/interface/DTTtrigRcd.h" +#include "FWCore/Framework/interface/ConsumesCollector.h" #include @@ -20,10 +21,10 @@ using namespace edm; namespace dtCalibration { - DTTTrigConstantShift::DTTTrigConstantShift(const ParameterSet& pset) - : dbLabel_(pset.getUntrackedParameter("dbLabel", "")), - calibChamber_(pset.getParameter("calibChamber")), - value_(pset.getParameter("value")) { + DTTTrigConstantShift::DTTTrigConstantShift(const ParameterSet& pset, edm::ConsumesCollector cc) + : calibChamber_(pset.getParameter("calibChamber")), value_(pset.getParameter("value")) { + ttrigToken_ = + cc.esConsumes(edm::ESInputTag("", pset.getUntrackedParameter("dbLabel"))); LogVerbatim("Calibration") << "[DTTTrigConstantShift] Applying constant correction value: " << value_ << endl; if (!calibChamber_.empty() && calibChamber_ != "None" && calibChamber_ != "All") { @@ -41,8 +42,7 @@ namespace dtCalibration { void DTTTrigConstantShift::setES(const EventSetup& setup) { // Get tTrig record from DB - ESHandle tTrig; - setup.get().get(dbLabel_, tTrig); + ESHandle tTrig = setup.getHandle(ttrigToken_); tTrigMap_ = &*tTrig; } diff --git a/CalibMuon/DTCalibration/plugins/DTTTrigConstantShift.h b/CalibMuon/DTCalibration/plugins/DTTTrigConstantShift.h index f9d9b66e8dc84..c1eb078a1d25b 100644 --- a/CalibMuon/DTCalibration/plugins/DTTTrigConstantShift.h +++ b/CalibMuon/DTCalibration/plugins/DTTTrigConstantShift.h @@ -11,6 +11,8 @@ #include "CalibMuon/DTCalibration/interface/DTTTrigBaseCorrection.h" #include "DataFormats/MuonDetId/interface/DTChamberId.h" +#include "CondFormats/DataRecord/interface/DTTtrigRcd.h" +#include "FWCore/Framework/interface/ConsumesCollector.h" #include @@ -25,7 +27,7 @@ namespace dtCalibration { class DTTTrigConstantShift : public DTTTrigBaseCorrection { public: // Constructor - DTTTrigConstantShift(const edm::ParameterSet&); + DTTTrigConstantShift(const edm::ParameterSet&, edm::ConsumesCollector); // Destructor ~DTTTrigConstantShift() override; @@ -34,12 +36,12 @@ namespace dtCalibration { DTTTrigData correction(const DTSuperLayerId&) override; private: - std::string dbLabel_; std::string calibChamber_; double value_; const DTTtrig* tTrigMap_; DTChamberId chosenChamberId_; + edm::ESGetToken ttrigToken_; }; } // namespace dtCalibration diff --git a/CalibMuon/DTCalibration/plugins/DTTTrigCorrection.cc b/CalibMuon/DTCalibration/plugins/DTTTrigCorrection.cc index 04889fb1a0e7e..d212be5bcf114 100644 --- a/CalibMuon/DTCalibration/plugins/DTTTrigCorrection.cc +++ b/CalibMuon/DTCalibration/plugins/DTTTrigCorrection.cc @@ -25,6 +25,8 @@ #include "CalibMuon/DTCalibration/interface/DTTTrigCorrectionFactory.h" #include "CalibMuon/DTCalibration/interface/DTTTrigBaseCorrection.h" +#include "FWCore/Framework/interface/ConsumesCollector.h" +#include "FWCore/Framework/interface/EDAnalyzer.h" #include #include @@ -33,9 +35,12 @@ using namespace edm; using namespace std; DTTTrigCorrection::DTTTrigCorrection(const ParameterSet& pset) - : dbLabel_(pset.getUntrackedParameter("dbLabel", "")), - correctionAlgo_{DTTTrigCorrectionFactory::get()->create( - pset.getParameter("correctionAlgo"), pset.getParameter("correctionAlgoConfig"))} { + : correctionAlgo_{DTTTrigCorrectionFactory::get()->create(pset.getParameter("correctionAlgo"), + pset.getParameter("correctionAlgoConfig"), + consumesCollector())} { + ttrigToken_ = + esConsumes(edm::ESInputTag("", pset.getUntrackedParameter("dbLabel"))); + dtGeomToken_ = esConsumes(); LogVerbatim("Calibration") << "[DTTTrigCorrection] Constructor called" << endl; } @@ -45,13 +50,12 @@ DTTTrigCorrection::~DTTTrigCorrection() { void DTTTrigCorrection::beginRun(const edm::Run& run, const edm::EventSetup& setup) { // Get tTrig record from DB - ESHandle tTrig; - setup.get().get(dbLabel_, tTrig); + ESHandle tTrig = setup.getHandle(ttrigToken_); tTrigMap_ = &*tTrig; LogVerbatim("Calibration") << "[DTTTrigCorrection]: TTrig version: " << tTrig->version() << endl; // Get geometry from Event Setup - setup.get().get(muonGeom_); + muonGeom_ = setup.getHandle(dtGeomToken_); // Pass EventSetup to correction Algo correctionAlgo_->setES(setup); diff --git a/CalibMuon/DTCalibration/plugins/DTTTrigCorrection.h b/CalibMuon/DTCalibration/plugins/DTTTrigCorrection.h index 89f63f4774e48..f518d1e787723 100644 --- a/CalibMuon/DTCalibration/plugins/DTTTrigCorrection.h +++ b/CalibMuon/DTCalibration/plugins/DTTTrigCorrection.h @@ -11,6 +11,10 @@ #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/EDAnalyzer.h" #include "FWCore/Framework/interface/ESHandle.h" +#include "FWCore/Framework/interface/ConsumesCollector.h" +#include "Geometry/Records/interface/MuonGeometryRecord.h" +#include "Geometry/DTGeometry/interface/DTGeometry.h" +#include "CondFormats/DataRecord/interface/DTTtrigRcd.h" #include @@ -37,11 +41,12 @@ class DTTTrigCorrection : public edm::EDAnalyzer { protected: private: - std::string dbLabel_; - const DTTtrig* tTrigMap_; edm::ESHandle muonGeom_; + edm::ESGetToken ttrigToken_; + edm::ESGetToken dtGeomToken_; + std::unique_ptr correctionAlgo_; }; #endif diff --git a/CalibMuon/DTCalibration/plugins/DTTTrigCorrectionFirst.cc b/CalibMuon/DTCalibration/plugins/DTTTrigCorrectionFirst.cc index 946c74ee204ee..5dd80b0ab82b8 100644 --- a/CalibMuon/DTCalibration/plugins/DTTTrigCorrectionFirst.cc +++ b/CalibMuon/DTCalibration/plugins/DTTTrigCorrectionFirst.cc @@ -26,13 +26,13 @@ using namespace edm; using namespace std; DTTTrigCorrectionFirst::DTTTrigCorrectionFirst(const ParameterSet& pset) - : dtGeomToken_(esConsumes()), ttrigToken_(esConsumes(edm::ESInputTag("", pset.getParameter("dbLabel")))) { + : dtGeomToken_(esConsumes()), + ttrigToken_( + esConsumes(edm::ESInputTag("", pset.getUntrackedParameter("dbLabel")))) { debug = pset.getUntrackedParameter("debug", false); ttrigMin = pset.getUntrackedParameter("ttrigMin", 0); ttrigMax = pset.getUntrackedParameter("ttrigMax", 5000); rmsLimit = pset.getUntrackedParameter("rmsLimit", 5.); - - dbLabel = pset.getUntrackedParameter("dbLabel", ""); } DTTTrigCorrectionFirst::~DTTTrigCorrectionFirst() {} diff --git a/CalibMuon/DTCalibration/plugins/DTTTrigCorrectionFirst.h b/CalibMuon/DTCalibration/plugins/DTTTrigCorrectionFirst.h index 70803fa64b4e8..4de93c25ba5e5 100644 --- a/CalibMuon/DTCalibration/plugins/DTTTrigCorrectionFirst.h +++ b/CalibMuon/DTCalibration/plugins/DTTTrigCorrectionFirst.h @@ -43,8 +43,6 @@ class DTTTrigCorrectionFirst : public edm::EDAnalyzer { const DTTtrig* tTrigMap; const edm::ESGetToken ttrigToken_; - std::string dbLabel; - bool debug; double ttrigMin, ttrigMax, rmsLimit; }; diff --git a/CalibMuon/DTCalibration/plugins/DTTTrigFillWithAverage.cc b/CalibMuon/DTCalibration/plugins/DTTTrigFillWithAverage.cc index 7bd083d3026dc..9386f412e8fb0 100644 --- a/CalibMuon/DTCalibration/plugins/DTTTrigFillWithAverage.cc +++ b/CalibMuon/DTCalibration/plugins/DTTTrigFillWithAverage.cc @@ -18,8 +18,11 @@ using namespace edm; namespace dtCalibration { - DTTTrigFillWithAverage::DTTTrigFillWithAverage(const ParameterSet& pset) : foundAverage_(false) { - dbLabel = pset.getUntrackedParameter("dbLabel", ""); + DTTTrigFillWithAverage::DTTTrigFillWithAverage(const ParameterSet& pset, edm::ConsumesCollector cc) + : foundAverage_(false) { + ttrigToken_ = + cc.esConsumes(edm::ESInputTag("", pset.getUntrackedParameter("dbLabel"))); + dtGeomToken_ = cc.esConsumes(); } DTTTrigFillWithAverage::~DTTTrigFillWithAverage() {} @@ -27,11 +30,11 @@ namespace dtCalibration { void DTTTrigFillWithAverage::setES(const EventSetup& setup) { // Get tTrig record from DB ESHandle tTrig; - setup.get().get(dbLabel, tTrig); + tTrig = setup.getHandle(ttrigToken_); tTrigMap_ = &*tTrig; // Get geometry from Event Setup - setup.get().get(muonGeom_); + muonGeom_ = setup.getHandle(dtGeomToken_); } DTTTrigData DTTTrigFillWithAverage::correction(const DTSuperLayerId& slId) { diff --git a/CalibMuon/DTCalibration/plugins/DTTTrigFillWithAverage.h b/CalibMuon/DTCalibration/plugins/DTTTrigFillWithAverage.h index fcc8b10e417cf..2f66d250daed1 100644 --- a/CalibMuon/DTCalibration/plugins/DTTTrigFillWithAverage.h +++ b/CalibMuon/DTCalibration/plugins/DTTTrigFillWithAverage.h @@ -10,6 +10,9 @@ #include "CalibMuon/DTCalibration/interface/DTTTrigBaseCorrection.h" #include "FWCore/Framework/interface/ESHandle.h" +#include "FWCore/Framework/interface/ConsumesCollector.h" +#include "Geometry/Records/interface/MuonGeometryRecord.h" +#include "CondFormats/DataRecord/interface/DTTtrigRcd.h" namespace edm { class ParameterSet; @@ -23,7 +26,7 @@ namespace dtCalibration { class DTTTrigFillWithAverage : public DTTTrigBaseCorrection { public: // Constructor - DTTTrigFillWithAverage(const edm::ParameterSet&); + DTTTrigFillWithAverage(const edm::ParameterSet&, edm::ConsumesCollector); // Destructor ~DTTTrigFillWithAverage() override; @@ -37,7 +40,8 @@ namespace dtCalibration { const DTTtrig* tTrigMap_; edm::ESHandle muonGeom_; - std::string dbLabel; + edm::ESGetToken ttrigToken_; + edm::ESGetToken dtGeomToken_; struct { float aveMean; diff --git a/CalibMuon/DTCalibration/plugins/DTTTrigMatchRPhi.cc b/CalibMuon/DTCalibration/plugins/DTTTrigMatchRPhi.cc index 4c4dc86f0e5f1..6f61a7ba133b5 100644 --- a/CalibMuon/DTCalibration/plugins/DTTTrigMatchRPhi.cc +++ b/CalibMuon/DTCalibration/plugins/DTTTrigMatchRPhi.cc @@ -19,16 +19,16 @@ using namespace edm; namespace dtCalibration { - DTTTrigMatchRPhi::DTTTrigMatchRPhi(const ParameterSet& pset) { - dbLabel = pset.getUntrackedParameter("dbLabel", ""); + DTTTrigMatchRPhi::DTTTrigMatchRPhi(const ParameterSet& pset, edm::ConsumesCollector cc) { + ttrigToken_ = + cc.esConsumes(edm::ESInputTag("", pset.getUntrackedParameter("dbLabel"))); } DTTTrigMatchRPhi::~DTTTrigMatchRPhi() {} void DTTTrigMatchRPhi::setES(const EventSetup& setup) { // Get tTrig record from DB - ESHandle tTrig; - setup.get().get(dbLabel, tTrig); + ESHandle tTrig = setup.getHandle(ttrigToken_); tTrigMap_ = &*tTrig; } diff --git a/CalibMuon/DTCalibration/plugins/DTTTrigMatchRPhi.h b/CalibMuon/DTCalibration/plugins/DTTTrigMatchRPhi.h index 340b647cdd4bb..77b4bcf7025e0 100644 --- a/CalibMuon/DTCalibration/plugins/DTTTrigMatchRPhi.h +++ b/CalibMuon/DTCalibration/plugins/DTTTrigMatchRPhi.h @@ -9,6 +9,8 @@ */ #include "CalibMuon/DTCalibration/interface/DTTTrigBaseCorrection.h" +#include "CondFormats/DataRecord/interface/DTTtrigRcd.h" +#include "FWCore/Framework/interface/ConsumesCollector.h" #include @@ -23,7 +25,7 @@ namespace dtCalibration { class DTTTrigMatchRPhi : public DTTTrigBaseCorrection { public: // Constructor - DTTTrigMatchRPhi(const edm::ParameterSet&); + DTTTrigMatchRPhi(const edm::ParameterSet&, edm::ConsumesCollector); // Destructor ~DTTTrigMatchRPhi() override; @@ -33,8 +35,7 @@ namespace dtCalibration { private: const DTTtrig* tTrigMap_; - - std::string dbLabel; + edm::ESGetToken ttrigToken_; }; } // namespace dtCalibration diff --git a/CalibMuon/DTCalibration/plugins/DTTTrigOffsetCalibration.cc b/CalibMuon/DTCalibration/plugins/DTTTrigOffsetCalibration.cc index 7faccb654a4ab..b36b872865276 100644 --- a/CalibMuon/DTCalibration/plugins/DTTTrigOffsetCalibration.cc +++ b/CalibMuon/DTCalibration/plugins/DTTTrigOffsetCalibration.cc @@ -38,8 +38,8 @@ DTTTrigOffsetCalibration::DTTTrigOffsetCalibration(const ParameterSet& pset) : theRecHits4DLabel_(pset.getParameter("recHits4DLabel")), doTTrigCorrection_(pset.getUntrackedParameter("doT0SegCorrection", false)), theCalibChamber_(pset.getUntrackedParameter("calibChamber", "All")), - dbLabel_(pset.getUntrackedParameter("dbLabel", "")), - ttrigToken_(esConsumes(edm::ESInputTag("", pset.getParameter("dbLabel")))), + ttrigToken_( + esConsumes(edm::ESInputTag("", pset.getUntrackedParameter("dbLabel")))), dtGeomToken_(esConsumes()) { LogVerbatim("Calibration") << "[DTTTrigOffsetCalibration] Constructor called!"; diff --git a/CalibMuon/DTCalibration/plugins/DTTTrigOffsetCalibration.h b/CalibMuon/DTCalibration/plugins/DTTTrigOffsetCalibration.h index 60c448faad1e4..8cf74428eb13c 100644 --- a/CalibMuon/DTCalibration/plugins/DTTTrigOffsetCalibration.h +++ b/CalibMuon/DTCalibration/plugins/DTTTrigOffsetCalibration.h @@ -47,7 +47,6 @@ class DTTTrigOffsetCalibration : public edm::EDAnalyzer { edm::InputTag theRecHits4DLabel_; bool doTTrigCorrection_; std::string theCalibChamber_; - std::string dbLabel_; TFile* rootFile_; const DTTtrig* tTrigMap_; diff --git a/CalibMuon/DTCalibration/plugins/DTTTrigResidualCorrection.cc b/CalibMuon/DTCalibration/plugins/DTTTrigResidualCorrection.cc index ac8f7cebfa63b..69eb3a8035763 100644 --- a/CalibMuon/DTCalibration/plugins/DTTTrigResidualCorrection.cc +++ b/CalibMuon/DTCalibration/plugins/DTTTrigResidualCorrection.cc @@ -42,15 +42,18 @@ using namespace edm; namespace dtCalibration { - DTTTrigResidualCorrection::DTTTrigResidualCorrection(const ParameterSet& pset) { + DTTTrigResidualCorrection::DTTTrigResidualCorrection(const ParameterSet& pset, edm::ConsumesCollector cc) { string residualsRootFile = pset.getParameter("residualsRootFile"); rootFile_ = new TFile(residualsRootFile.c_str(), "READ"); rootBaseDir_ = pset.getUntrackedParameter("rootBaseDir", "/DQMData/DT/DTCalibValidation"); useFit_ = pset.getParameter("useFitToResiduals"); //useConstantvDrift_ = pset.getParameter("useConstantDriftVelocity"); - dbLabel_ = pset.getUntrackedParameter("dbLabel", ""); useSlopesCalib_ = pset.getUntrackedParameter("useSlopesCalib", false); readLegacyVDriftDB = pset.getParameter("readLegacyVDriftDB"); + ttrigToken_ = + cc.esConsumes(edm::ESInputTag("", pset.getUntrackedParameter("dbLabel"))); + mTimeMapToken_ = cc.esConsumes(); + vDriftMapToken_ = cc.esConsumes(); // Load external slopes if (useSlopesCalib_) { @@ -81,20 +84,17 @@ namespace dtCalibration { void DTTTrigResidualCorrection::setES(const EventSetup& setup) { // Get tTrig record from DB ESHandle tTrig; - //setup.get().get(tTrig); - setup.get().get(dbLabel_, tTrig); + tTrig = setup.getHandle(ttrigToken_); tTrigMap_ = &*tTrig; // Get vDrift record if (readLegacyVDriftDB) { ESHandle mTimeHandle; - setup.get().get(mTimeHandle); - mTimeMap_ = &*mTimeHandle; + mTimeMap_ = &setup.getData(mTimeMapToken_); vDriftMap_ = nullptr; } else { ESHandle hVdrift; - setup.get().get(hVdrift); - vDriftMap_ = &*hVdrift; + vDriftMap_ = &setup.getData(vDriftMapToken_); mTimeMap_ = nullptr; // Consistency check: no parametrization is implemented for the time being int version = vDriftMap_->version(); diff --git a/CalibMuon/DTCalibration/plugins/DTTTrigResidualCorrection.h b/CalibMuon/DTCalibration/plugins/DTTTrigResidualCorrection.h index e13806bce3253..a37e75e2eb549 100644 --- a/CalibMuon/DTCalibration/plugins/DTTTrigResidualCorrection.h +++ b/CalibMuon/DTCalibration/plugins/DTTTrigResidualCorrection.h @@ -9,6 +9,10 @@ */ #include "CalibMuon/DTCalibration/interface/DTTTrigBaseCorrection.h" +#include "CondFormats/DataRecord/interface/DTTtrigRcd.h" +#include "CondFormats/DataRecord/interface/DTMtimeRcd.h" +#include "CondFormats/DataRecord/interface/DTRecoConditionsVdriftRcd.h" +#include "FWCore/Framework/interface/ConsumesCollector.h" #include @@ -29,7 +33,7 @@ namespace dtCalibration { class DTTTrigResidualCorrection : public DTTTrigBaseCorrection { public: // Constructor - DTTTrigResidualCorrection(const edm::ParameterSet&); + DTTTrigResidualCorrection(const edm::ParameterSet&, edm::ConsumesCollector cc); // Destructor ~DTTTrigResidualCorrection() override; @@ -45,7 +49,6 @@ namespace dtCalibration { std::string rootBaseDir_; bool useFit_; - std::string dbLabel_; bool useSlopesCalib_; double vDriftEff_[5][14][4][3]; @@ -56,6 +59,10 @@ namespace dtCalibration { bool readLegacyVDriftDB; // which one to use DTResidualFitter* fitter_; + + edm::ESGetToken ttrigToken_; + edm::ESGetToken mTimeMapToken_; + edm::ESGetToken vDriftMapToken_; }; } // namespace dtCalibration diff --git a/CalibMuon/DTCalibration/plugins/DTTTrigT0SegCorrection.cc b/CalibMuon/DTCalibration/plugins/DTTTrigT0SegCorrection.cc index 0a06ad51ec987..02630aaeb78b4 100644 --- a/CalibMuon/DTCalibration/plugins/DTTTrigT0SegCorrection.cc +++ b/CalibMuon/DTCalibration/plugins/DTTTrigT0SegCorrection.cc @@ -23,18 +23,18 @@ using namespace edm; namespace dtCalibration { - DTTTrigT0SegCorrection::DTTTrigT0SegCorrection(const ParameterSet& pset) { + DTTTrigT0SegCorrection::DTTTrigT0SegCorrection(const ParameterSet& pset, edm::ConsumesCollector cc) { string t0SegRootFile = pset.getParameter("t0SegRootFile"); rootFile_ = new TFile(t0SegRootFile.c_str(), "READ"); - dbLabel = pset.getUntrackedParameter("dbLabel", ""); + ttrigToken_ = + cc.esConsumes(edm::ESInputTag("", pset.getUntrackedParameter("dbLabel"))); } DTTTrigT0SegCorrection::~DTTTrigT0SegCorrection() { delete rootFile_; } void DTTTrigT0SegCorrection::setES(const EventSetup& setup) { // Get tTrig record from DB - ESHandle tTrig; - setup.get().get(dbLabel, tTrig); + ESHandle tTrig = setup.getHandle(ttrigToken_); tTrigMap_ = &*tTrig; } diff --git a/CalibMuon/DTCalibration/plugins/DTTTrigT0SegCorrection.h b/CalibMuon/DTCalibration/plugins/DTTTrigT0SegCorrection.h index 594f1b61bdaf7..7c8d758567f46 100644 --- a/CalibMuon/DTCalibration/plugins/DTTTrigT0SegCorrection.h +++ b/CalibMuon/DTCalibration/plugins/DTTTrigT0SegCorrection.h @@ -9,12 +9,15 @@ */ #include "CalibMuon/DTCalibration/interface/DTTTrigBaseCorrection.h" +#include "CondFormats/DataRecord/interface/DTTtrigRcd.h" +#include "FWCore/Framework/interface/ConsumesCollector.h" #include namespace edm { class ParameterSet; -} + class ConsumesCollector; +} // namespace edm class DTTtrig; @@ -26,7 +29,7 @@ namespace dtCalibration { class DTTTrigT0SegCorrection : public DTTTrigBaseCorrection { public: // Constructor - DTTTrigT0SegCorrection(const edm::ParameterSet&); + DTTTrigT0SegCorrection(const edm::ParameterSet&, edm::ConsumesCollector); // Destructor ~DTTTrigT0SegCorrection() override; @@ -40,9 +43,8 @@ namespace dtCalibration { TFile* rootFile_; - std::string dbLabel; - const DTTtrig* tTrigMap_; + edm::ESGetToken ttrigToken_; }; } // namespace dtCalibration diff --git a/CalibMuon/DTCalibration/plugins/DTVDriftMeanTimer.cc b/CalibMuon/DTCalibration/plugins/DTVDriftMeanTimer.cc index 8f0e7fe061ed8..99b54cb3f458b 100644 --- a/CalibMuon/DTCalibration/plugins/DTVDriftMeanTimer.cc +++ b/CalibMuon/DTCalibration/plugins/DTVDriftMeanTimer.cc @@ -29,7 +29,7 @@ using namespace edm; namespace dtCalibration { - DTVDriftMeanTimer::DTVDriftMeanTimer(const ParameterSet& pset) { + DTVDriftMeanTimer::DTVDriftMeanTimer(const ParameterSet& pset, edm::ConsumesCollector cc) { string rootFileName = pset.getParameter("rootFileName"); rootFile_ = new TFile(rootFileName.c_str(), "READ"); fitter_ = new DTMeanTimerFitter(rootFile_); diff --git a/CalibMuon/DTCalibration/plugins/DTVDriftMeanTimer.h b/CalibMuon/DTCalibration/plugins/DTVDriftMeanTimer.h index f980f1b61f778..66879a7cd3015 100644 --- a/CalibMuon/DTCalibration/plugins/DTVDriftMeanTimer.h +++ b/CalibMuon/DTCalibration/plugins/DTVDriftMeanTimer.h @@ -10,6 +10,7 @@ #include "CalibMuon/DTCalibration/interface/DTVDriftBaseAlgo.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" +#include "FWCore/Framework/interface/ConsumesCollector.h" class TFile; class DTMeanTimerFitter; @@ -18,7 +19,7 @@ namespace dtCalibration { class DTVDriftMeanTimer : public DTVDriftBaseAlgo { public: - DTVDriftMeanTimer(edm::ParameterSet const&); + DTVDriftMeanTimer(edm::ParameterSet const&, edm::ConsumesCollector); ~DTVDriftMeanTimer() override; void setES(const edm::EventSetup& setup) override; diff --git a/CalibMuon/DTCalibration/plugins/DTVDriftSegment.cc b/CalibMuon/DTCalibration/plugins/DTVDriftSegment.cc index 514f947e54c74..2aecd8c26bd7f 100644 --- a/CalibMuon/DTCalibration/plugins/DTVDriftSegment.cc +++ b/CalibMuon/DTCalibration/plugins/DTVDriftSegment.cc @@ -21,7 +21,7 @@ #include "CalibMuon/DTCalibration/interface/DTResidualFitter.h" #include "CalibMuon/DTCalibration/interface/DTCalibDBUtils.h" - +#include "FWCore/Framework/interface/ConsumesCollector.h" #include #include @@ -33,7 +33,7 @@ using namespace edm; namespace dtCalibration { - DTVDriftSegment::DTVDriftSegment(const ParameterSet& pset) + DTVDriftSegment::DTVDriftSegment(const ParameterSet& pset, edm::ConsumesCollector cc) : nSigmas_(pset.getUntrackedParameter("nSigmasFitRange", 1)), mTimeMap_(nullptr), vDriftMap_(nullptr) { @@ -45,6 +45,11 @@ namespace dtCalibration { //if(debug) fitter_->setVerbosity(1); readLegacyVDriftDB = pset.getParameter("readLegacyVDriftDB"); + if (readLegacyVDriftDB) { + mTimeMapToken_ = cc.esConsumes(); + } else { + vDriftMapToken_ = cc.esConsumes(); + } } DTVDriftSegment::~DTVDriftSegment() { @@ -55,13 +60,9 @@ namespace dtCalibration { void DTVDriftSegment::setES(const edm::EventSetup& setup) { // Get the map of vdrift from the setup if (readLegacyVDriftDB) { - ESHandle mTime; - setup.get().get(mTime); - mTimeMap_ = &*mTime; + mTimeMap_ = &setup.getData(mTimeMapToken_); } else { - ESHandle hVdrift; - setup.get().get(hVdrift); - vDriftMap_ = &*hVdrift; + vDriftMap_ = &setup.getData(vDriftMapToken_); // Consistency check: no parametrization is implemented for the time being int version = vDriftMap_->version(); if (version != 1) { diff --git a/CalibMuon/DTCalibration/plugins/DTVDriftSegment.h b/CalibMuon/DTCalibration/plugins/DTVDriftSegment.h index f1e42e452a086..a7fb70b4bc8cd 100644 --- a/CalibMuon/DTCalibration/plugins/DTVDriftSegment.h +++ b/CalibMuon/DTCalibration/plugins/DTVDriftSegment.h @@ -10,6 +10,12 @@ #include "CalibMuon/DTCalibration/interface/DTVDriftBaseAlgo.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" +#include "FWCore/Framework/interface/ConsumesCollector.h" +#include "FWCore/Framework/interface/EventSetup.h" +#include "FWCore/Framework/interface/ESHandle.h" +#include "CondFormats/DataRecord/interface/DTMtimeRcd.h" +#include "CondFormats/DataRecord/interface/DTRecoConditionsVdriftRcd.h" +#include "Geometry/Records/interface/MuonGeometryRecord.h" #include @@ -23,7 +29,7 @@ namespace dtCalibration { class DTVDriftSegment : public DTVDriftBaseAlgo { public: - DTVDriftSegment(edm::ParameterSet const&); + DTVDriftSegment(edm::ParameterSet const&, edm::ConsumesCollector); ~DTVDriftSegment() override; void setES(const edm::EventSetup& setup) override; @@ -40,6 +46,9 @@ namespace dtCalibration { bool readLegacyVDriftDB; // which one to use TFile* rootFile_; DTResidualFitter* fitter_; + + edm::ESGetToken mTimeMapToken_; + edm::ESGetToken vDriftMapToken_; }; } // namespace dtCalibration diff --git a/CalibMuon/DTCalibration/plugins/DTVDriftWriter.cc b/CalibMuon/DTCalibration/plugins/DTVDriftWriter.cc index 5a2ba83a87222..380241d479518 100644 --- a/CalibMuon/DTCalibration/plugins/DTVDriftWriter.cc +++ b/CalibMuon/DTCalibration/plugins/DTVDriftWriter.cc @@ -33,14 +33,15 @@ using namespace std; using namespace edm; DTVDriftWriter::DTVDriftWriter(const ParameterSet& pset) - : mTimeMapToken_(esConsumes()), - vDriftMapToken_(esConsumes()), - dtGeomToken_(esConsumes()), + : mTimeMapToken_(esConsumes()), + vDriftMapToken_(esConsumes()), + dtGeomToken_(esConsumes()), granularity_(pset.getUntrackedParameter("calibGranularity", "bySL")), mTimeMap_(nullptr), vDriftMap_(nullptr), vDriftAlgo_{DTVDriftPluginFactory::get()->create(pset.getParameter("vDriftAlgo"), - pset.getParameter("vDriftAlgoConfig"))} { + pset.getParameter("vDriftAlgoConfig"), + consumesCollector())} { LogVerbatim("Calibration") << "[DTVDriftWriter]Constructor called!"; if (granularity_ != "bySL") diff --git a/CalibMuon/DTCalibration/plugins/DTVDriftWriter.h b/CalibMuon/DTCalibration/plugins/DTVDriftWriter.h index ccd7a8bdf80b8..c956f79f3b00d 100644 --- a/CalibMuon/DTCalibration/plugins/DTVDriftWriter.h +++ b/CalibMuon/DTCalibration/plugins/DTVDriftWriter.h @@ -15,6 +15,7 @@ #include "CondFormats/DataRecord/interface/DTMtimeRcd.h" #include "CondFormats/DataRecord/interface/DTRecoConditionsVdriftRcd.h" #include "Geometry/Records/interface/MuonGeometryRecord.h" +#include "FWCore/Framework/interface/ConsumesCollector.h" #include diff --git a/CalibMuon/DTCalibration/plugins/SealModule.cc b/CalibMuon/DTCalibration/plugins/SealModule.cc index d82c14b088add..97f149efc0ccb 100644 --- a/CalibMuon/DTCalibration/plugins/SealModule.cc +++ b/CalibMuon/DTCalibration/plugins/SealModule.cc @@ -37,6 +37,7 @@ #include "CalibMuon/DTCalibration/plugins/DTT0FillChamberFromDB.h" #include "CalibMuon/DTCalibration/plugins/DTT0WireInChamberReferenceCorrection.h" #include "CalibMuon/DTCalibration/plugins/DTT0AbsoluteReferenceCorrection.h" +#include "CalibMuon/DTCalibration/plugins/DTT0FEBPathCorrection.h" #include "CalibMuon/DTCalibration/interface/DTVDriftPluginFactory.h" #include "CalibMuon/DTCalibration/plugins/DTVDriftMeanTimer.h" @@ -78,6 +79,7 @@ DEFINE_EDM_PLUGIN(DTT0CorrectionFactory, DEFINE_EDM_PLUGIN(DTT0CorrectionFactory, dtCalibration::DTT0AbsoluteReferenceCorrection, "DTT0AbsoluteReferenceCorrection"); +DEFINE_EDM_PLUGIN(DTT0CorrectionFactory, dtCalibration::DTT0FEBPathCorrection, "DTT0FEBPathCorrection"); DEFINE_EDM_PLUGIN(DTVDriftPluginFactory, dtCalibration::DTVDriftMeanTimer, "DTVDriftMeanTimer"); DEFINE_EDM_PLUGIN(DTVDriftPluginFactory, dtCalibration::DTVDriftSegment, "DTVDriftSegment"); diff --git a/CalibMuon/DTCalibration/python/dtT0AbsoluteReferenceCorrection_cfg.py b/CalibMuon/DTCalibration/python/dtT0AbsoluteReferenceCorrection_cfg.py index df27749ccbf8f..7b895cc5665f9 100644 --- a/CalibMuon/DTCalibration/python/dtT0AbsoluteReferenceCorrection_cfg.py +++ b/CalibMuon/DTCalibration/python/dtT0AbsoluteReferenceCorrection_cfg.py @@ -8,9 +8,6 @@ process.load("Configuration.StandardSequences.FrontierConditions_GlobalTag_cff") process.GlobalTag.globaltag = '' -#process.load("Configuration.StandardSequences.GeometryDB_cff") -#process.load("Configuration.StandardSequences.FrontierConditions_GlobalTag_cff") -#process.GlobalTag.globaltag = '' process.load("Configuration.StandardSequences.GeometryDB_cff") process.load("Configuration.StandardSequences.MagneticField_AutoFromDBCurrent_cff") process.load("Geometry.DTGeometry.dtGeometry_cfi") diff --git a/CalibMuon/DTCalibration/python/dtT0FillChamberFromDBCorrection_cfg.py b/CalibMuon/DTCalibration/python/dtT0FillChamberFromDBCorrection_cfg.py index 46c06cdab40c5..bb8ecfd76c566 100644 --- a/CalibMuon/DTCalibration/python/dtT0FillChamberFromDBCorrection_cfg.py +++ b/CalibMuon/DTCalibration/python/dtT0FillChamberFromDBCorrection_cfg.py @@ -7,6 +7,7 @@ process.load("Configuration.StandardSequences.FrontierConditions_GlobalTag_cff") process.GlobalTag.globaltag = '' + process.load("Configuration.StandardSequences.GeometryDB_cff") process.load("Configuration.StandardSequences.MagneticField_AutoFromDBCurrent_cff") process.load("Geometry.DTGeometry.dtGeometry_cfi") diff --git a/CalibMuon/DTCalibration/python/dtT0FillDefaultFromDBCorrection_cfg.py b/CalibMuon/DTCalibration/python/dtT0FillDefaultFromDBCorrection_cfg.py index 8c5e4b35c2069..82df6f51266b1 100644 --- a/CalibMuon/DTCalibration/python/dtT0FillDefaultFromDBCorrection_cfg.py +++ b/CalibMuon/DTCalibration/python/dtT0FillDefaultFromDBCorrection_cfg.py @@ -7,6 +7,7 @@ process.load("Configuration.StandardSequences.FrontierConditions_GlobalTag_cff") process.GlobalTag.globaltag = '' + process.load("Configuration.StandardSequences.GeometryDB_cff") process.load("Configuration.StandardSequences.MagneticField_AutoFromDBCurrent_cff") process.load("Geometry.DTGeometry.dtGeometry_cfi") diff --git a/CalibMuon/DTCalibration/python/dtTTrigCorrection_cfi.py b/CalibMuon/DTCalibration/python/dtTTrigCorrection_cfi.py index c056f91bba812..1730761d79a85 100644 --- a/CalibMuon/DTCalibration/python/dtTTrigCorrection_cfi.py +++ b/CalibMuon/DTCalibration/python/dtTTrigCorrection_cfi.py @@ -2,6 +2,7 @@ dtTTrigCorrection = cms.EDAnalyzer("DTTTrigCorrectionFirst", debug = cms.untracked.bool(False), + dbLabel = cms.untracked.string(''), ttrigMax = cms.untracked.double(700.0), ttrigMin = cms.untracked.double(200.0), rmsLimit = cms.untracked.double(8.) diff --git a/CalibMuon/DTCalibration/src/DTSegmentSelector.cc b/CalibMuon/DTCalibration/src/DTSegmentSelector.cc index a532bf07f30f2..708d0b1dd22ce 100644 --- a/CalibMuon/DTCalibration/src/DTSegmentSelector.cc +++ b/CalibMuon/DTCalibration/src/DTSegmentSelector.cc @@ -22,6 +22,7 @@ DTSegmentSelector::DTSegmentSelector(edm::ParameterSet const& pset, edm::Consume maxAnglePhi_(pset.getParameter("maxAnglePhi")), maxAngleZ_(pset.getParameter("maxAngleZ")) { muonToken_ = iC.consumes(muonTags_); + theStatusMapToken_ = iC.esConsumes(); } bool DTSegmentSelector::operator()(DTRecSegment4D const& segment, @@ -68,7 +69,7 @@ bool DTSegmentSelector::operator()(DTRecSegment4D const& segment, edm::ESHandle statusMap; if (checkNoisyChannels_) - setup.get().get(statusMap); + statusMap = setup.getHandle(theStatusMapToken_); // Get the Phi 2D segment int nPhiHits = -1; diff --git a/CalibMuon/DTCalibration/test/DBTools/DTT0Analyzer.cc b/CalibMuon/DTCalibration/test/DBTools/DTT0Analyzer.cc index a3549865b8592..5a3f5a3920a80 100644 --- a/CalibMuon/DTCalibration/test/DBTools/DTT0Analyzer.cc +++ b/CalibMuon/DTCalibration/test/DBTools/DTT0Analyzer.cc @@ -25,18 +25,19 @@ DTT0Analyzer::DTT0Analyzer(const ParameterSet& pset) { string rootFileName = pset.getUntrackedParameter("rootFileName"); theFile = new TFile(rootFileName.c_str(), "RECREATE"); theFile->cd(); + t0Token_ = esConsumes(); + dtGeomToken_ = esConsumes(); } DTT0Analyzer::~DTT0Analyzer() { theFile->Close(); } void DTT0Analyzer::beginRun(const edm::Run&, const edm::EventSetup& eventSetup) { //Get the t0 map from the DB - ESHandle t0; - eventSetup.get().get(t0); + ESHandle t0 = eventSetup.getHandle(t0Token_); tZeroMap = &*t0; // Get the DT Geometry - eventSetup.get().get(dtGeom); + dtGeom = eventSetup.getHandle(dtGeomToken_); } void DTT0Analyzer::endJob() { diff --git a/CalibMuon/DTCalibration/test/DBTools/DTT0Analyzer.h b/CalibMuon/DTCalibration/test/DBTools/DTT0Analyzer.h index aa1571534fc2e..a1bd8d8fbe835 100644 --- a/CalibMuon/DTCalibration/test/DBTools/DTT0Analyzer.h +++ b/CalibMuon/DTCalibration/test/DBTools/DTT0Analyzer.h @@ -10,9 +10,13 @@ #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/EDAnalyzer.h" #include "FWCore/Framework/interface/ESHandle.h" +#include "FWCore/Utilities/interface/ESGetToken.h" #include "DataFormats/MuonDetId/interface/DTLayerId.h" #include "DataFormats/MuonDetId/interface/DTWireId.h" #include "Geometry/DTGeometry/interface/DTGeometry.h" +#include "CondFormats/DataRecord/interface/DTT0Rcd.h" +#include "CondFormats/DTObjects/interface/DTT0.h" +#include "Geometry/Records/interface/MuonGeometryRecord.h" #include #include @@ -53,5 +57,8 @@ class DTT0Analyzer : public edm::EDAnalyzer { // Map of the t0 and sigma histos by layer std::map theMeanHistoMap; std::map theSigmaHistoMap; + + edm::ESGetToken t0Token_; + edm::ESGetToken dtGeomToken_; }; #endif diff --git a/CalibMuon/DTCalibration/test/DBTools/DTTTrigAnalyzer.cc b/CalibMuon/DTCalibration/test/DBTools/DTTTrigAnalyzer.cc index 510215c6e3ef8..94233b3457101 100644 --- a/CalibMuon/DTCalibration/test/DBTools/DTTTrigAnalyzer.cc +++ b/CalibMuon/DTCalibration/test/DBTools/DTTTrigAnalyzer.cc @@ -26,14 +26,14 @@ DTTTrigAnalyzer::DTTTrigAnalyzer(const ParameterSet &pset) { theFile->cd(); //The k factor to compute ttrig //kfactor = pset.getUntrackedParameter("kfactor",0); - dbLabel = pset.getUntrackedParameter("dbLabel", ""); + ttrigToken_ = + esConsumes(edm::ESInputTag("", pset.getUntrackedParameter("dbLabel"))); } DTTTrigAnalyzer::~DTTTrigAnalyzer() { theFile->Close(); } void DTTTrigAnalyzer::beginRun(const edm::Run &, const edm::EventSetup &eventSetup) { - ESHandle tTrig; - eventSetup.get().get(dbLabel, tTrig); + ESHandle tTrig = eventSetup.getHandle(ttrigToken_); tTrigMap = &*tTrig; cout << "[DTTTrigAnalyzer] TTrig version: " << tTrig->version() << endl; } diff --git a/CalibMuon/DTCalibration/test/DBTools/DTTTrigAnalyzer.h b/CalibMuon/DTCalibration/test/DBTools/DTTTrigAnalyzer.h index 518afcf3b9283..7ae652f207f43 100644 --- a/CalibMuon/DTCalibration/test/DBTools/DTTTrigAnalyzer.h +++ b/CalibMuon/DTCalibration/test/DBTools/DTTTrigAnalyzer.h @@ -11,6 +11,7 @@ #include "FWCore/Framework/interface/EDAnalyzer.h" #include "FWCore/Framework/interface/ESHandle.h" #include "DataFormats/MuonDetId/interface/DTWireId.h" +#include "CondFormats/DataRecord/interface/DTTtrigRcd.h" #include #include @@ -47,8 +48,6 @@ class DTTTrigAnalyzer : public edm::EDAnalyzer { //The t0 map const DTTtrig* tTrigMap; - std::string dbLabel; - //The k factor //double kfactor; @@ -62,5 +61,7 @@ class DTTTrigAnalyzer : public edm::EDAnalyzer { std::map, TH1D*> theTMeanDistribMap; std::map, TH1D*> theSigmaDistribMap; std::map, TH1D*> theKFactorDistribMap; + + edm::ESGetToken ttrigToken_; }; #endif diff --git a/CalibMuon/DTCalibration/test/DBTools/DTVDriftAnalyzer.cc b/CalibMuon/DTCalibration/test/DBTools/DTVDriftAnalyzer.cc index 6bd906fb2cb6d..91b191112198e 100644 --- a/CalibMuon/DTCalibration/test/DBTools/DTVDriftAnalyzer.cc +++ b/CalibMuon/DTCalibration/test/DBTools/DTVDriftAnalyzer.cc @@ -28,20 +28,20 @@ DTVDriftAnalyzer::DTVDriftAnalyzer(const ParameterSet& pset) string rootFileName = pset.getUntrackedParameter("rootFileName"); theFile = new TFile(rootFileName.c_str(), "RECREATE"); theFile->cd(); + mTimeMapToken_ = esConsumes(); + vDriftMapToken_ = esConsumes(); } DTVDriftAnalyzer::~DTVDriftAnalyzer() { theFile->Close(); } void DTVDriftAnalyzer::beginRun(const edm::Run& run, const edm::EventSetup& eventSetup) { if (readLegacyVDriftDB) { - ESHandle mTime; - eventSetup.get().get(mTime); + ESHandle mTime = eventSetup.getHandle(mTimeMapToken_); mTimeMap = &*mTime; vDriftMap_ = nullptr; edm::LogVerbatim("DTVDriftAnalyzer") << "[DTVDriftAnalyzer] MTime version: " << mTime->version() << endl; } else { - ESHandle hVdrift; - eventSetup.get().get(hVdrift); + ESHandle hVdrift = eventSetup.getHandle(vDriftMapToken_); vDriftMap_ = &*hVdrift; mTimeMap = nullptr; // Consistency check: no parametrization is implemented for the time being diff --git a/CalibMuon/DTCalibration/test/DBTools/DTVDriftAnalyzer.h b/CalibMuon/DTCalibration/test/DBTools/DTVDriftAnalyzer.h index e6c85041f5c78..bb48ee5c9ce5a 100644 --- a/CalibMuon/DTCalibration/test/DBTools/DTVDriftAnalyzer.h +++ b/CalibMuon/DTCalibration/test/DBTools/DTVDriftAnalyzer.h @@ -11,6 +11,8 @@ #include "FWCore/Framework/interface/EDAnalyzer.h" #include "FWCore/Framework/interface/ESHandle.h" #include "DataFormats/MuonDetId/interface/DTWireId.h" +#include "CondFormats/DataRecord/interface/DTMtimeRcd.h" +#include "CondFormats/DataRecord/interface/DTRecoConditionsVdriftRcd.h" #include #include @@ -56,5 +58,8 @@ class DTVDriftAnalyzer : public edm::EDAnalyzer { // Map of the vdrift, reso distributions by wheel/station/SL std::map, TH1D*> theVDriftDistribMap; std::map, TH1D*> theResoDistribMap; + + edm::ESGetToken mTimeMapToken_; + edm::ESGetToken vDriftMapToken_; }; #endif diff --git a/CalibMuon/DTCalibration/test/DBTools/DumpFileToDB.cc b/CalibMuon/DTCalibration/test/DBTools/DumpFileToDB.cc index f0bf44d53ab32..f148f18aa09d9 100644 --- a/CalibMuon/DTCalibration/test/DBTools/DumpFileToDB.cc +++ b/CalibMuon/DTCalibration/test/DBTools/DumpFileToDB.cc @@ -36,6 +36,7 @@ using namespace std; DumpFileToDB::DumpFileToDB(const ParameterSet& pset) { dbToDump = pset.getUntrackedParameter("dbToDump", "TTrigDB"); format = pset.getUntrackedParameter("dbFormat", "Legacy"); + ttrigToken_ = esConsumes(); cout << "Writing DB: " << dbToDump << " with format: " << format << endl; @@ -329,8 +330,7 @@ vector DumpFileToDB::readChannelsMap(stringstream& linestr) { void DumpFileToDB::beginRun(const edm::Run& run, const edm::EventSetup& setup) { if (diffMode) { if (dbToDump == "TTrigDB") { // read the original DB - ESHandle tTrig; - setup.get().get(tTrig); + ESHandle tTrig = setup.getHandle(ttrigToken_); tTrigMapOrig = &*tTrig; cout << "[DumpDBToFile] TTrig version: " << tTrig->version() << endl; } diff --git a/CalibMuon/DTCalibration/test/DBTools/DumpFileToDB.h b/CalibMuon/DTCalibration/test/DBTools/DumpFileToDB.h index caf00c5652085..ff655b5effc05 100644 --- a/CalibMuon/DTCalibration/test/DBTools/DumpFileToDB.h +++ b/CalibMuon/DTCalibration/test/DBTools/DumpFileToDB.h @@ -11,6 +11,7 @@ #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/one/EDAnalyzer.h" +#include "CondFormats/DataRecord/interface/DTTtrigRcd.h" #include #include @@ -49,5 +50,7 @@ class DumpFileToDB : public edm::one::EDAnalyzer { // sum the correction in the txt file (for the mean value) to what is input DB bool diffMode; const DTTtrig* tTrigMapOrig; + + edm::ESGetToken ttrigToken_; }; #endif diff --git a/CalibMuon/DTCalibration/test/DBTools/FakeTTrig.cc b/CalibMuon/DTCalibration/test/DBTools/FakeTTrig.cc index 003584fc7d5c3..943de2b2fdf23 100644 --- a/CalibMuon/DTCalibration/test/DBTools/FakeTTrig.cc +++ b/CalibMuon/DTCalibration/test/DBTools/FakeTTrig.cc @@ -44,8 +44,9 @@ FakeTTrig::FakeTTrig(const ParameterSet& pset) : dataBaseWriteWasDone(false) { // further configurable smearing smearing = pset.getUntrackedParameter("smearing"); - dbLabel = pset.getUntrackedParameter("dbLabel", ""); - + ttrigToken_ = + esConsumes(edm::ESInputTag("", pset.getUntrackedParameter("dbLabel"))); + dtGeomToken_ = esConsumes(); // get random engine edm::Service rng; if (!rng.isAvailable()) { @@ -58,11 +59,11 @@ FakeTTrig::~FakeTTrig() { cout << "[FakeTTrig] Destructor called! " << endl; } void FakeTTrig::beginRun(const edm::Run&, const EventSetup& setup) { cout << "[FakeTTrig] entered into beginRun! " << endl; - setup.get().get(muonGeom); + muonGeom = setup.getHandle(dtGeomToken_); // Get the tTrig reference map if (ps.getUntrackedParameter("readDB", true)) - setup.get().get(dbLabel, tTrigMapRef); + tTrigMapRef = setup.getHandle(ttrigToken_); } void FakeTTrig::beginLuminosityBlock(edm::LuminosityBlock const& lumi, edm::EventSetup const&) { diff --git a/CalibMuon/DTCalibration/test/DBTools/FakeTTrig.h b/CalibMuon/DTCalibration/test/DBTools/FakeTTrig.h index 696d60753b4c1..828e7d471b537 100644 --- a/CalibMuon/DTCalibration/test/DBTools/FakeTTrig.h +++ b/CalibMuon/DTCalibration/test/DBTools/FakeTTrig.h @@ -15,7 +15,9 @@ #include "FWCore/Framework/interface/EDAnalyzer.h" #include "FWCore/Framework/interface/ESHandle.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" - +#include "Geometry/Records/interface/MuonGeometryRecord.h" +#include "Geometry/DTGeometry/interface/DTGeometry.h" +#include "CondFormats/DataRecord/interface/DTTtrigRcd.h" #include class DTGeometry; class DTSuperLayer; @@ -47,8 +49,6 @@ class FakeTTrig : public edm::EDAnalyzer { double smearing; - std::string dbLabel; - /// tTrig from the DB float tTrigRef; float tTrigRMSRef; @@ -58,5 +58,8 @@ class FakeTTrig : public edm::EDAnalyzer { edm::ESHandle tTrigMapRef; bool dataBaseWriteWasDone; + + edm::ESGetToken ttrigToken_; + edm::ESGetToken dtGeomToken_; }; #endif diff --git a/CalibMuon/DTCalibration/test/DBTools/ShiftTTrigDB.cc b/CalibMuon/DTCalibration/test/DBTools/ShiftTTrigDB.cc index 3b19e774bcc94..eb6d1c588861f 100644 --- a/CalibMuon/DTCalibration/test/DBTools/ShiftTTrigDB.cc +++ b/CalibMuon/DTCalibration/test/DBTools/ShiftTTrigDB.cc @@ -30,7 +30,10 @@ ShiftTTrigDB::ShiftTTrigDB(const ParameterSet& pset) { shifts = pset.getParameter >("shifts"); //Read the chambers to be shifted vector parameters = pset.getParameter >("chambers"); - dbLabel = pset.getUntrackedParameter("dbLabel", ""); + + ttrigToken_ = + esConsumes(edm::ESInputTag("", pset.getUntrackedParameter("dbLabel"))); + dtGeomToken_ = esConsumes(); int counter = 0; for (vector::iterator parameter = parameters.begin(); parameter != parameters.end(); ++parameter) { @@ -55,12 +58,10 @@ ShiftTTrigDB::ShiftTTrigDB(const ParameterSet& pset) { ShiftTTrigDB::~ShiftTTrigDB() {} void ShiftTTrigDB::beginRun(const edm::Run&, const EventSetup& setup) { - ESHandle tTrig; - setup.get().get(dbLabel, tTrig); + ESHandle tTrig = setup.getHandle(ttrigToken_); tTrigMap = &*tTrig; cout << "[ShiftTTrigDB]: TTrig version: " << tTrig->version() << endl; - - setup.get().get(muonGeom); + muonGeom = setup.getHandle(dtGeomToken_); } void ShiftTTrigDB::endJob() { diff --git a/CalibMuon/DTCalibration/test/DBTools/ShiftTTrigDB.h b/CalibMuon/DTCalibration/test/DBTools/ShiftTTrigDB.h index ba1a15b779432..a6429e231b057 100644 --- a/CalibMuon/DTCalibration/test/DBTools/ShiftTTrigDB.h +++ b/CalibMuon/DTCalibration/test/DBTools/ShiftTTrigDB.h @@ -11,6 +11,9 @@ #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/EDAnalyzer.h" #include "FWCore/Framework/interface/ESHandle.h" +#include "Geometry/Records/interface/MuonGeometryRecord.h" +#include "Geometry/DTGeometry/interface/DTGeometry.h" +#include "CondFormats/DataRecord/interface/DTTtrigRcd.h" #include #include @@ -40,11 +43,12 @@ class ShiftTTrigDB : public edm::EDAnalyzer { const DTTtrig* tTrigMap; edm::ESHandle muonGeom; - std::string dbLabel; - std::vector > chambers; std::vector shifts; std::map, double> mapShiftsByChamber; bool debug; + + edm::ESGetToken ttrigToken_; + edm::ESGetToken dtGeomToken_; }; #endif diff --git a/CalibPPS/AlignmentGlobal/README.md b/CalibPPS/AlignmentGlobal/README.md index 74f93ad42810a..2ed157af113b5 100644 --- a/CalibPPS/AlignmentGlobal/README.md +++ b/CalibPPS/AlignmentGlobal/README.md @@ -1,125 +1,133 @@ # PPSAlignmentWorker -## Config example: -[`ppsAlignmentWorker_cfi.py`](python/ppsAlignmentWorker_cfi.py) ## Parameters: | Name | Type | Description | |-------------|----------------|--------------------------------------------------------------------------| -| `tagTracks` | `cms.InputTag` | Should be set to `"ctppsLocalTrackLiteProducer"`. | +| `tagTracks` | `cms.InputTag` | Should be set to `"ctppsLocalTrackLiteProducer"`. | | `folder` | `cms.string` | Should be the same as the `folder` parameter in DQM configuration. | | `label` | `cms.string` | Label for EventSetup | | `debug` | `cms.bool` | When set to `True`, the worker will produce some extra debug histograms. | # PPSAlignmentHarvester -## Config example: -[`ppsAlignmentHarvester_cfi.py`](python/ppsAlignmentHarvester_cfi.py) ## Parameters: -| Name | Type | Description | -|----------|--------------|---------------------------------------------------------------------------------------| -| `folder` | `cms.string` | Should be the same as the `folder` parameter in DQM configuration. | -| `debug` | `cms.bool` | When set to `True`, the harvester will produce an extra ROOT file with debug plots. | +| Name | Type | Description | +|-------------------------------|---------------|---------------------------------------------------------------------------------------------------------------------------------------------------------| +| `folder` | `cms.string` | Should be the same as the `folder` parameter in DQM configuration. | +| `sequence` | `cms.vstring` | Determines order of the alignment methods: `"x_alignemnt"`, `"x_alignment_relative"`, `"y_alignment"`. | +| `overwrite_sh_x` | `cms.bool` | If set to `True`, `x alignment` will overwrite horizontal shift passed in the configuration. | +| `test_results_path` | `cms.string` | Path of a file with the results. If empty (`""`), the file will not be created. | +| `write_sqlite_results` | `cms.bool` | When set to `True`, the harvester will try to use PoolDBOutputService to save the final results. | +| `x_ali_rel_final_slope_fixed` | `cms.bool` | `True`: the harvester will use the x relative alignment results with fixed slope to prepare final merged results. `False`: results without fixed slope. | +| `y_ali_final_slope_fixed` | `cms.bool` | `True`: the harvester will use the y alignment results with fixed slope to prepare final merged results. `False`: results without fixed slope. | +| `debug` | `cms.bool` | When set to `True`, the harvester will produce an extra ROOT file with debug plots. | # Event Setup Default values come from the `fillDescriptions` method in `CalibPPS/ESProducers/plugins/PPSAlignmentConfigESSource.cc`.
NB: Parameters here are written in snake_case. Many of them are in camelCase in the code (as PPSAlignmentConfig getters). -| Name | Type | Default | Description | -|------------------------|---------------|----------------------------------------|--------------------------------------------------------------------------------------------------------------| -| `debug` | `cms.bool` | `False` | When set to `True`, the ESProducer will produce an extra ROOT file with debug plots (from reference run). | -| `label` | `cms.string` | `""` | label to distinguish reference and test fill configs. Should be set either to `""` (test) or `"reference"` | -| `sequence` | `cms.vstring` | empty vector | Determines order of the alignment methods: `"x_alignemnt"`, `"x_alignment_relative"`, `"y_alignment"`. | -| `results_dir` | `cms.string` | `"./alignment_results.txt"` | Directory of a file with the results. If empty (`""`), the file will not be created. | -| `sector_45` | `cms.PSet` | [details below](#Sector-config) | Configuration of sector 45. [Details below](#Sector-config) | -| `sector_56` | `cms.PSet` | [details below](#Sector-config) | Configuration of sector 56. [Details below](#Sector-config) | -| `x_ali_sh_step` | `cms.double` | `0.01` | Step for x alignment algorithm | -| `y_mode_sys_unc` | `cms.double` | `0.03` | Squared is an element of y mode uncertainty in y alignment. | -| `chiSqThreshold` | `cms.double` | `50.` | Chi-square threshold of y mode | -| `y_mode_unc_max_valid` | `cms.double` | `5.` | Maximal valid y mode uncertainty | -| `y_mode_max_valid` | `cms.double` | `20.` | Maximal valid y mode | -| `max_RP_tracks_size` | `cms.uint32` | `2.` | Maximal tracksUp or tracksDw size to avoid crowded events | -| `n_si` | `cms.double` | `4.` | Element of checking whether the cuts passed | -| `matching` | `cms.PSet` | [details below](#matching) | Reference dataset parameters. [Details below](#matching) | -| `x_alignment_meth_o` | `cms.PSet` | [details below](#x_alignment_meth_o) | X alignment parameters. (Details below)[#x_alignment_meth_o] | -| `x_alignment_relative` | `cms.PSet` | [details below](#x_alignment_relative) | Relative x alignment parameters. [Details below](#x_aligmment_relative) | -| `y_alignment` | `cms.PSet` | [details below](#y_alignment) | Y alignment parameters. [Details below](#y_alignment) | -| `binning` | `cms.PSet` | [details below](#binning) | Binning parameters for worker. [Details below](#binning) | +| Name | Type | Default | Description | +|------------------------|---------------|----------------------------------------|------------------------------------------------------------------------------------------------------------| +| `debug` | `cms.bool` | `False` | When set to `True`, the ESProducer will produce an extra ROOT file with debug plots (from reference run). | +| `label` | `cms.string` | `""` | label to distinguish reference and test fill configs. Should be set either to `""` (test) or `"reference"` | +| `sector_45` | `cms.PSet` | [details below](#Sector-config) | Configuration of sector 45. [Details below](#Sector-config) | +| `sector_56` | `cms.PSet` | [details below](#Sector-config) | Configuration of sector 56. [Details below](#Sector-config) | +| `x_ali_sh_step` | `cms.double` | `0.01` | Step for x alignment algorithm [mm] | +| `y_mode_sys_unc` | `cms.double` | `0.03` | Squared is an element of y mode uncertainty in y alignment. | +| `chiSqThreshold` | `cms.double` | `50.` | Chi-square threshold of y mode | +| `y_mode_unc_max_valid` | `cms.double` | `5.` | Maximum valid y mode uncertainty | +| `y_mode_max_valid` | `cms.double` | `20.` | Maximum valid y mode | +| `min_RP_tracks_size` | `cms.uint32` | `1` | Minimum number of tracks in each RP | +| `max_RP_tracks_size` | `cms.uint32` | `1` | Maximum number of tracks in each RP | +| `n_si` | `cms.double` | `4.` | Element of checking whether the cuts passed | +| `matching` | `cms.PSet` | [details below](#matching) | Reference dataset parameters. [Details below](#matching) | +| `x_alignment_meth_o` | `cms.PSet` | [details below](#x_alignment_meth_o) | X alignment parameters. [Details below](#x_alignment_meth_o) | +| `x_alignment_relative` | `cms.PSet` | [details below](#x_alignment_relative) | Relative x alignment parameters. [Details below](#x_aligmment_relative) | +| `y_alignment` | `cms.PSet` | [details below](#y_alignment) | Y alignment parameters. [Details below](#y_alignment) | +| `binning` | `cms.PSet` | [details below](#binning) | Binning parameters for worker. [Details below](#binning) | +| `extraParams` | `cms.vdouble` | empty vector | Extra vector of doubles added in case new parameters need to be added in the future | ## Sector config -| Name | Type | Default (s_45) | Default (s_56) | Description | -|---------------|--------------|-------------------------------|-------------------------------|------------------------------------------------------| -| `rp_N` | `cms.PSet` | [details below](#RP-config) | [details below](#RP-config) | Near RP configuration. [Details below](#RP-config) | -| `rp_F` | `cms.PSet` | [details below](#RP-config) | [details below](#RP-config) | Far RP configuration. [Details below](#RP-config) | -| `slope` | `cms.double` | `0.006` | `-0.015` | Base slope value | -| `cut_h_apply` | `cms.bool` | `True` | `True` | If set to `True`, cut_h is applied | -| `cut_h_a` | `cms.double` | `-1.` | `-1.` | cut_h parameter | -| `cut_h_c` | `cms.double` | `-38.55` | `-39.26` | cut_h parameter | -| `cut_h_si` | `cms.double` | `0.2` | `0.2` | cut_h parameter | -| `cut_v_apply` | `cms.bool` | `True` | `True` | If set to `True`, cut_v is applied | -| `cut_v_a` | `cms.double` | `-1.07` | `-1.07` | cut_v parameter | -| `cut_v_c` | `cms.double` | `1.63` | `1.49` | cut_v parameter | -| `cut_v_si` | `cms.double` | `0.15` | `0.15` | cut_v parameter | +| Name | Type | Default (s_45) | Default (s_56) | Description | +|---------------|--------------|-----------------------------|-----------------------------|----------------------------------------------------| +| `rp_N` | `cms.PSet` | [details below](#RP-config) | [details below](#RP-config) | Near RP configuration. [Details below](#RP-config) | +| `rp_F` | `cms.PSet` | [details below](#RP-config) | [details below](#RP-config) | Far RP configuration. [Details below](#RP-config) | +| `slope` | `cms.double` | `0.006` | `-0.015` | Base slope value | +| `cut_h_apply` | `cms.bool` | `True` | `True` | If set to `True`, cut_h is applied | +| `cut_h_a` | `cms.double` | `-1.` | `-1.` | cut_h parameter | +| `cut_h_c` | `cms.double` | `-38.55` | `-39.26` | cut_h parameter | +| `cut_h_si` | `cms.double` | `0.2` | `0.2` | cut_h parameter | +| `cut_v_apply` | `cms.bool` | `True` | `True` | If set to `True`, cut_v is applied | +| `cut_v_a` | `cms.double` | `-1.07` | `-1.07` | cut_v parameter | +| `cut_v_c` | `cms.double` | `1.63` | `1.49` | cut_v parameter | +| `cut_v_si` | `cms.double` | `0.15` | `0.15` | cut_v parameter | ### RP config -| Name | Type | Default (s_45, rp_N) | Default (s_45, rp_F) | Default (s_56, rp_N) | Default (s_56, rp_F) | Description | -|------------------|--------------|----------------------|----------------------|----------------------|----------------------|---------------------------------------------------------------------------------------------------------------------------------| -| `name` | `cms.string` | `"L_1_F"` | `"L_2_F"` | `"R_1_F"` | `"R_2_F"` | Name of the RP | -| `id` | `cms.int32` | `3` | `23` | `103` | `123` | ID of the RP | -| `slope` | `cms.double` | `0.19` | `0.19` | `0.40` | `0.39` | Base slope value | -| `sh_x` | `cms.double` | `-3.6` | `-42.` | `-2.8` | `-41.9` | Base sh_x value. X alignment method overwrites it. | +| Name | Type | Default (s_45, rp_N) | Default (s_45, rp_F) | Default (s_56, rp_N) | Default (s_56, rp_F) | Description | +|------------------|--------------|----------------------|----------------------|----------------------|----------------------|-------------------------------------------------------------------------------------------------------------------------------| +| `name` | `cms.string` | `"L_1_F"` | `"L_2_F"` | `"R_1_F"` | `"R_2_F"` | Name of the RP | +| `id` | `cms.int32` | `3` | `23` | `103` | `123` | ID of the RP | +| `slope` | `cms.double` | `0.19` | `0.19` | `0.40` | `0.39` | Base slope value | +| `sh_x` | `cms.double` | `-3.6` | `-42.` | `-2.8` | `-41.9` | Base sh_x value [mm]. X alignment method overwrites it. | | `x_min_fit_mode` | `cms.double` | `2.` | `2.` | `2.` | `2.` | Mode graph parameter. See [buildModeGraph](plugins/PPSAlignmentHarvester.cc#L648). | | `x_max_fit_mode` | `cms.double` | `7.` | `7.5` | `7.4` | `8.` | Mode graph parameter. See [buildModeGraph](plugins/PPSAlignmentHarvester.cc#L648). | | `y_max_fit_mode` | `cms.double` | `7.` | `7.5` | `7.4` | `8.` | Mode graph parameter (in 2018 the same value as x_max_fit_mode). See [buildModeGraph](plugins/PPSAlignmentHarvester.cc#L654). | -| `y_cen_add` | `cms.double` | `-0.3` | `-0.3` | `-0.8` | `-0.8` | The value is added to y_cen (mean of y) while constructing a graph in x alignment. | -| `y_width_mult` | `cms.double` | `1.1` | `1.1` | `1.0` | `1.` | y_width (RMS of y) is multiplied by the value when constructing a graph in x alignment. | -| `x_slice_min` | `cms.double` | `7.` | `46.` | `6.` | `45.` | Min x for slice plots (x alignment) | -| `x_slice_max` | `cms.double` | `19.` | `58.` | `17.` | `57.` | Max x for slice plots (x alignment) | -| `x_slice_w` | `cms.double` | `0.2` | `0.2` | `0.2` | `0.2` | X width for slice plots (x alignment) | +| `y_cen_add` | `cms.double` | `-0.3` | `-0.3` | `-0.8` | `-0.8` | The value is added to y_cen (mean of y) while constructing a graph in x alignment. | +| `y_width_mult` | `cms.double` | `1.1` | `1.1` | `1.0` | `1.` | y_width (RMS of y) is multiplied by the value when constructing a graph in x alignment. | +| `x_slice_min` | `cms.double` | `7.` | `46.` | `6.` | `45.` | Min x for slice plots (x alignment) | +| `x_slice_max` | `cms.double` | `19.` | `58.` | `17.` | `57.` | Max x for slice plots (x alignment) | +| `x_slice_w` | `cms.double` | `0.2` | `0.2` | `0.2` | `0.2` | X width for slice plots (x alignment) | ## matching -Should be set in the reference config! -| Name | Type | Default | Description | -|---------------------|--------------|-------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| `reference_dataset` | `cms.string` | `""` | Directory of the file with reference dataset histograms. Should be empty when running the worker for the reference dataset. After that, should be set to the name of the created ROOT file. | -| `rp_L_F` | `cms.PSet` | `-43.` - `-41.` | Left far RP. Contains two parameters of type `cms.double`: `sh_min` and `sh_max` - shift range for x alignment | -| `rp_L_N` | `cms.PSet` | `-4.2` - `-2.4` | Left near RP. Contains two parameters of type `cms.double`: `sh_min` and `sh_max` - shift range for x alignment | -| `rp_R_N` | `cms.PSet` | `-3.6` - `-1.8` | Right near RP. Contains two parameters of type `cms.double`: `sh_min` and `sh_max` - shift range for x alignment | -| `rp_R_F` | `cms.PSet` | `-43.2` - `-41.2` | Right far RP. Contains two parameters of type `cms.double`: `sh_min` and `sh_max` - shift range for x alignment | +| Name | Type | Default | Description | +|---------------------|--------------|-------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `reference_dataset` | `cms.string` | `""` | Directory of the file with reference dataset histograms. Should be empty when running the worker for the reference dataset. After that, should be set to the name of the created ROOT file (in the reference config). | +| `rp_L_F` | `cms.PSet` | `-43.` - `-41.` | Left far RP. Contains two parameters of type `cms.double`: `sh_min` and `sh_max` - shift range for x alignment [mm] | +| `rp_L_N` | `cms.PSet` | `-4.2` - `-2.4` | Left near RP. Contains two parameters of type `cms.double`: `sh_min` and `sh_max` - shift range for x alignment [mm] | +| `rp_R_N` | `cms.PSet` | `-3.6` - `-1.8` | Right near RP. Contains two parameters of type `cms.double`: `sh_min` and `sh_max` - shift range for x alignment [mm] | +| `rp_R_F` | `cms.PSet` | `-43.2` - `-41.2` | Right far RP. Contains two parameters of type `cms.double`: `sh_min` and `sh_max` - shift range for x alignment [mm] | ## x_alignment_meth_o -| Name | Type | Default | Description | -|--------------------------------|--------------|----------------|--------------------------------------------------------------------------------------------------------------| -| `rp_L_F` | `cms.PSet` | `47.` - `56.5` | Left far RP. Contains two parameters of type `cms.double`: `x_min` and `x_max` - x range for x alignment | -| `rp_L_N` | `cms.PSet` | `9.` - `18.5` | Left near RP. Contains two parameters of type `cms.double`: `x_min` and `x_max` - x range for x alignment | -| `rp_R_N` | `cms.PSet` | `7.` - `15.` | Right near RP. Contains two parameters of type `cms.double`: `x_min` and `x_max` - x range for x alignment | -| `rp_R_F` | `cms.PSet` | `46.` - `54.` | Right far RP. Contains two parameters of type `cms.double`: `x_min` and `x_max` - x range for x alignment | -| `fit_profile_min_bin_entries` | `cms.uint32` | `5` | Minimal number of entries in each bin in fitProfile method | -| `fit_profile_min_N_reasonable` | `cms.uint32` | `10` | Minimal number of valid bins in fitProfile method | -| `meth_o_graph_min_N` | `cms.uint32` | `5` | Minimal number of points in each of reference and test graph | -| `meth_o_unc_fit_range` | `cms.double` | `0.5` | Fit range for chi-square graph. | +| Name | Type | Default | Description | +|--------------------------------|--------------|----------------|------------------------------------------------------------------------------------------------------------| +| `rp_L_F` | `cms.PSet` | `47.` - `56.5` | Left far RP. Contains two parameters of type `cms.double`: `x_min` and `x_max` - x range for x alignment | +| `rp_L_N` | `cms.PSet` | `9.` - `18.5` | Left near RP. Contains two parameters of type `cms.double`: `x_min` and `x_max` - x range for x alignment | +| `rp_R_N` | `cms.PSet` | `7.` - `15.` | Right near RP. Contains two parameters of type `cms.double`: `x_min` and `x_max` - x range for x alignment | +| `rp_R_F` | `cms.PSet` | `46.` - `54.` | Right far RP. Contains two parameters of type `cms.double`: `x_min` and `x_max` - x range for x alignment | +| `fit_profile_min_bin_entries` | `cms.uint32` | `5` | Minimum number of entries in each bin in fitProfile method | +| `fit_profile_min_N_reasonable` | `cms.uint32` | `10` | Minimum number of valid bins in fitProfile method | +| `meth_o_graph_min_N` | `cms.uint32` | `5` | Minimum number of points in each of reference and test graph | +| `meth_o_unc_fit_range` | `cms.double` | `0.5` | Fit range for chi-square graph. | ## x_alignment_relative -| Name | Type | Default | Description | -|------------------------|--------------|---------------|-----------------------------------------------------------------------------------------------------------------------| -| `rp_L_F` | `cms.PSet` | `0.` - `0.` | Left far RP. Contains two parameters of type `cms.double`: `x_min` and `x_max` - x range for relative x alignment | -| `rp_L_N` | `cms.PSet` | `7.5` - `12.` | Left near RP. Contains two parameters of type `cms.double`: `x_min` and `x_max` - x range for relative x alignment | -| `rp_R_N` | `cms.PSet` | `6.` - `10.` | Right near RP. Contains two parameters of type `cms.double`: `x_min` and `x_max` - x range for relative x alignment | -| `rp_R_F` | `cms.PSet` | `0.` - `0.` | Right far RP. Contains two parameters of type `cms.double`: `x_min` and `x_max` - x range for relative x alignment | -| `near_far_min_entries` | `cms.uint32` | `100` | Minimal number of entries in near_far histograms | +| Name | Type | Default | Description | +|------------------------|--------------|---------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------| +| `rp_L_N` | `cms.PSet` | `7.5` - `12.` | Sector 45 alignment x relative ranges configuration. Contains two parameters of type `cms.double`: `x_min` and `x_max` - x range for relative x alignment | +| `rp_R_N` | `cms.PSet` | `6.` - `10.` | Sector 56 alignment x relative ranges configuration. Contains two parameters of type `cms.double`: `x_min` and `x_max` - x range for relative x alignment | +| `near_far_min_entries` | `cms.uint32` | `100` | Minimum number of entries in n+A97:D100ear_far histograms | ## y_alignment -| Name | Type | Default | Description | -|-------------------------------|--------------|----------------|--------------------------------------------------------------------------------------------------------------| -| `rp_L_F` | `cms.PSet` | `44.5` - `49.` | Left far RP. Contains two parameters of type `cms.double`: `x_min` and `x_max` - x range for y alignment | -| `rp_L_N` | `cms.PSet` | `6.7` - `11.` | Left near RP. Contains two parameters of type `cms.double`: `x_min` and `x_max` - x range for y alignment | -| `rp_R_N` | `cms.PSet` | `5.9` - `10.` | Right near RP. Contains two parameters of type `cms.double`: `x_min` and `x_max` - x range for y alignment | -| `rp_R_F` | `cms.PSet` | `44.5` - `49.` | Right far RP. Contains two parameters of type `cms.double`: `x_min` and `x_max` - x range for y alignment | -| `mode_graph_min_N` | `cms.uint32` | `5` | Minimal number of points in mode graph | -| `mult_sel_proj_y_min_entries` | `cms.uint32` | `300` | Minimal number of entries in y projection of multiplicity selection histograms | +| Name | Type | Default | Description | +|-------------------------------|--------------|----------------|------------------------------------------------------------------------------------------------------------| +| `rp_L_F` | `cms.PSet` | `44.5` - `49.` | Left far RP. Contains two parameters of type `cms.double`: `x_min` and `x_max` - x range for y alignment | +| `rp_L_N` | `cms.PSet` | `6.7` - `11.` | Left near RP. Contains two parameters of type `cms.double`: `x_min` and `x_max` - x range for y alignment | +| `rp_R_N` | `cms.PSet` | `5.9` - `10.` | Right near RP. Contains two parameters of type `cms.double`: `x_min` and `x_max` - x range for y alignment | +| `rp_R_F` | `cms.PSet` | `44.5` - `49.` | Right far RP. Contains two parameters of type `cms.double`: `x_min` and `x_max` - x range for y alignment | +| `mode_graph_min_N` | `cms.uint32` | `5` | Minimum number of points in mode graph | +| `mult_sel_proj_y_min_entries` | `cms.uint32` | `300` | Minimum number of entries in y projection of multiplicity selection histograms | ## binning -| Name | Type | Default | Description | -|------------------|--------------|---------------|-----------------------------------| -| `bin_size_x` | `cms.double` | `142.3314E-3` | X bin size | -| `n_bins_x` | `cms.uint32` | `210` | Number of bins in many histograms | -| `pixel_x_offset` | `cms.double` | `40.` | Pixel x offset | -| `n_bins_y` | `cms.uint32` | `400` | Number of bins in many histograms | -| `y_min` | `cms.double` | `-20.` | Min y for 2D histograms | -| `y_max` | `cms.double` | `20.` | Min y for 2D histograms | \ No newline at end of file +| Name | Type | Default | Description | +|-------------------|--------------|---------------|------------------------------------------| +| `bin_size_x` | `cms.double` | `142.3314E-3` | X bin size | +| `n_bins_x` | `cms.uint32` | `210` | Number of bins in many histograms | +| `pixel_x_offset` | `cms.double` | `40.` | Pixel x offset | +| `n_bins_y` | `cms.uint32` | `400` | Number of bins in many histograms | +| `y_min` | `cms.double` | `-20.` | Min y for 2D histograms | +| `y_max` | `cms.double` | `20.` | Max y for 2D histograms | +| `diffFN_n_bins_x` | `cms.uint32` | `100` | Number of bins in near-far profiles | +| `diffFN_x_min` | `cms.double` | `0.` | X axis min for near-far profiles | +| `diffFN_x_max` | `cms.double` | `20.` | X axis max for near-far profiles | +| `slice_n_bins_x` | `cms.uint32` | `100` | Number of bins in x axis for slice plots | +| `slice_x_min` | `cms.double` | `-10.` | X axis min for slice plots | +| `slice_x_max` | `cms.double` | `10.` | X axis max for slice plots | +| `slice_n_bins_y` | `cms.uint32` | `100` | Number of bins in y axis for slice plots | +| `slice_y_min` | `cms.double` | `-2.` | Y axis min for slice plots | +| `slice_y_max` | `cms.double` | `2.` | Y axis max for slice plots | \ No newline at end of file diff --git a/CalibPPS/AlignmentGlobal/plugins/BuildFile.xml b/CalibPPS/AlignmentGlobal/plugins/BuildFile.xml index 7c6e8f93db3ab..aa1c70dbc725d 100644 --- a/CalibPPS/AlignmentGlobal/plugins/BuildFile.xml +++ b/CalibPPS/AlignmentGlobal/plugins/BuildFile.xml @@ -4,10 +4,12 @@ + + - \ No newline at end of file + diff --git a/CalibPPS/AlignmentGlobal/plugins/PPSAlignmentHarvester.cc b/CalibPPS/AlignmentGlobal/plugins/PPSAlignmentHarvester.cc index 3d86df5cc99ea..d8b52504193be 100644 --- a/CalibPPS/AlignmentGlobal/plugins/PPSAlignmentHarvester.cc +++ b/CalibPPS/AlignmentGlobal/plugins/PPSAlignmentHarvester.cc @@ -1,14 +1,8 @@ /**************************************************************************** - * - * CalibPPS/AlignmentGlobal/plugins/PPSAlignmentHarvester.cc - * - * Description : PPS Alignment DQM harvester - * - * Authors: - * - Jan KaÅ¡par - * - Mateusz Kocot - * - ****************************************************************************/ +* Authors: +* Jan KaÅ¡par (jan.kaspar@gmail.com) +* Mateusz Kocot (mateuszkocot99@gmail.com) +****************************************************************************/ #include "DQMServices/Core/interface/DQMEDHarvester.h" #include "DQMServices/Core/interface/DQMStore.h" @@ -18,13 +12,18 @@ #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/Framework/interface/EventSetup.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" +#include "FWCore/ServiceRegistry/interface/Service.h" + +#include "CondCore/DBOutputService/interface/PoolDBOutputService.h" #include "CondFormats/PPSObjects/interface/CTPPSRPAlignmentCorrectionData.h" #include "CondFormats/PPSObjects/interface/CTPPSRPAlignmentCorrectionsData.h" +#include "CondFormats/DataRecord/interface/CTPPSRPAlignmentCorrectionsDataRcd.h" -#include "CondFormats/PPSObjects/interface/PPSAlignmentConfig.h" -#include "CondFormats/DataRecord/interface/PPSAlignmentConfigRcd.h" +#include "CondFormats/PPSObjects/interface/PPSAlignmentConfiguration.h" +#include "CondFormats/DataRecord/interface/PPSAlignmentConfigurationRcd.h" +#include #include #include #include @@ -49,90 +48,292 @@ class PPSAlignmentHarvester : public DQMEDHarvester { public: - PPSAlignmentHarvester(const edm::ParameterSet &iConfig); + PPSAlignmentHarvester(const edm::ParameterSet& iConfig); + ~PPSAlignmentHarvester() override; + + static void fillDescriptions(edm::ConfigurationDescriptions& descriptions); private: - void dqmEndJob(DQMStore::IBooker &iBooker, DQMStore::IGetter &iGetter) override; - void dqmEndRun(DQMStore::IBooker &iBooker, - DQMStore::IGetter &iGetter, - edm::Run const &iRun, - edm::EventSetup const &iSetup) override; + void dqmEndJob(DQMStore::IBooker& iBooker, DQMStore::IGetter& iGetter) override; + void dqmEndRun(DQMStore::IBooker& iBooker, + DQMStore::IGetter& iGetter, + edm::Run const& iRun, + edm::EventSetup const& iSetup) override; // ------------ x alignment ------------ - static int fitProfile(TProfile *p, + static int fitProfile(TProfile* p, double x_mean, double x_rms, unsigned int fitProfileMinBinEntries, unsigned int fitProfileMinNReasonable, - double &sl, - double &sl_unc); - TGraphErrors *buildGraphFromVector(const std::vector &pv); - TGraphErrors *buildGraphFromMonitorElements(DQMStore::IGetter &iGetter, - const RPConfig &rpd, - const std::vector &mes, - unsigned int fitProfileMinBinEntries, - unsigned int fitProfileMinNReasonable); - void doMatch(DQMStore::IBooker &iBooker, - const PPSAlignmentConfig &cfg, - const RPConfig &rpd, - TGraphErrors *g_ref, - TGraphErrors *g_test, - const SelectionRange &range_ref, + double& sl, + double& sl_unc); + std::unique_ptr buildGraphFromVector(const std::vector& pv); + std::unique_ptr buildGraphFromMonitorElements(DQMStore::IGetter& iGetter, + const PPSAlignmentConfiguration::RPConfig& rpc, + const std::vector& mes, + unsigned int fitProfileMinBinEntries, + unsigned int fitProfileMinNReasonable); + void doMatch(DQMStore::IBooker& iBooker, + const PPSAlignmentConfiguration& cfg, + const PPSAlignmentConfiguration::RPConfig& rpc, + TGraphErrors* g_ref, + TGraphErrors* g_test, + const PPSAlignmentConfiguration::SelectionRange& range_ref, double sh_min, double sh_max, - double &sh_best, - double &sh_best_unc); + double& sh_best, + double& sh_best_unc); - void xAlignment(DQMStore::IBooker &iBooker, - DQMStore::IGetter &iGetter, - const PPSAlignmentConfig &cfg, - const PPSAlignmentConfig &cfg_ref, + void xAlignment(DQMStore::IBooker& iBooker, + DQMStore::IGetter& iGetter, + const PPSAlignmentConfiguration& cfg, + const PPSAlignmentConfiguration& cfg_ref, int seqPos); - std::map sh_x_map; + std::map sh_x_map_; // ------------ x alignment relative ------------ - void xAlignmentRelative(DQMStore::IBooker &iBooker, - DQMStore::IGetter &iGetter, - const PPSAlignmentConfig &cfg, + void xAlignmentRelative(DQMStore::IBooker& iBooker, + DQMStore::IGetter& iGetter, + const PPSAlignmentConfiguration& cfg, int seqPos); // ------------ y alignment ------------ - static double findMax(TF1 *ff_fit); - TGraphErrors *buildModeGraph(DQMStore::IBooker &iBooker, - MonitorElement *h2_y_vs_x, - const PPSAlignmentConfig &cfg, - const RPConfig &rpd); - - void yAlignment(DQMStore::IBooker &iBooker, DQMStore::IGetter &iGetter, const PPSAlignmentConfig &cfg, int seqPos); + static double findMax(TF1* ff_fit); + TH1D* buildModeGraph(DQMStore::IBooker& iBooker, + MonitorElement* h2_y_vs_x, + const PPSAlignmentConfiguration& cfg, + const PPSAlignmentConfiguration::RPConfig& rpc); + + void yAlignment(DQMStore::IBooker& iBooker, + DQMStore::IGetter& iGetter, + const PPSAlignmentConfiguration& cfg, + int seqPos); // ------------ other member data and methods ------------ - static TH1D *getTH1DFromTGraphErrors(TGraphErrors *graph, - std::string title = "", - std::string labels = "", - int n = -1, - double binWidth = -1., - double min = -1.); - - edm::ESGetToken esTokenTest_; - edm::ESGetToken esTokenReference_; - + static void writeCutPlot(TH2D* h, double a, double c, double si, double n_si, const std::string& label); + static std::unique_ptr getTH1DFromTGraphErrors(TGraphErrors* graph, + std::string title = "", + std::string labels = "", + int n = -1, + double binWidth = -1., + double min = -1.); + + edm::ESGetToken esTokenTest_; + edm::ESGetToken esTokenReference_; + + // variables from parameters const std::string folder_; + const std::vector sequence_; + bool overwriteShX_; + const bool writeSQLiteResults_; + const bool xAliRelFinalSlopeFixed_; + const bool yAliFinalSlopeFixed_; const bool debug_; - TFile *debugFile_; - std::ofstream resultsFile_; + + // other class variables + std::unique_ptr debugFile_; + std::ofstream textResultsFile_; + + CTPPSRPAlignmentCorrectionsData xAliResults_; + + CTPPSRPAlignmentCorrectionsData xAliRelResults_; + CTPPSRPAlignmentCorrectionsData xAliRelResultsSlopeFixed_; + + CTPPSRPAlignmentCorrectionsData yAliResults_; + CTPPSRPAlignmentCorrectionsData yAliResultsSlopeFixed_; }; +// -------------------------------- DQMEDHarvester methods -------------------------------- + +PPSAlignmentHarvester::PPSAlignmentHarvester(const edm::ParameterSet& iConfig) + : esTokenTest_(esConsumes( + edm::ESInputTag("", ""))), + esTokenReference_(esConsumes( + edm::ESInputTag("", "reference"))), + folder_(iConfig.getParameter("folder")), + sequence_(iConfig.getParameter>("sequence")), + overwriteShX_(iConfig.getParameter("overwrite_sh_x")), + writeSQLiteResults_(iConfig.getParameter("write_sqlite_results")), + xAliRelFinalSlopeFixed_(iConfig.getParameter("x_ali_rel_final_slope_fixed")), + yAliFinalSlopeFixed_(iConfig.getParameter("y_ali_final_slope_fixed")), + debug_(iConfig.getParameter("debug")) { + auto textResultsPath = iConfig.getParameter("text_results_path"); + if (!textResultsPath.empty()) { + textResultsFile_.open(textResultsPath, std::ios::out | std::ios::trunc); + } + if (debug_) { + debugFile_ = std::make_unique("debug_harvester.root", "recreate"); + } + + edm::LogInfo("PPS").log([&](auto& li) { + li << "[harvester] parameters:\n"; + li << "* folder: " << folder_ << "\n"; + li << "* sequence:\n"; + for (unsigned int i = 0; i < sequence_.size(); i++) { + li << " " << i + 1 << ": " << sequence_[i] << "\n"; + } + li << "* overwrite_sh_x: " << std::boolalpha << overwriteShX_ << "\n"; + li << "* text_results_path: " << textResultsPath << "\n"; + li << "* write_sqlite_results: " << std::boolalpha << writeSQLiteResults_ << "\n"; + li << "* x_ali_rel_final_slope_fixed: " << std::boolalpha << xAliRelFinalSlopeFixed_ << "\n"; + li << "* y_ali_final_slope_fixed: " << std::boolalpha << yAliFinalSlopeFixed_ << "\n"; + li << "* debug: " << std::boolalpha << debug_; + }); +} + +PPSAlignmentHarvester::~PPSAlignmentHarvester() { + if (textResultsFile_.is_open()) { + textResultsFile_.close(); + } +} + +void PPSAlignmentHarvester::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { + edm::ParameterSetDescription desc; + + desc.add("folder", "AlCaReco/PPSAlignment"); + desc.add>("sequence", {"x_alignment", "x_alignment_relative", "y_alignment"}); + desc.add("overwrite_sh_x", true); + desc.add("text_results_path", "./alignment_results.txt"); + desc.add("write_sqlite_results", false); + desc.add("x_ali_rel_final_slope_fixed", true); + desc.add("y_ali_final_slope_fixed", true); + desc.add("debug", false); + + descriptions.addWithDefaultLabel(desc); +} + +void PPSAlignmentHarvester::dqmEndJob(DQMStore::IBooker& iBooker, DQMStore::IGetter& iGetter) {} + +void PPSAlignmentHarvester::dqmEndRun(DQMStore::IBooker& iBooker, + DQMStore::IGetter& iGetter, + edm::Run const& iRun, + edm::EventSetup const& iSetup) { + const auto& cfg = iSetup.getData(esTokenTest_); + + const auto& cfg_ref = iSetup.getData(esTokenReference_); + + // setting default sh_x values from config + for (const auto& sc : {cfg.sectorConfig45(), cfg.sectorConfig56()}) { + for (const auto& rpc : {sc.rp_N_, sc.rp_F_}) { + sh_x_map_[rpc.id_] = rpc.sh_x_; + } + } + edm::LogInfo("PPS").log([&](auto& li) { + li << "[harvester] Setting sh_x from config of:\n"; + for (const auto& sc : {cfg.sectorConfig45(), cfg.sectorConfig56()}) { + for (const auto& rpc : {sc.rp_N_, sc.rp_F_}) { + li << " " << rpc.name_ << " to " << std::fixed << std::setprecision(3) << rpc.sh_x_; + if (rpc.name_ != "R_2_F") + li << "\n"; + } + } + }); + + bool doXAli = false, doXAliRel = false, doYAli = false; + for (unsigned int i = 0; i < sequence_.size(); i++) { + if (sequence_[i] == "x_alignment") { + xAlignment(iBooker, iGetter, cfg, cfg_ref, i); + doXAli = true; + } else if (sequence_[i] == "x_alignment_relative") { + xAlignmentRelative(iBooker, iGetter, cfg, i); + doXAliRel = true; + } else if (sequence_[i] == "y_alignment") { + yAlignment(iBooker, iGetter, cfg, i); + doYAli = true; + } else + edm::LogError("PPS") << "[harvester] " << sequence_[i] << " is a wrong method name."; + } + + // merge results from all the specified methods + CTPPSRPAlignmentCorrectionsData finalResults; + if (doXAli) { // x alignment + finalResults.addCorrections(xAliResults_); + if (doXAliRel) { // merge with x alignment relative + for (const auto& sc : {cfg.sectorConfig45(), cfg.sectorConfig56()}) { + // extract shifts + double d_x_N = xAliResults_.getRPCorrection(sc.rp_N_.id_).getShX(); + double d_x_F = xAliResults_.getRPCorrection(sc.rp_F_.id_).getShX(); + + double d_x_rel_N, d_x_rel_F; + if (xAliRelFinalSlopeFixed_) { + d_x_rel_N = xAliRelResultsSlopeFixed_.getRPCorrection(sc.rp_N_.id_).getShX(); + d_x_rel_F = xAliRelResultsSlopeFixed_.getRPCorrection(sc.rp_F_.id_).getShX(); + } else { + d_x_rel_N = xAliRelResults_.getRPCorrection(sc.rp_N_.id_).getShX(); + d_x_rel_F = xAliRelResults_.getRPCorrection(sc.rp_F_.id_).getShX(); + } + + // merge the results + double b = d_x_rel_N - d_x_rel_F; + double xCorrRel = b + d_x_F - d_x_N; + + CTPPSRPAlignmentCorrectionData corrRelN(xCorrRel / 2., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.); + finalResults.addRPCorrection(sc.rp_N_.id_, corrRelN); + CTPPSRPAlignmentCorrectionData corrRelF(-xCorrRel / 2., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.); + finalResults.addRPCorrection(sc.rp_F_.id_, corrRelF); + } + } + } + if (doYAli) { // y alignment + if (yAliFinalSlopeFixed_) { + finalResults.addCorrections(yAliResultsSlopeFixed_); + } else { + finalResults.addCorrections(yAliResults_); + } + } + + // print the text results + edm::LogInfo("PPS") << "final merged results:\n" << finalResults; + + if (textResultsFile_.is_open()) { + textResultsFile_ << "final merged results:\n" << finalResults; + } + + // if requested, store the results in a DB object + if (writeSQLiteResults_) { + edm::Service poolDbService; + if (poolDbService.isAvailable()) { + poolDbService->writeOneIOV(finalResults, poolDbService->currentTime(), "CTPPSRPAlignmentCorrectionsDataRcd"); + } else { + edm::LogWarning("PPS") << "Could not store the results in a DB object. PoolDBService not available."; + } + } + + // if debug_, save nice-looking cut plots with the worker data in the debug ROOT file + if (debug_) { + TDirectory* cutsDir = debugFile_->mkdir("cuts"); + for (const auto& sc : {cfg.sectorConfig45(), cfg.sectorConfig56()}) { + TDirectory* sectorDir = cutsDir->mkdir(sc.name_.c_str()); + + gDirectory = sectorDir->mkdir("cut_h"); + auto* h2_cut_h_bef_monitor = iGetter.get(folder_ + "/worker/" + sc.name_ + "/cuts/cut_h/h2_cut_h_bef"); + auto* h2_cut_h_aft_monitor = iGetter.get(folder_ + "/worker/" + sc.name_ + "/cuts/cut_h/h2_cut_h_aft"); + writeCutPlot( + h2_cut_h_bef_monitor->getTH2D(), sc.cut_h_a_, sc.cut_h_c_, cfg.n_si(), sc.cut_h_si_, "canvas_before"); + writeCutPlot(h2_cut_h_aft_monitor->getTH2D(), sc.cut_h_a_, sc.cut_h_c_, cfg.n_si(), sc.cut_h_si_, "canvas_after"); + + gDirectory = sectorDir->mkdir("cut_v"); + auto* h2_cut_v_bef_monitor = iGetter.get(folder_ + "/worker/" + sc.name_ + "/cuts/cut_v/h2_cut_v_bef"); + auto* h2_cut_v_aft_monitor = iGetter.get(folder_ + "/worker/" + sc.name_ + "/cuts/cut_v/h2_cut_v_aft"); + writeCutPlot( + h2_cut_v_bef_monitor->getTH2D(), sc.cut_v_a_, sc.cut_v_c_, cfg.n_si(), sc.cut_v_si_, "canvas_before"); + writeCutPlot(h2_cut_v_aft_monitor->getTH2D(), sc.cut_v_a_, sc.cut_v_c_, cfg.n_si(), sc.cut_v_si_, "canvas_after"); + } + } +} + // -------------------------------- x alignment methods -------------------------------- -// Fits a linear function to a TProfile (similar method in PPSAlignmentConfigESSource). -int PPSAlignmentHarvester::fitProfile(TProfile *p, +// Fits a linear function to a TProfile (similar method in PPSAlignmentConfigurationESSource). +int PPSAlignmentHarvester::fitProfile(TProfile* p, double x_mean, double x_rms, unsigned int fitProfileMinBinEntries, unsigned int fitProfileMinNReasonable, - double &sl, - double &sl_unc) { + double& sl, + double& sl_unc) { unsigned int n_reasonable = 0; for (int bi = 1; bi <= p->GetNbinsX(); bi++) { if (p->GetBinEntries(bi) < fitProfileMinBinEntries) { @@ -146,12 +347,12 @@ int PPSAlignmentHarvester::fitProfile(TProfile *p, if (n_reasonable < fitProfileMinNReasonable) return 1; - double xMin = x_mean - x_rms, xMax = x_mean + x_rms; + double x_min = x_mean - x_rms, x_max = x_mean + x_rms; - TF1 *ff_pol1 = new TF1("ff_pol1", "[0] + [1]*x"); + auto ff_pol1 = std::make_unique("ff_pol1", "[0] + [1]*x"); ff_pol1->SetParameter(0., 0.); - p->Fit(ff_pol1, "Q", "", xMin, xMax); + p->Fit(ff_pol1.get(), "Q", "", x_min, x_max); sl = ff_pol1->GetParameter(1); sl_unc = ff_pol1->GetParError(1); @@ -160,11 +361,12 @@ int PPSAlignmentHarvester::fitProfile(TProfile *p, } // Builds graph from a vector of points (with errors). -TGraphErrors *PPSAlignmentHarvester::buildGraphFromVector(const std::vector &pv) { - TGraphErrors *g = new TGraphErrors(); +std::unique_ptr PPSAlignmentHarvester::buildGraphFromVector( + const std::vector& pv) { + auto g = std::make_unique(); for (unsigned int i = 0; i < pv.size(); i++) { - const auto &p = pv[i]; + const auto& p = pv[i]; g->SetPoint(i, p.x_, p.y_); g->SetPointError(i, p.ex_, p.ey_); } @@ -174,14 +376,15 @@ TGraphErrors *PPSAlignmentHarvester::buildGraphFromVector(const std::vector &mes, - unsigned int fitProfileMinBinEntries, - unsigned int fitProfileMinNReasonable) { - TGraphErrors *g = new TGraphErrors(); - - for (auto *me : mes) { +std::unique_ptr PPSAlignmentHarvester::buildGraphFromMonitorElements( + DQMStore::IGetter& iGetter, + const PPSAlignmentConfiguration::RPConfig& rpc, + const std::vector& mes, + unsigned int fitProfileMinBinEntries, + unsigned int fitProfileMinNReasonable) { + auto g = std::make_unique(); + + for (auto* me : mes) { if (me->getName() == "h_y") // find "h_y" { // retrieve parent directory @@ -189,24 +392,24 @@ TGraphErrors *PPSAlignmentHarvester::buildGraphFromMonitorElements(DQMStore::IGe size_t parentPos = parentPath.substr(0, parentPath.size() - 1).find_last_of('/') + 1; std::string parentName = parentPath.substr(parentPos); size_t d = parentName.find('-'); - const double xMin = std::stod(parentName.substr(0, d)); - const double xMax = std::stod(parentName.substr(d + 1)); + const double x_min = std::stod(parentName.substr(0, d)); + const double x_max = std::stod(parentName.substr(d + 1)); - TH1D *h_y = me->getTH1D(); + TH1D* h_y = me->getTH1D(); // collect "p_y_diffFN_vs_y" corresponding to found "h_y" - auto *p_y_diffFN_vs_y_monitor = iGetter.get(parentPath + "p_y_diffFN_vs_y"); + auto* p_y_diffFN_vs_y_monitor = iGetter.get(parentPath + "p_y_diffFN_vs_y"); if (p_y_diffFN_vs_y_monitor == nullptr) { edm::LogWarning("PPS") << "[x_alignment] could not find p_y_diffFN_vs_y in: " << parentPath; continue; } - TProfile *p_y_diffFN_vs_y = p_y_diffFN_vs_y_monitor->getTProfile(); + TProfile* p_y_diffFN_vs_y = p_y_diffFN_vs_y_monitor->getTProfile(); double y_cen = h_y->GetMean(); double y_width = h_y->GetRMS(); - y_cen += rpd.y_cen_add_; - y_width *= rpd.y_width_mult_; + y_cen += rpc.y_cen_add_; + y_width *= rpc.y_width_mult_; double sl = 0., sl_unc = 0.; int fr = @@ -218,8 +421,8 @@ TGraphErrors *PPSAlignmentHarvester::buildGraphFromMonitorElements(DQMStore::IGe p_y_diffFN_vs_y->Write(parentName.c_str()); int idx = g->GetN(); - g->SetPoint(idx, (xMax + xMin) / 2., sl); - g->SetPointError(idx, (xMax - xMin) / 2., sl_unc); + g->SetPoint(idx, (x_max + x_min) / 2., sl); + g->SetPointError(idx, (x_max - x_min) / 2., sl_unc); } } g->Sort(); @@ -228,17 +431,17 @@ TGraphErrors *PPSAlignmentHarvester::buildGraphFromMonitorElements(DQMStore::IGe } // Matches reference data with test data. -void PPSAlignmentHarvester::doMatch(DQMStore::IBooker &iBooker, - const PPSAlignmentConfig &cfg, - const RPConfig &rpd, - TGraphErrors *g_ref, - TGraphErrors *g_test, - const SelectionRange &range_ref, +void PPSAlignmentHarvester::doMatch(DQMStore::IBooker& iBooker, + const PPSAlignmentConfiguration& cfg, + const PPSAlignmentConfiguration::RPConfig& rpc, + TGraphErrors* g_ref, + TGraphErrors* g_test, + const PPSAlignmentConfiguration::SelectionRange& range_ref, double sh_min, double sh_max, - double &sh_best, - double &sh_best_unc) { - const auto range_test = cfg.alignment_x_meth_o_ranges().at(rpd.id_); + double& sh_best, + double& sh_best_unc) { + const auto range_test = cfg.alignment_x_meth_o_ranges().at(rpc.id_); // print config edm::LogInfo("PPS") << std::fixed << std::setprecision(3) << "[x_alignment] " @@ -246,16 +449,16 @@ void PPSAlignmentHarvester::doMatch(DQMStore::IBooker &iBooker, << "test: x_min = " << range_test.x_min_ << ", x_max = " << range_test.x_max_; // make spline from g_ref - TSpline3 *s_ref = new TSpline3("s_ref", g_ref->GetX(), g_ref->GetY(), g_ref->GetN()); + auto s_ref = std::make_unique("s_ref", g_ref->GetX(), g_ref->GetY(), g_ref->GetN()); // book match-quality graphs - TGraph *g_n_points = new TGraph(); + auto g_n_points = std::make_unique(); g_n_points->SetName("g_n_points"); g_n_points->SetTitle(";sh;N"); - TGraph *g_chi_sq = new TGraph(); + auto g_chi_sq = std::make_unique(); g_chi_sq->SetName("g_chi_sq"); g_chi_sq->SetTitle(";sh;S2"); - TGraph *g_chi_sq_norm = new TGraph(); + auto g_chi_sq_norm = std::make_unique(); g_chi_sq_norm->SetName("g_chi_sq_norm"); g_chi_sq_norm->SetTitle(";sh;S2 / N"); @@ -318,26 +521,25 @@ void PPSAlignmentHarvester::doMatch(DQMStore::IBooker &iBooker, g_chi_sq_norm->SetPoint(idx, sh, S2_norm); } - TF1 *ff_pol2 = new TF1("ff_pol2", "[0] + [1]*x + [2]*x*x"); + auto ff_pol2 = std::make_unique("ff_pol2", "[0] + [1]*x + [2]*x*x"); // determine uncertainty double fit_range = cfg.methOUncFitRange(); - g_chi_sq->Fit(ff_pol2, "Q", "", sh_best - fit_range, sh_best + fit_range); + g_chi_sq->Fit(ff_pol2.get(), "Q", "", sh_best - fit_range, sh_best + fit_range); sh_best_unc = 1. / sqrt(ff_pol2->GetParameter(2)); // print results edm::LogInfo("PPS") << std::fixed << std::setprecision(3) << "[x_alignment] " << "sh_best = (" << sh_best << " +- " << sh_best_unc << ") mm"; - TGraphErrors *g_test_shifted = new TGraphErrors(*g_test); + auto g_test_shifted = std::make_unique(*g_test); for (int i = 0; i < g_test_shifted->GetN(); ++i) { g_test_shifted->GetX()[i] += sh_best; } - iBooker.book1DD( - "h_test_shifted", - getTH1DFromTGraphErrors( - g_test_shifted, "test_shifted", ";x (mm);S", rpd.x_slice_n_, rpd.x_slice_w_, rpd.x_slice_min_ + sh_best)); + std::unique_ptr histPtr = getTH1DFromTGraphErrors( + g_test_shifted.get(), "test_shifted", ";x (mm);S", rpc.x_slice_n_, rpc.x_slice_w_, rpc.x_slice_min_ + sh_best); + iBooker.book1DD("h_test_shifted", histPtr.get()); if (debug_) { // save graphs @@ -348,7 +550,7 @@ void PPSAlignmentHarvester::doMatch(DQMStore::IBooker &iBooker, g_test_shifted->Write("g_test_shifted"); // save results - TGraph *g_results = new TGraph(); + auto g_results = std::make_unique(); g_results->SetName("g_results"); g_results->SetPoint(0, sh_best, sh_best_unc); g_results->SetPoint(1, range_ref.x_min_, range_ref.x_max_); @@ -356,7 +558,7 @@ void PPSAlignmentHarvester::doMatch(DQMStore::IBooker &iBooker, g_results->Write(); // save debug canvas - TCanvas *c_cmp = new TCanvas("c_cmp"); + auto c_cmp = std::make_unique("c_cmp"); g_ref->SetLineColor(1); g_ref->SetName("g_ref"); g_ref->Draw("apl"); @@ -370,72 +572,68 @@ void PPSAlignmentHarvester::doMatch(DQMStore::IBooker &iBooker, g_test_shifted->Draw("pl"); c_cmp->Write(); - - delete c_cmp; } - - // clean up - delete s_ref; } // method o -void PPSAlignmentHarvester::xAlignment(DQMStore::IBooker &iBooker, - DQMStore::IGetter &iGetter, - const PPSAlignmentConfig &cfg, - const PPSAlignmentConfig &cfg_ref, +void PPSAlignmentHarvester::xAlignment(DQMStore::IBooker& iBooker, + DQMStore::IGetter& iGetter, + const PPSAlignmentConfiguration& cfg, + const PPSAlignmentConfiguration& cfg_ref, int seqPos) { - TDirectory *xAliDir = nullptr; + TDirectory* xAliDir = nullptr; if (debug_) xAliDir = debugFile_->mkdir((std::to_string(seqPos + 1) + ": x alignment").c_str()); - // prepare results - CTPPSRPAlignmentCorrectionsData results; + for (const auto& scPair : {std::make_pair(cfg.sectorConfig45(), cfg_ref.sectorConfig45()), + std::make_pair(cfg.sectorConfig56(), cfg_ref.sectorConfig56())}) { + const auto& sc = scPair.first; + const auto& sc_ref = scPair.second; - for (const auto &sdp : {std::make_pair(cfg.sectorConfig45(), cfg_ref.sectorConfig45()), - std::make_pair(cfg.sectorConfig56(), cfg_ref.sectorConfig56())}) { - const auto &sd = sdp.first; - for (const auto &rpdp : {std::make_pair(sd.rp_F_, sdp.second.rp_F_), std::make_pair(sd.rp_N_, sdp.second.rp_N_)}) { - const auto &rpd = rpdp.first; + for (const auto& rpcPair : {std::make_pair(sc.rp_F_, sc_ref.rp_F_), std::make_pair(sc.rp_N_, sc_ref.rp_N_)}) { + const auto& rpc = rpcPair.first; + const auto& rpc_ref = rpcPair.second; - auto mes_test = iGetter.getAllContents(folder_ + "/worker/" + sd.name_ + "/near_far/x slices, " + rpd.position_); + auto mes_test = iGetter.getAllContents(folder_ + "/worker/" + sc.name_ + "/near_far/x slices, " + rpc.position_); if (mes_test.empty()) { - edm::LogWarning("PPS") << "[x_alignment] " << rpd.name_ << ": could not load mes_test"; + edm::LogWarning("PPS") << "[x_alignment] " << rpc.name_ << ": could not load mes_test"; continue; } - TDirectory *rpDir = nullptr; + TDirectory* rpDir = nullptr; if (debug_) - rpDir = xAliDir->mkdir(rpd.name_.c_str()); + rpDir = xAliDir->mkdir(rpc.name_.c_str()); - auto vec_ref = cfg_ref.matchingReferencePoints().at(rpd.id_); + auto vec_ref = cfg_ref.matchingReferencePoints().at(rpc.id_); if (vec_ref.empty()) { - edm::LogInfo("PPS") << "[x_alignment] " << rpd.name_ << ": reference points vector is empty"; + edm::LogInfo("PPS") << "[x_alignment] " << rpc.name_ << ": reference points vector is empty"; continue; } - TGraphErrors *g_ref = buildGraphFromVector(vec_ref); + std::unique_ptr g_ref = buildGraphFromVector(vec_ref); if (debug_) gDirectory = rpDir->mkdir("fits_test"); - TGraphErrors *g_test = buildGraphFromMonitorElements( - iGetter, rpd, mes_test, cfg.fitProfileMinBinEntries(), cfg.fitProfileMinNReasonable()); + std::unique_ptr g_test = buildGraphFromMonitorElements( + iGetter, rpc, mes_test, cfg.fitProfileMinBinEntries(), cfg.fitProfileMinNReasonable()); // require minimal number of points if (g_ref->GetN() < (int)cfg.methOGraphMinN() || g_test->GetN() < (int)cfg.methOGraphMinN()) { - edm::LogWarning("PPS") << "[x_alignment] " << rpd.name_ << ": insufficient data, skipping (g_ref " + edm::LogWarning("PPS") << "[x_alignment] " << rpc.name_ << ": insufficient data, skipping (g_ref " << g_ref->GetN() << "/" << cfg.methOGraphMinN() << ", g_test " << g_test->GetN() << "/" << cfg.methOGraphMinN() << ")"; continue; } - iBooker.setCurrentFolder(folder_ + "/harvester/x alignment/" + rpd.name_); - iBooker.book1DD( - "h_ref", - getTH1DFromTGraphErrors( - g_ref, "ref", ";x (mm);S", rpdp.second.x_slice_n_, rpdp.second.x_slice_w_, rpdp.second.x_slice_min_)); - iBooker.book1DD( - "h_test", - getTH1DFromTGraphErrors(g_test, "test", ";x (mm);S", rpd.x_slice_n_, rpd.x_slice_w_, rpd.x_slice_min_)); + iBooker.setCurrentFolder(folder_ + "/harvester/x alignment/" + rpc.name_); + + std::unique_ptr histPtr = getTH1DFromTGraphErrors( + g_ref.get(), "ref", ";x (mm);S", rpc_ref.x_slice_n_, rpc_ref.x_slice_w_, rpc_ref.x_slice_min_); + iBooker.book1DD("h_ref", histPtr.get()); + + histPtr = + getTH1DFromTGraphErrors(g_test.get(), "test", ";x (mm);S", rpc.x_slice_n_, rpc.x_slice_w_, rpc.x_slice_min_); + iBooker.book1DD("h_test", histPtr.get()); if (debug_) { gDirectory = rpDir; @@ -445,116 +643,124 @@ void PPSAlignmentHarvester::xAlignment(DQMStore::IBooker &iBooker, g_test->Write("g_test"); } - const auto &shiftRange = cfg_ref.matchingShiftRanges().at(rpd.id_); + const auto& shiftRange = cfg.matchingShiftRanges().at(rpc.id_); double sh = 0., sh_unc = 0.; + + // matching doMatch(iBooker, cfg, - rpd, - g_ref, - g_test, - cfg_ref.alignment_x_meth_o_ranges().at(rpd.id_), + rpc, + g_ref.get(), + g_test.get(), + cfg_ref.alignment_x_meth_o_ranges().at(rpc.id_), shiftRange.x_min_, shiftRange.x_max_, sh, sh_unc); + // save the results CTPPSRPAlignmentCorrectionData rpResult(sh, sh_unc, 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.); - results.setRPCorrection(rpd.id_, rpResult); + xAliResults_.setRPCorrection(rpc.id_, rpResult); edm::LogInfo("PPS") << std::fixed << std::setprecision(3) << "[x_alignment] " - << "Setting sh_x of " << rpd.name_ << " to " << sh; - sh_x_map[rpd.id_] = sh; + << "Setting sh_x of " << rpc.name_ << " to " << sh; + + // update the shift + if (overwriteShX_) { + sh_x_map_[rpc.id_] = sh; + } } } - edm::LogInfo("PPS") << seqPos + 1 << ": x_alignment:\n" << results; + edm::LogInfo("PPS") << seqPos + 1 << ": x_alignment:\n" << xAliResults_; - if (resultsFile_.is_open()) - resultsFile_ << seqPos + 1 << ": x_alignment:\n" << results << "\n\n"; + if (textResultsFile_.is_open()) + textResultsFile_ << seqPos + 1 << ": x_alignment:\n" << xAliResults_ << "\n\n"; } // -------------------------------- x alignment relative methods -------------------------------- -void PPSAlignmentHarvester::xAlignmentRelative(DQMStore::IBooker &iBooker, - DQMStore::IGetter &iGetter, - const PPSAlignmentConfig &cfg, +void PPSAlignmentHarvester::xAlignmentRelative(DQMStore::IBooker& iBooker, + DQMStore::IGetter& iGetter, + const PPSAlignmentConfiguration& cfg, int seqPos) { - TDirectory *xAliRelDir = nullptr; + TDirectory* xAliRelDir = nullptr; if (debug_) xAliRelDir = debugFile_->mkdir((std::to_string(seqPos + 1) + ": x_alignment_relative").c_str()); - // prepare results - CTPPSRPAlignmentCorrectionsData results; - CTPPSRPAlignmentCorrectionsData results_sl_fix; - - TF1 *ff = new TF1("ff", "[0] + [1]*(x - [2])"); - TF1 *ff_sl_fix = new TF1("ff_sl_fix", "[0] + [1]*(x - [2])"); + auto ff = std::make_unique("ff", "[0] + [1]*(x - [2])"); + auto ff_sl_fix = std::make_unique("ff_sl_fix", "[0] + [1]*(x - [2])"); // processing - for (const auto &sd : {cfg.sectorConfig45(), cfg.sectorConfig56()}) { - TDirectory *sectorDir = nullptr; + for (const auto& sc : {cfg.sectorConfig45(), cfg.sectorConfig56()}) { + TDirectory* sectorDir = nullptr; if (debug_) { - sectorDir = xAliRelDir->mkdir(sd.name_.c_str()); + sectorDir = xAliRelDir->mkdir(sc.name_.c_str()); gDirectory = sectorDir; } - auto *p_x_diffFN_vs_x_N_monitor = iGetter.get(folder_ + "/worker/" + sd.name_ + "/near_far/p_x_diffFN_vs_x_N"); + auto* p_x_diffFN_vs_x_N_monitor = iGetter.get(folder_ + "/worker/" + sc.name_ + "/near_far/p_x_diffFN_vs_x_N"); if (p_x_diffFN_vs_x_N_monitor == nullptr) { - edm::LogWarning("PPS") << "[x_alignment_relative] " << sd.name_ << ": cannot load data, skipping"; + edm::LogWarning("PPS") << "[x_alignment_relative] " << sc.name_ << ": cannot load data, skipping"; continue; } - TProfile *p_x_diffFN_vs_x_N = p_x_diffFN_vs_x_N_monitor->getTProfile(); + TProfile* p_x_diffFN_vs_x_N = p_x_diffFN_vs_x_N_monitor->getTProfile(); if (p_x_diffFN_vs_x_N->GetEntries() < cfg.nearFarMinEntries()) { - edm::LogWarning("PPS") << "[x_alignment_relative] " << sd.name_ << ": insufficient data, skipping (near_far " + edm::LogWarning("PPS") << "[x_alignment_relative] " << sc.name_ << ": insufficient data, skipping (near_far " << p_x_diffFN_vs_x_N->GetEntries() << "/" << cfg.nearFarMinEntries() << ")"; continue; } - const double xMin = cfg.alignment_x_relative_ranges().at(sd.rp_N_.id_).x_min_; - const double xMax = cfg.alignment_x_relative_ranges().at(sd.rp_N_.id_).x_max_; + const double x_min = cfg.alignment_x_relative_ranges().at(sc.rp_N_.id_).x_min_; + const double x_max = cfg.alignment_x_relative_ranges().at(sc.rp_N_.id_).x_max_; - const double sh_x_N = sh_x_map[sd.rp_N_.id_]; - double slope = sd.slope_; + const double sh_x_N = sh_x_map_[sc.rp_N_.id_]; + double slope = sc.slope_; ff->SetParameters(0., slope, 0.); ff->FixParameter(2, -sh_x_N); ff->SetLineColor(2); - p_x_diffFN_vs_x_N->Fit(ff, "Q", "", xMin, xMax); + p_x_diffFN_vs_x_N->Fit(ff.get(), "Q", "", x_min, x_max); const double a = ff->GetParameter(1), a_unc = ff->GetParError(1); const double b = ff->GetParameter(0), b_unc = ff->GetParError(0); - edm::LogInfo("PPS") << "[x_alignment_relative] " << sd.name_ << ":\n" - << std::fixed << std::setprecision(3) << " x_min = " << xMin << ", x_max = " << xMax << "\n" + edm::LogInfo("PPS") << "[x_alignment_relative] " << sc.name_ << ":\n" + << std::fixed << std::setprecision(3) << " x_min = " << x_min << ", x_max = " << x_max + << "\n" << " sh_x_N = " << sh_x_N << ", slope (fix) = " << slope << ", slope (fitted) = " << a; CTPPSRPAlignmentCorrectionData rpResult_N(+b / 2., b_unc / 2., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.); - results.setRPCorrection(sd.rp_N_.id_, rpResult_N); + xAliRelResults_.setRPCorrection(sc.rp_N_.id_, rpResult_N); CTPPSRPAlignmentCorrectionData rpResult_F(-b / 2., b_unc / 2., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.); - results.setRPCorrection(sd.rp_F_.id_, rpResult_F); + xAliRelResults_.setRPCorrection(sc.rp_F_.id_, rpResult_F); ff_sl_fix->SetParameters(0., slope, 0.); ff_sl_fix->FixParameter(1, slope); ff_sl_fix->FixParameter(2, -sh_x_N); ff_sl_fix->SetLineColor(4); - p_x_diffFN_vs_x_N->Fit(ff_sl_fix, "Q+", "", xMin, xMax); + p_x_diffFN_vs_x_N->Fit(ff_sl_fix.get(), "Q+", "", x_min, x_max); const double b_fs = ff_sl_fix->GetParameter(0), b_fs_unc = ff_sl_fix->GetParError(0); CTPPSRPAlignmentCorrectionData rpResult_sl_fix_N(+b_fs / 2., b_fs_unc / 2., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.); - results_sl_fix.setRPCorrection(sd.rp_N_.id_, rpResult_sl_fix_N); + xAliRelResultsSlopeFixed_.setRPCorrection(sc.rp_N_.id_, rpResult_sl_fix_N); CTPPSRPAlignmentCorrectionData rpResult_sl_fix_F(-b_fs / 2., b_fs_unc / 2., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.); - results_sl_fix.setRPCorrection(sd.rp_F_.id_, rpResult_sl_fix_F); + xAliRelResultsSlopeFixed_.setRPCorrection(sc.rp_F_.id_, rpResult_sl_fix_F); edm::LogInfo("PPS") << "[x_alignment_relative] " << std::fixed << std::setprecision(3) << "ff: " << ff->GetParameter(0) << " + " << ff->GetParameter(1) << " * (x - " << ff->GetParameter(2) << "), ff_sl_fix: " << ff_sl_fix->GetParameter(0) << " + " << ff_sl_fix->GetParameter(1) << " * (x - " << ff_sl_fix->GetParameter(2) << ")"; + // rebook the diffFN plot in the harvester + iBooker.setCurrentFolder(folder_ + "/harvester/x_alignment_relative/" + sc.name_); + iBooker.bookProfile("p_x_diffFN_vs_x_N", p_x_diffFN_vs_x_N); + if (debug_) { p_x_diffFN_vs_x_N->Write("p_x_diffFN_vs_x_N"); - TGraph *g_results = new TGraph(); + auto g_results = std::make_unique(); g_results->SetPoint(0, sh_x_N, 0.); g_results->SetPoint(1, a, a_unc); g_results->SetPoint(2, b, b_unc); @@ -565,18 +771,18 @@ void PPSAlignmentHarvester::xAlignmentRelative(DQMStore::IBooker &iBooker, // write results edm::LogInfo("PPS") << seqPos + 1 << ": x_alignment_relative:\n" - << results << seqPos + 1 << ": x_alignment_relative_sl_fix:\n" - << results_sl_fix; + << xAliRelResults_ << seqPos + 1 << ": x_alignment_relative_sl_fix:\n" + << xAliRelResultsSlopeFixed_; - if (resultsFile_.is_open()) { - resultsFile_ << seqPos + 1 << ": x_alignment_relative:\n" << results << "\n"; - resultsFile_ << seqPos + 1 << ": x_alignment_relative_sl_fix:\n" << results_sl_fix << "\n\n"; + if (textResultsFile_.is_open()) { + textResultsFile_ << seqPos + 1 << ": x_alignment_relative:\n" << xAliRelResults_ << "\n"; + textResultsFile_ << seqPos + 1 << ": x_alignment_relative_sl_fix:\n" << xAliRelResultsSlopeFixed_ << "\n\n"; } } // -------------------------------- y alignment methods -------------------------------- -double PPSAlignmentHarvester::findMax(TF1 *ff_fit) { +double PPSAlignmentHarvester::findMax(TF1* ff_fit) { const double mu = ff_fit->GetParameter(1); const double si = ff_fit->GetParameter(2); @@ -584,30 +790,28 @@ double PPSAlignmentHarvester::findMax(TF1 *ff_fit) { if (si > 25. || std::fabs(mu) > 100.) return 1E100; - double xMax = 1E100; - double yMax = -1E100; + double x_max = 1E100; + double y_max = -1E100; for (double x = mu - si; x <= mu + si; x += 0.001) { double y = ff_fit->Eval(x); - if (y > yMax) { - xMax = x; - yMax = y; + if (y > y_max) { + x_max = x; + y_max = y; } } - return xMax; + return x_max; } -TGraphErrors *PPSAlignmentHarvester::buildModeGraph(DQMStore::IBooker &iBooker, - MonitorElement *h2_y_vs_x, - const PPSAlignmentConfig &cfg, - const RPConfig &rpd) { - TDirectory *d_top = nullptr; +TH1D* PPSAlignmentHarvester::buildModeGraph(DQMStore::IBooker& iBooker, + MonitorElement* h2_y_vs_x, + const PPSAlignmentConfiguration& cfg, + const PPSAlignmentConfiguration::RPConfig& rpc) { + TDirectory* d_top = nullptr; if (debug_) d_top = gDirectory; - TF1 *ff_fit = new TF1("ff_fit", "[0] * exp(-(x-[1])*(x-[1])/2./[2]/[2]) + [3] + [4]*x"); - - TGraphErrors *g_y_mode_vs_x = new TGraphErrors(); + auto ff_fit = std::make_unique("ff_fit", "[0] * exp(-(x-[1])*(x-[1])/2./[2]/[2]) + [3] + [4]*x"); int h_n = h2_y_vs_x->getNbinsX(); double diff = h2_y_vs_x->getTH2D()->GetXaxis()->GetBinWidth(1) / 2.; @@ -619,11 +823,10 @@ TGraphErrors *PPSAlignmentHarvester::buildModeGraph(DQMStore::IBooker &iBooker, for (int bix = 1; bix <= h_n; bix++) { const double x = h2_y_vs_x->getTH2D()->GetXaxis()->GetBinCenter(bix); - const double x_unc = h2_y_vs_x->getTH2D()->GetXaxis()->GetBinWidth(bix) / 2.; char buf[100]; sprintf(buf, "h_y_x=%.3f", x); - TH1D *h_y = h2_y_vs_x->getTH2D()->ProjectionY(buf, bix, bix); + TH1D* h_y = h2_y_vs_x->getTH2D()->ProjectionY(buf, bix, bix); if (h_y->GetEntries() < cfg.multSelProjYMinEntries()) continue; @@ -645,20 +848,20 @@ TGraphErrors *PPSAlignmentHarvester::buildModeGraph(DQMStore::IBooker &iBooker, ff_fit->SetParameters(conMax, conMax_x, h_y->GetRMS() * 0.75, 0., 0.); ff_fit->FixParameter(4, 0.); - double xMin = rpd.x_min_fit_mode_, xMax = rpd.x_max_fit_mode_; - h_y->Fit(ff_fit, "Q", "", xMin, xMax); + double x_min = rpc.x_min_fit_mode_, x_max = rpc.x_max_fit_mode_; + h_y->Fit(ff_fit.get(), "Q", "", x_min, x_max); ff_fit->ReleaseParameter(4); double w = std::min(4., 2. * ff_fit->GetParameter(2)); - xMin = ff_fit->GetParameter(1) - w; - xMax = std::min(rpd.y_max_fit_mode_, ff_fit->GetParameter(1) + w); + x_min = ff_fit->GetParameter(1) - w; + x_max = std::min(rpc.y_max_fit_mode_, ff_fit->GetParameter(1) + w); - h_y->Fit(ff_fit, "Q", "", xMin, xMax); + h_y->Fit(ff_fit.get(), "Q", "", x_min, x_max); if (debug_) h_y->Write("h_y"); - double y_mode = findMax(ff_fit); + double y_mode = findMax(ff_fit.get()); const double y_mode_fit_unc = ff_fit->GetParameter(2) / 10; const double y_mode_sys_unc = cfg.y_mode_sys_unc(); double y_mode_unc = std::sqrt(y_mode_fit_unc * y_mode_fit_unc + y_mode_sys_unc * y_mode_sys_unc); @@ -670,7 +873,7 @@ TGraphErrors *PPSAlignmentHarvester::buildModeGraph(DQMStore::IBooker &iBooker, ff_fit->GetChisquare() / ff_fit->GetNDF() > chiSqThreshold); if (debug_) { - TGraph *g_data = new TGraph(); + auto g_data = std::make_unique(); g_data->SetPoint(0, y_mode, y_mode_unc); g_data->SetPoint(1, ff_fit->GetChisquare(), ff_fit->GetNDF()); g_data->SetPoint(2, valid, 0.); @@ -680,90 +883,82 @@ TGraphErrors *PPSAlignmentHarvester::buildModeGraph(DQMStore::IBooker &iBooker, if (!valid) continue; - int idx = g_y_mode_vs_x->GetN(); - g_y_mode_vs_x->SetPoint(idx, x, y_mode); - g_y_mode_vs_x->SetPointError(idx, x_unc, y_mode_unc); - h_mode->Fill(x, y_mode); h_mode->setBinError(bix, y_mode_unc); } - return g_y_mode_vs_x; + return h_mode->getTH1D(); } -void PPSAlignmentHarvester::yAlignment(DQMStore::IBooker &iBooker, - DQMStore::IGetter &iGetter, - const PPSAlignmentConfig &cfg, +void PPSAlignmentHarvester::yAlignment(DQMStore::IBooker& iBooker, + DQMStore::IGetter& iGetter, + const PPSAlignmentConfiguration& cfg, int seqPos) { - TDirectory *yAliDir = nullptr; + TDirectory* yAliDir = nullptr; if (debug_) yAliDir = debugFile_->mkdir((std::to_string(seqPos + 1) + ": y_alignment").c_str()); - // prepare results - CTPPSRPAlignmentCorrectionsData results; - CTPPSRPAlignmentCorrectionsData results_sl_fix; - - TF1 *ff = new TF1("ff", "[0] + [1]*(x - [2])"); - TF1 *ff_sl_fix = new TF1("ff_sl_fix", "[0] + [1]*(x - [2])"); + auto ff = std::make_unique("ff", "[0] + [1]*(x - [2])"); + auto ff_sl_fix = std::make_unique("ff_sl_fix", "[0] + [1]*(x - [2])"); // processing - for (const auto &sd : {cfg.sectorConfig45(), cfg.sectorConfig56()}) { - for (const auto &rpd : {sd.rp_F_, sd.rp_N_}) { - TDirectory *rpDir = nullptr; + for (const auto& sc : {cfg.sectorConfig45(), cfg.sectorConfig56()}) { + for (const auto& rpc : {sc.rp_F_, sc.rp_N_}) { + TDirectory* rpDir = nullptr; if (debug_) { - rpDir = yAliDir->mkdir(rpd.name_.c_str()); + rpDir = yAliDir->mkdir(rpc.name_.c_str()); gDirectory = rpDir->mkdir("x"); } - auto *h2_y_vs_x = - iGetter.get(folder_ + "/worker/" + sd.name_ + "/multiplicity selection/" + rpd.name_ + "/h2_y_vs_x"); + auto* h2_y_vs_x = + iGetter.get(folder_ + "/worker/" + sc.name_ + "/multiplicity selection/" + rpc.name_ + "/h2_y_vs_x"); if (h2_y_vs_x == nullptr) { - edm::LogWarning("PPS") << "[y_alignment] " << rpd.name_ << ": cannot load data, skipping"; + edm::LogWarning("PPS") << "[y_alignment] " << rpc.name_ << ": cannot load data, skipping"; continue; } - iBooker.setCurrentFolder(folder_ + "/harvester/y alignment/" + rpd.name_); - auto *g_y_cen_vs_x = buildModeGraph(iBooker, h2_y_vs_x, cfg, rpd); + iBooker.setCurrentFolder(folder_ + "/harvester/y alignment/" + rpc.name_); + auto* h_y_cen_vs_x = buildModeGraph(iBooker, h2_y_vs_x, cfg, rpc); - if ((unsigned int)g_y_cen_vs_x->GetN() < cfg.modeGraphMinN()) { - edm::LogWarning("PPS") << "[y_alignment] " << rpd.name_ << ": insufficient data, skipping (mode graph " - << g_y_cen_vs_x->GetN() << "/" << cfg.modeGraphMinN() << ")"; + if ((unsigned int)h_y_cen_vs_x->GetEntries() < cfg.modeGraphMinN()) { + edm::LogWarning("PPS") << "[y_alignment] " << rpc.name_ << ": insufficient data, skipping (mode graph " + << h_y_cen_vs_x->GetEntries() << "/" << cfg.modeGraphMinN() << ")"; continue; } - const double xMin = cfg.alignment_y_ranges().at(rpd.id_).x_min_; - const double xMax = cfg.alignment_y_ranges().at(rpd.id_).x_max_; + const double x_min = cfg.alignment_y_ranges().at(rpc.id_).x_min_; + const double x_max = cfg.alignment_y_ranges().at(rpc.id_).x_max_; - const double sh_x = sh_x_map[rpd.id_]; - double slope = rpd.slope_; + const double sh_x = sh_x_map_[rpc.id_]; + double slope = rpc.slope_; ff->SetParameters(0., 0., 0.); ff->FixParameter(2, -sh_x); ff->SetLineColor(2); - g_y_cen_vs_x->Fit(ff, "Q", "", xMin, xMax); + h_y_cen_vs_x->Fit(ff.get(), "Q", "", x_min, x_max); const double a = ff->GetParameter(1), a_unc = ff->GetParError(1); const double b = ff->GetParameter(0), b_unc = ff->GetParError(0); - edm::LogInfo("PPS") << "[y_alignment] " << rpd.name_ << ":\n" - << std::fixed << std::setprecision(3) << " x_min = " << xMin << ", x_max = " << xMax + edm::LogInfo("PPS") << "[y_alignment] " << rpc.name_ << ":\n" + << std::fixed << std::setprecision(3) << " x_min = " << x_min << ", x_max = " << x_max << "\n" << " sh_x = " << sh_x << ", slope (fix) = " << slope << ", slope (fitted) = " << a; CTPPSRPAlignmentCorrectionData rpResult(0., 0., b, b_unc, 0., 0., 0., 0., 0., 0., 0., 0.); - results.setRPCorrection(rpd.id_, rpResult); + yAliResults_.setRPCorrection(rpc.id_, rpResult); ff_sl_fix->SetParameters(0., 0., 0.); ff_sl_fix->FixParameter(1, slope); ff_sl_fix->FixParameter(2, -sh_x); ff_sl_fix->SetLineColor(4); - g_y_cen_vs_x->Fit(ff_sl_fix, "Q+", "", xMin, xMax); + h_y_cen_vs_x->Fit(ff_sl_fix.get(), "Q+", "", x_min, x_max); const double b_fs = ff_sl_fix->GetParameter(0), b_fs_unc = ff_sl_fix->GetParError(0); CTPPSRPAlignmentCorrectionData rpResult_sl_fix(0., 0., b_fs, b_fs_unc, 0., 0., 0., 0., 0., 0., 0., 0.); - results_sl_fix.setRPCorrection(rpd.id_, rpResult_sl_fix); + yAliResultsSlopeFixed_.setRPCorrection(rpc.id_, rpResult_sl_fix); edm::LogInfo("PPS") << "[y_alignment] " << std::fixed << std::setprecision(3) << "ff: " << ff->GetParameter(0) << " + " << ff->GetParameter(1) << " * (x - " << ff->GetParameter(2) @@ -773,10 +968,10 @@ void PPSAlignmentHarvester::yAlignment(DQMStore::IBooker &iBooker, if (debug_) { gDirectory = rpDir; - g_y_cen_vs_x->SetTitle(";x (mm); mode of y (mm)"); - g_y_cen_vs_x->Write("g_y_cen_vs_x"); + h_y_cen_vs_x->SetTitle(";x (mm); mode of y (mm)"); + h_y_cen_vs_x->Write("h_y_cen_vs_x"); - TGraph *g_results = new TGraph(); + auto g_results = std::make_unique(); g_results->SetPoint(0, sh_x, 0.); g_results->SetPoint(1, a, a_unc); g_results->SetPoint(2, b, b_unc); @@ -788,33 +983,60 @@ void PPSAlignmentHarvester::yAlignment(DQMStore::IBooker &iBooker, // write results edm::LogInfo("PPS") << seqPos + 1 << ": y_alignment:\n" - << results << seqPos + 1 << ": y_alignment_sl_fix:\n" - << results_sl_fix; + << yAliResults_ << seqPos + 1 << ": y_alignment_sl_fix:\n" + << yAliResultsSlopeFixed_; - if (resultsFile_.is_open()) { - resultsFile_ << seqPos + 1 << ": y_alignment:\n" << results << "\n"; - resultsFile_ << seqPos + 1 << ": y_alignment_sl_fix:\n" << results_sl_fix << "\n\n"; + if (textResultsFile_.is_open()) { + textResultsFile_ << seqPos + 1 << ": y_alignment:\n" << yAliResults_ << "\n"; + textResultsFile_ << seqPos + 1 << ": y_alignment_sl_fix:\n" << yAliResultsSlopeFixed_ << "\n\n"; } } -// -------------------------------- PPSAlignmentHarvester methods -------------------------------- +// -------------------------------- other methods -------------------------------- + +void PPSAlignmentHarvester::writeCutPlot(TH2D* h, double a, double c, double n_si, double si, const std::string& label) { + auto canvas = std::make_unique(); + canvas->SetName(label.c_str()); + canvas->SetLogz(1); + + h->Draw("colz"); + + double x_min = -30.; + double x_max = 30.; + + auto g_up = std::make_unique(); + g_up->SetName("g_up"); + g_up->SetPoint(0, x_min, -a * x_min - c + n_si * si); + g_up->SetPoint(1, x_max, -a * x_max - c + n_si * si); + g_up->SetLineColor(1); + g_up->Draw("l"); + + auto g_down = std::make_unique(); + g_down->SetName("g_down"); + g_down->SetPoint(0, x_min, -a * x_min - c - n_si * si); + g_down->SetPoint(1, x_max, -a * x_max - c - n_si * si); + g_down->SetLineColor(1); + g_down->Draw("l"); + + canvas->Write(); +} // Points in TGraph should be sorted (TGraph::Sort()) // if n, binWidth, or min is set to -1, method will find it on its own -TH1D *PPSAlignmentHarvester::getTH1DFromTGraphErrors( - TGraphErrors *graph, std::string title, std::string labels, int n, double binWidth, double min) { - TH1D *hist; +std::unique_ptr PPSAlignmentHarvester::getTH1DFromTGraphErrors( + TGraphErrors* graph, std::string title, std::string labels, int n, double binWidth, double min) { + std::unique_ptr hist; if (n == 0) { - hist = new TH1D(title.c_str(), labels.c_str(), 0, -10., 10.); + hist = std::make_unique(title.c_str(), labels.c_str(), 0, -10., 10.); } else if (n == 1) { - hist = new TH1D(title.c_str(), labels.c_str(), 1, graph->GetPointX(0) - 5., graph->GetPointX(0) + 5.); + hist = std::make_unique(title.c_str(), labels.c_str(), 1, graph->GetPointX(0) - 5., graph->GetPointX(0) + 5.); } else { n = n == -1 ? graph->GetN() : n; binWidth = binWidth == -1 ? graph->GetPointX(1) - graph->GetPointX(0) : binWidth; double diff = binWidth / 2.; min = min == -1 ? graph->GetPointX(0) - diff : min; double max = min + n * binWidth; - hist = new TH1D(title.c_str(), labels.c_str(), n, min, max); + hist = std::make_unique(title.c_str(), labels.c_str(), n, min, max); } for (int i = 0; i < graph->GetN(); i++) { @@ -826,55 +1048,4 @@ TH1D *PPSAlignmentHarvester::getTH1DFromTGraphErrors( return hist; } -PPSAlignmentHarvester::PPSAlignmentHarvester(const edm::ParameterSet &iConfig) - : esTokenTest_( - esConsumes(edm::ESInputTag("", ""))), - esTokenReference_(esConsumes( - edm::ESInputTag("", "reference"))), - folder_(iConfig.getParameter("folder")), - debug_(iConfig.getParameter("debug")) {} - -void PPSAlignmentHarvester::dqmEndJob(DQMStore::IBooker &iBooker, DQMStore::IGetter &iGetter) {} - -void PPSAlignmentHarvester::dqmEndRun(DQMStore::IBooker &iBooker, - DQMStore::IGetter &iGetter, - edm::Run const &iRun, - edm::EventSetup const &iSetup) { - const auto &cfg = iSetup.getData(esTokenTest_); - - const auto &cfg_ref = iSetup.getData(esTokenReference_); - - if (debug_) - debugFile_ = new TFile("debug_harvester.root", "recreate"); - - if (!cfg.resultsDir().empty()) - resultsFile_.open(cfg.resultsDir(), std::ios::out | std::ios::trunc); - - // setting default sh_x values from config - for (const auto &sd : {cfg.sectorConfig45(), cfg.sectorConfig56()}) { - for (const auto &rpd : {sd.rp_N_, sd.rp_F_}) { - edm::LogInfo("PPS") << "[harvester] " << std::fixed << std::setprecision(3) << "Setting sh_x of " << rpd.name_ - << " to " << rpd.sh_x_; - sh_x_map[rpd.id_] = rpd.sh_x_; - } - } - - for (unsigned int i = 0; i < cfg.sequence().size(); i++) { - if (cfg.sequence()[i] == "x_alignment") - xAlignment(iBooker, iGetter, cfg, cfg_ref, i); - else if (cfg.sequence()[i] == "x_alignment_relative") - xAlignmentRelative(iBooker, iGetter, cfg, i); - else if (cfg.sequence()[i] == "y_alignment") - yAlignment(iBooker, iGetter, cfg, i); - else - edm::LogError("PPS") << "[harvester] " << cfg.sequence()[i] << " is a wrong method name."; - } - - if (debug_) - delete debugFile_; - - if (resultsFile_.is_open()) - resultsFile_.close(); -} - -DEFINE_FWK_MODULE(PPSAlignmentHarvester); \ No newline at end of file +DEFINE_FWK_MODULE(PPSAlignmentHarvester); diff --git a/CalibPPS/AlignmentGlobal/plugins/PPSAlignmentWorker.cc b/CalibPPS/AlignmentGlobal/plugins/PPSAlignmentWorker.cc index 00844dbeb85d8..a8f200e7fd073 100644 --- a/CalibPPS/AlignmentGlobal/plugins/PPSAlignmentWorker.cc +++ b/CalibPPS/AlignmentGlobal/plugins/PPSAlignmentWorker.cc @@ -1,14 +1,8 @@ /**************************************************************************** - * - * CalibPPS/AlignmentGlobal/plugins/PPSAlignmentWorker.cc - * - * Description : PPS Alignment DQM worker - * - * Authors: - * - Jan KaÅ¡par - * - Mateusz Kocot - * - ****************************************************************************/ +* Authors: +* Jan KaÅ¡par (jan.kaspar@gmail.com) +* Mateusz Kocot (mateuszkocot99@gmail.com) +****************************************************************************/ #include "DQMServices/Core/interface/DQMEDAnalyzer.h" #include "DQMServices/Core/interface/DQMStore.h" @@ -25,12 +19,13 @@ #include "DataFormats/CTPPSReco/interface/CTPPSLocalTrackLite.h" #include "DataFormats/CTPPSReco/interface/CTPPSLocalTrackLiteFwd.h" -#include "CondFormats/PPSObjects/interface/PPSAlignmentConfig.h" -#include "CondFormats/DataRecord/interface/PPSAlignmentConfigRcd.h" +#include "CondFormats/PPSObjects/interface/PPSAlignmentConfiguration.h" +#include "CondFormats/DataRecord/interface/PPSAlignmentConfigurationRcd.h" #include #include #include +#include #include "TH2D.h" #include "TGraph.h" @@ -39,86 +34,151 @@ class PPSAlignmentWorker : public DQMEDAnalyzer { public: - PPSAlignmentWorker(const edm::ParameterSet &iConfig); + PPSAlignmentWorker(const edm::ParameterSet& iConfig); + + static void fillDescriptions(edm::ConfigurationDescriptions& descriptions); private: - void bookHistograms(DQMStore::IBooker &iBooker, edm::Run const &, edm::EventSetup const &iSetup) override; - void analyze(const edm::Event &iEvent, const edm::EventSetup &iSetup) override; + void bookHistograms(DQMStore::IBooker& iBooker, edm::Run const&, edm::EventSetup const& iSetup) override; + void analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) override; // ------------ structures ------------ struct SectorData { - SectorConfig scfg; + PPSAlignmentConfiguration::SectorConfig scfg_; // hit distributions - std::map m_h2_y_vs_x_bef_sel; + std::map m_h2_y_vs_x_bef_sel; - std::map m_h2_y_vs_x_mlt_sel; + std::map m_h2_y_vs_x_mlt_sel; - std::map m_h2_y_vs_x_aft_sel; + std::map m_h2_y_vs_x_aft_sel; // cut plots - MonitorElement *h_q_cut_h_bef, *h_q_cut_h_aft; - MonitorElement *h2_cut_h_bef, *h2_cut_h_aft; + MonitorElement* h_q_cut_h_bef; + MonitorElement* h_q_cut_h_aft; + MonitorElement* h2_cut_h_bef; + MonitorElement* h2_cut_h_aft; - MonitorElement *h_q_cut_v_bef, *h_q_cut_v_aft; - MonitorElement *h2_cut_v_bef, *h2_cut_v_aft; + MonitorElement* h_q_cut_v_bef; + MonitorElement* h_q_cut_v_aft; + MonitorElement* h2_cut_v_bef; + MonitorElement* h2_cut_v_aft; // near-far plots - MonitorElement *p_x_diffFN_vs_x_N; - MonitorElement *p_y_diffFN_vs_y_F; + MonitorElement* p_x_diffFN_vs_x_N; + MonitorElement* p_y_diffFN_vs_y_F; struct SlicePlots { - MonitorElement *h_y; - MonitorElement *h2_y_diffFN_vs_y; - MonitorElement *p_y_diffFN_vs_y; + MonitorElement* h_y; + MonitorElement* h2_y_diffFN_vs_y; + MonitorElement* p_y_diffFN_vs_y; SlicePlots(); - SlicePlots(DQMStore::IBooker &iBooker, bool debug); + SlicePlots(DQMStore::IBooker& iBooker, const PPSAlignmentConfiguration& cfg, bool debug); }; std::map x_slice_plots_N, x_slice_plots_F; - void init(DQMStore::IBooker &iBooker, - const PPSAlignmentConfig &cfg, - const SectorConfig &_scfg, - const std::string &folder, + void init(DQMStore::IBooker& iBooker, + const PPSAlignmentConfiguration& cfg, + const PPSAlignmentConfiguration::SectorConfig& scfg, + const std::string& folder, bool debug); - unsigned int process(const CTPPSLocalTrackLiteCollection &tracks, const PPSAlignmentConfig &cfg, bool debug); + unsigned int process(const CTPPSLocalTrackLiteCollection& tracks, const PPSAlignmentConfiguration& cfg, bool debug); }; // ------------ member data ------------ - edm::ESGetToken esTokenBookHistograms_; - edm::ESGetToken esTokenAnalyze_; + edm::ESGetToken esTokenBookHistograms_; + edm::ESGetToken esTokenAnalyze_; edm::EDGetTokenT tracksToken_; - SectorData sectorData45; - SectorData sectorData56; + SectorData sectorData45_; + SectorData sectorData56_; std::string folder_; bool debug_; }; +// -------------------------------- DQMEDAnalyzer methods -------------------------------- + +PPSAlignmentWorker::PPSAlignmentWorker(const edm::ParameterSet& iConfig) + : esTokenBookHistograms_( + esConsumes( + edm::ESInputTag("", iConfig.getParameter("label")))), + esTokenAnalyze_(esConsumes( + edm::ESInputTag("", iConfig.getParameter("label")))), + tracksToken_(consumes(iConfig.getParameter("tagTracks"))), + folder_(iConfig.getParameter("folder")), + debug_(iConfig.getParameter("debug")) { + edm::LogInfo("PPS").log([&](auto& li) { + li << "[worker] parameters:\n"; + li << "* label: " << iConfig.getParameter("label") << "\n"; + li << "* tagTracks: " << iConfig.getParameter("tagTracks") << "\n"; + li << "* folder: " << folder_ << "\n"; + li << "* debug: " << std::boolalpha << debug_; + }); +} + +void PPSAlignmentWorker::bookHistograms(DQMStore::IBooker& iBooker, edm::Run const&, edm::EventSetup const& iSetup) { + const auto& cfg = iSetup.getData(esTokenBookHistograms_); + + sectorData45_.init(iBooker, cfg, cfg.sectorConfig45(), folder_ + "/worker", debug_); + sectorData56_.init(iBooker, cfg, cfg.sectorConfig56(), folder_ + "/worker", debug_); +} + +void PPSAlignmentWorker::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) { + const auto& tracks = iEvent.get(tracksToken_); + + const auto& cfg = iSetup.getData(esTokenAnalyze_); + + sectorData45_.process(tracks, cfg, debug_); + sectorData56_.process(tracks, cfg, debug_); +} + +void PPSAlignmentWorker::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { + edm::ParameterSetDescription desc; + + desc.add("label", ""); + desc.add("tagTracks", edm::InputTag("ctppsLocalTrackLiteProducer")); + desc.add("folder", "AlCaReco/PPSAlignment"); + desc.add("debug", false); + + descriptions.addWithDefaultLabel(desc); +} + // -------------------------------- SectorData and SlicePlots methods -------------------------------- PPSAlignmentWorker::SectorData::SlicePlots::SlicePlots() {} -PPSAlignmentWorker::SectorData::SlicePlots::SlicePlots(DQMStore::IBooker &iBooker, bool debug) { - h_y = iBooker.book1DD("h_y", ";y", 100, -10., 10.); - auto *tmp = new TProfile("", ";y;x_{F} - y_{N}", 100, -10., 10.); - p_y_diffFN_vs_y = iBooker.bookProfile("p_y_diffFN_vs_y", tmp); +PPSAlignmentWorker::SectorData::SlicePlots::SlicePlots(DQMStore::IBooker& iBooker, + const PPSAlignmentConfiguration& cfg, + bool debug) { + h_y = iBooker.book1DD( + "h_y", ";y", cfg.binning().slice_n_bins_x_, cfg.binning().slice_x_min_, cfg.binning().slice_x_max_); + + auto profilePtr = std::make_unique( + "", ";y;y_{F} - y_{N}", cfg.binning().slice_n_bins_x_, cfg.binning().slice_x_min_, cfg.binning().slice_x_max_); + p_y_diffFN_vs_y = iBooker.bookProfile("p_y_diffFN_vs_y", profilePtr.get()); if (debug) - h2_y_diffFN_vs_y = iBooker.book2DD("h2_y_diffFN_vs_y", ";y;x_{F} - y_{N}", 100, -10., 10., 100, -2., 2.); + h2_y_diffFN_vs_y = iBooker.book2DD("h2_y_diffFN_vs_y", + ";y;y_{F} - y_{N}", + cfg.binning().slice_n_bins_x_, + cfg.binning().slice_x_min_, + cfg.binning().slice_x_max_, + cfg.binning().slice_n_bins_y_, + cfg.binning().slice_y_min_, + cfg.binning().slice_y_max_); } -void PPSAlignmentWorker::SectorData::init(DQMStore::IBooker &iBooker, - const PPSAlignmentConfig &cfg, - const SectorConfig &_scfg, - const std::string &folder, +void PPSAlignmentWorker::SectorData::init(DQMStore::IBooker& iBooker, + const PPSAlignmentConfiguration& cfg, + const PPSAlignmentConfiguration::SectorConfig& scfg, + const std::string& folder, bool debug) { - scfg = _scfg; + scfg_ = scfg; // binning const double bin_size_x = cfg.binning().bin_size_x_; @@ -133,29 +193,29 @@ void PPSAlignmentWorker::SectorData::init(DQMStore::IBooker &iBooker, const double y_min = cfg.binning().y_min_, y_max = cfg.binning().y_max_; // hit distributions - iBooker.setCurrentFolder(folder + "/" + scfg.name_ + "/before selection/" + scfg.rp_N_.name_); - m_h2_y_vs_x_bef_sel[scfg.rp_N_.id_] = + iBooker.setCurrentFolder(folder + "/" + scfg_.name_ + "/before selection/" + scfg_.rp_N_.name_); + m_h2_y_vs_x_bef_sel[scfg_.rp_N_.id_] = iBooker.book2DD("h2_y_vs_x", ";x;y", n_bins_x, x_min_str, x_max_str, n_bins_y, y_min, y_max); - iBooker.setCurrentFolder(folder + "/" + scfg.name_ + "/before selection/" + scfg.rp_F_.name_); - m_h2_y_vs_x_bef_sel[scfg.rp_F_.id_] = + iBooker.setCurrentFolder(folder + "/" + scfg_.name_ + "/before selection/" + scfg_.rp_F_.name_); + m_h2_y_vs_x_bef_sel[scfg_.rp_F_.id_] = iBooker.book2DD("h2_y_vs_x", ";x;y", n_bins_x, x_min_pix, x_max_pix, n_bins_y, y_min, y_max); - iBooker.setCurrentFolder(folder + "/" + scfg.name_ + "/multiplicity selection/" + scfg.rp_N_.name_); - m_h2_y_vs_x_mlt_sel[scfg.rp_N_.id_] = + iBooker.setCurrentFolder(folder + "/" + scfg_.name_ + "/multiplicity selection/" + scfg_.rp_N_.name_); + m_h2_y_vs_x_mlt_sel[scfg_.rp_N_.id_] = iBooker.book2DD("h2_y_vs_x", ";x;y", n_bins_x, x_min_str, x_max_str, n_bins_y, y_min, y_max); - iBooker.setCurrentFolder(folder + "/" + scfg.name_ + "/multiplicity selection/" + scfg.rp_F_.name_); - m_h2_y_vs_x_mlt_sel[scfg.rp_F_.id_] = + iBooker.setCurrentFolder(folder + "/" + scfg_.name_ + "/multiplicity selection/" + scfg_.rp_F_.name_); + m_h2_y_vs_x_mlt_sel[scfg_.rp_F_.id_] = iBooker.book2DD("h2_y_vs_x", ";x;y", n_bins_x, x_min_pix, x_max_pix, n_bins_y, y_min, y_max); - iBooker.setCurrentFolder(folder + "/" + scfg.name_ + "/after selection/" + scfg.rp_N_.name_); - m_h2_y_vs_x_aft_sel[scfg.rp_N_.id_] = + iBooker.setCurrentFolder(folder + "/" + scfg_.name_ + "/after selection/" + scfg_.rp_N_.name_); + m_h2_y_vs_x_aft_sel[scfg_.rp_N_.id_] = iBooker.book2DD("h2_y_vs_x", ";x;y", n_bins_x, x_min_str, x_max_str, n_bins_y, y_min, y_max); - iBooker.setCurrentFolder(folder + "/" + scfg.name_ + "/after selection/" + scfg.rp_F_.name_); - m_h2_y_vs_x_aft_sel[scfg.rp_F_.id_] = + iBooker.setCurrentFolder(folder + "/" + scfg_.name_ + "/after selection/" + scfg_.rp_F_.name_); + m_h2_y_vs_x_aft_sel[scfg_.rp_F_.id_] = iBooker.book2DD("h2_y_vs_x", ";x;y", n_bins_x, x_min_pix, x_max_pix, n_bins_y, y_min, y_max); // cut plots - iBooker.setCurrentFolder(folder + "/" + scfg.name_ + "/cuts/cut_h"); + iBooker.setCurrentFolder(folder + "/" + scfg_.name_ + "/cuts/cut_h"); h_q_cut_h_bef = iBooker.book1DD("h_q_cut_h_bef", ";cq_h", 400, -2., 2.); h_q_cut_h_aft = iBooker.book1DD("h_q_cut_h_aft", ";cq_h", 400, -2., 2.); h2_cut_h_bef = @@ -163,119 +223,105 @@ void PPSAlignmentWorker::SectorData::init(DQMStore::IBooker &iBooker, h2_cut_h_aft = iBooker.book2DD("h2_cut_h_aft", ";x_up;x_dw", n_bins_x, x_min_str, x_max_str, n_bins_x, x_min_pix, x_max_pix); - iBooker.setCurrentFolder(folder + "/" + scfg.name_ + "/cuts/cut_v"); + iBooker.setCurrentFolder(folder + "/" + scfg_.name_ + "/cuts/cut_v"); h_q_cut_v_bef = iBooker.book1DD("h_q_cut_v_bef", ";cq_v", 400, -2., 2.); h_q_cut_v_aft = iBooker.book1DD("h_q_cut_v_aft", ";cq_v", 400, -2., 2.); h2_cut_v_bef = iBooker.book2DD("h2_cut_v_bef", ";y_up;y_dw", n_bins_y, y_min, y_max, n_bins_y, y_min, y_max); h2_cut_v_aft = iBooker.book2DD("h2_cut_v_aft", ";y_up;y_dw", n_bins_y, y_min, y_max, n_bins_y, y_min, y_max); // near-far plots - iBooker.setCurrentFolder(folder + "/" + scfg.name_ + "/near_far"); - auto *tmp = new TProfile("", ";x_{N};x_{F} - x_{N}", 100, 0., 20.); - p_x_diffFN_vs_x_N = iBooker.bookProfile("p_x_diffFN_vs_x_N", tmp); + iBooker.setCurrentFolder(folder + "/" + scfg_.name_ + "/near_far"); - for (int i = 0; i < scfg.rp_N_.x_slice_n_; i++) { - const double xMin = scfg.rp_N_.x_slice_min_ + i * scfg.rp_N_.x_slice_w_; - const double xMax = scfg.rp_N_.x_slice_min_ + (i + 1) * scfg.rp_N_.x_slice_w_; + auto profilePtr = std::make_unique("", + ";x_{N};x_{F} - x_{N}", + cfg.binning().diffFN_n_bins_x_, + cfg.binning().diffFN_x_min_, + cfg.binning().diffFN_x_max_); + p_x_diffFN_vs_x_N = iBooker.bookProfile("p_x_diffFN_vs_x_N", profilePtr.get()); + + for (int i = 0; i < scfg_.rp_N_.x_slice_n_; i++) { + const double x_min = scfg_.rp_N_.x_slice_min_ + i * scfg_.rp_N_.x_slice_w_; + const double x_max = scfg_.rp_N_.x_slice_min_ + (i + 1) * scfg_.rp_N_.x_slice_w_; char buf[100]; - sprintf(buf, "%.1f-%.1f", xMin, xMax); + sprintf(buf, "%.1f-%.1f", x_min, x_max); - iBooker.setCurrentFolder(folder + "/" + scfg.name_ + "/near_far/x slices, N/" + buf); - x_slice_plots_N.insert({i, SlicePlots(iBooker, debug)}); + iBooker.setCurrentFolder(folder + "/" + scfg_.name_ + "/near_far/x slices, N/" + buf); + x_slice_plots_N.insert({i, SlicePlots(iBooker, cfg, debug)}); } - for (int i = 0; i < scfg.rp_F_.x_slice_n_; i++) { - const double xMin = scfg.rp_F_.x_slice_min_ + i * scfg.rp_F_.x_slice_w_; - const double xMax = scfg.rp_F_.x_slice_min_ + (i + 1) * scfg.rp_F_.x_slice_w_; + for (int i = 0; i < scfg_.rp_F_.x_slice_n_; i++) { + const double x_min = scfg_.rp_F_.x_slice_min_ + i * scfg_.rp_F_.x_slice_w_; + const double x_max = scfg_.rp_F_.x_slice_min_ + (i + 1) * scfg_.rp_F_.x_slice_w_; char buf[100]; - sprintf(buf, "%.1f-%.1f", xMin, xMax); + sprintf(buf, "%.1f-%.1f", x_min, x_max); - iBooker.setCurrentFolder(folder + "/" + scfg.name_ + "/near_far/x slices, F/" + buf); - x_slice_plots_F.insert({i, SlicePlots(iBooker, debug)}); + iBooker.setCurrentFolder(folder + "/" + scfg_.name_ + "/near_far/x slices, F/" + buf); + x_slice_plots_F.insert({i, SlicePlots(iBooker, cfg, debug)}); } } -unsigned int PPSAlignmentWorker::SectorData::process(const CTPPSLocalTrackLiteCollection &tracks, - const PPSAlignmentConfig &cfg, +unsigned int PPSAlignmentWorker::SectorData::process(const CTPPSLocalTrackLiteCollection& tracks, + const PPSAlignmentConfiguration& cfg, bool debug) { CTPPSLocalTrackLiteCollection tracksUp, tracksDw; - for (const auto &tr : tracks) { + for (const auto& tr : tracks) { CTPPSDetId rpId(tr.rpId()); unsigned int rpDecId = rpId.arm() * 100 + rpId.station() * 10 + rpId.rp(); - if (rpDecId != scfg.rp_N_.id_ && rpDecId != scfg.rp_F_.id_) + if (rpDecId != scfg_.rp_N_.id_ && rpDecId != scfg_.rp_F_.id_) continue; - double x = tr.x(); - double y = tr.y(); - - // re-build track object - CTPPSLocalTrackLite trCorr(tr.rpId(), - x, - 0., - y, - 0., - tr.tx(), - tr.txUnc(), - tr.ty(), - tr.tyUnc(), - tr.chiSquaredOverNDF(), - tr.pixelTrackRecoInfo(), - tr.numberOfPointsUsedForFit(), - tr.time(), - tr.timeUnc()); - - // store corrected track into the right collection - if (rpDecId == scfg.rp_N_.id_) - tracksUp.push_back(trCorr); - if (rpDecId == scfg.rp_F_.id_) - tracksDw.push_back(trCorr); + // store the track in the right collection + if (rpDecId == scfg_.rp_N_.id_) + tracksUp.push_back(tr); + if (rpDecId == scfg_.rp_F_.id_) + tracksDw.push_back(tr); } // update plots before selection - for (const auto &tr : tracksUp) - m_h2_y_vs_x_bef_sel[scfg.rp_N_.id_]->Fill(tr.x(), tr.y()); + for (const auto& tr : tracksUp) + m_h2_y_vs_x_bef_sel[scfg_.rp_N_.id_]->Fill(tr.x(), tr.y()); - for (const auto &tr : tracksDw) - m_h2_y_vs_x_bef_sel[scfg.rp_F_.id_]->Fill(tr.x(), tr.y()); + for (const auto& tr : tracksDw) + m_h2_y_vs_x_bef_sel[scfg_.rp_F_.id_]->Fill(tr.x(), tr.y()); - // skip crowded events - if (tracksUp.size() > cfg.maxRPTracksSize()) + // skip crowded events (multiplicity selection) + if (tracksUp.size() < cfg.minRPTracksSize() || tracksUp.size() > cfg.maxRPTracksSize()) return 0; - if (tracksDw.size() > cfg.maxRPTracksSize()) + if (tracksDw.size() < cfg.minRPTracksSize() || tracksDw.size() > cfg.maxRPTracksSize()) return 0; // update plots with multiplicity selection - for (const auto &tr : tracksUp) - m_h2_y_vs_x_mlt_sel[scfg.rp_N_.id_]->Fill(tr.x(), tr.y()); + for (const auto& tr : tracksUp) + m_h2_y_vs_x_mlt_sel[scfg_.rp_N_.id_]->Fill(tr.x(), tr.y()); - for (const auto &tr : tracksDw) - m_h2_y_vs_x_mlt_sel[scfg.rp_F_.id_]->Fill(tr.x(), tr.y()); + for (const auto& tr : tracksDw) + m_h2_y_vs_x_mlt_sel[scfg_.rp_F_.id_]->Fill(tr.x(), tr.y()); // do the selection unsigned int pairsSelected = 0; - for (const auto &trUp : tracksUp) { - for (const auto &trDw : tracksDw) { + for (const auto& trUp : tracksUp) { + for (const auto& trDw : tracksDw) { h2_cut_h_bef->Fill(trUp.x(), trDw.x()); h2_cut_v_bef->Fill(trUp.y(), trDw.y()); - const double cq_h = trDw.x() + scfg.cut_h_a_ * trUp.x() + scfg.cut_h_c_; + const double cq_h = trDw.x() + scfg_.cut_h_a_ * trUp.x() + scfg_.cut_h_c_; h_q_cut_h_bef->Fill(cq_h); - const bool cv_h = (std::fabs(cq_h) < cfg.n_si() * scfg.cut_h_si_); + const bool cv_h = (std::fabs(cq_h) < cfg.n_si() * scfg_.cut_h_si_); - const double cq_v = trDw.y() + scfg.cut_v_a_ * trUp.y() + scfg.cut_v_c_; + const double cq_v = trDw.y() + scfg_.cut_v_a_ * trUp.y() + scfg_.cut_v_c_; h_q_cut_v_bef->Fill(cq_v); - const bool cv_v = (std::fabs(cq_v) < cfg.n_si() * scfg.cut_v_si_); + const bool cv_v = (std::fabs(cq_v) < cfg.n_si() * scfg_.cut_v_si_); bool cutsPassed = true; - if (scfg.cut_h_apply_) + if (scfg_.cut_h_apply_) cutsPassed &= cv_h; - if (scfg.cut_v_apply_) + if (scfg_.cut_v_apply_) cutsPassed &= cv_v; if (cutsPassed) { @@ -287,21 +333,21 @@ unsigned int PPSAlignmentWorker::SectorData::process(const CTPPSLocalTrackLiteCo h2_cut_h_aft->Fill(trUp.x(), trDw.x()); h2_cut_v_aft->Fill(trUp.y(), trDw.y()); - m_h2_y_vs_x_aft_sel[scfg.rp_N_.id_]->Fill(trUp.x(), trUp.y()); - m_h2_y_vs_x_aft_sel[scfg.rp_F_.id_]->Fill(trDw.x(), trDw.y()); + m_h2_y_vs_x_aft_sel[scfg_.rp_N_.id_]->Fill(trUp.x(), trUp.y()); + m_h2_y_vs_x_aft_sel[scfg_.rp_F_.id_]->Fill(trDw.x(), trDw.y()); p_x_diffFN_vs_x_N->Fill(trUp.x(), trDw.x() - trUp.x()); - int idx = (trUp.x() - scfg.rp_N_.x_slice_min_) / scfg.rp_N_.x_slice_w_; - if (idx >= 0 && idx < scfg.rp_N_.x_slice_n_) { + int idx = (trUp.x() - scfg_.rp_N_.x_slice_min_) / scfg_.rp_N_.x_slice_w_; + if (idx >= 0 && idx < scfg_.rp_N_.x_slice_n_) { x_slice_plots_N[idx].h_y->Fill(trUp.y()); x_slice_plots_N[idx].p_y_diffFN_vs_y->Fill(trUp.y(), trDw.y() - trUp.y()); if (debug) x_slice_plots_N[idx].h2_y_diffFN_vs_y->Fill(trUp.y(), trDw.y() - trUp.y()); } - idx = (trDw.x() - scfg.rp_F_.x_slice_min_) / scfg.rp_F_.x_slice_w_; - if (idx >= 0 && idx < scfg.rp_F_.x_slice_n_) { + idx = (trDw.x() - scfg_.rp_F_.x_slice_min_) / scfg_.rp_F_.x_slice_w_; + if (idx >= 0 && idx < scfg_.rp_F_.x_slice_n_) { x_slice_plots_F[idx].h_y->Fill(trDw.y()); x_slice_plots_F[idx].p_y_diffFN_vs_y->Fill(trDw.y(), trDw.y() - trUp.y()); if (debug) @@ -314,31 +360,4 @@ unsigned int PPSAlignmentWorker::SectorData::process(const CTPPSLocalTrackLiteCo return pairsSelected; } -// -------------------------------- PPSAlignmentWorker methods -------------------------------- - -PPSAlignmentWorker::PPSAlignmentWorker(const edm::ParameterSet &iConfig) - : esTokenBookHistograms_(esConsumes( - edm::ESInputTag("", iConfig.getParameter("label")))), - esTokenAnalyze_(esConsumes( - edm::ESInputTag("", iConfig.getParameter("label")))), - tracksToken_(consumes(iConfig.getParameter("tagTracks"))), - folder_(iConfig.getParameter("folder")), - debug_(iConfig.getParameter("debug")) {} - -void PPSAlignmentWorker::bookHistograms(DQMStore::IBooker &iBooker, edm::Run const &, edm::EventSetup const &iSetup) { - const auto &cfg = iSetup.getData(esTokenBookHistograms_); - - sectorData45.init(iBooker, cfg, cfg.sectorConfig45(), folder_ + "/worker", debug_); - sectorData56.init(iBooker, cfg, cfg.sectorConfig56(), folder_ + "/worker", debug_); -} - -void PPSAlignmentWorker::analyze(const edm::Event &iEvent, const edm::EventSetup &iSetup) { - const auto &tracks = iEvent.get(tracksToken_); - - const auto &cfg = iSetup.getData(esTokenAnalyze_); - - sectorData45.process(tracks, cfg, debug_); - sectorData56.process(tracks, cfg, debug_); -} - -DEFINE_FWK_MODULE(PPSAlignmentWorker); \ No newline at end of file +DEFINE_FWK_MODULE(PPSAlignmentWorker); diff --git a/CalibPPS/AlignmentGlobal/python/ALCARECOPPSAlignment_Output_cff.py b/CalibPPS/AlignmentGlobal/python/ALCARECOPPSAlignment_Output_cff.py new file mode 100644 index 0000000000000..8ff556699bdaf --- /dev/null +++ b/CalibPPS/AlignmentGlobal/python/ALCARECOPPSAlignment_Output_cff.py @@ -0,0 +1,13 @@ +import FWCore.ParameterSet.Config as cms + +OutALCARECOPPSAlignment_noDrop = cms.PSet( + SelectEvents = cms.untracked.PSet( + SelectEvents = cms.vstring('pathALCARECOPPSAlignment') + ), + outputCommands = cms.untracked.vstring( + 'keep *_MEtoEDMConvertPPSAlignment_*_*', + ) +) + +OutALCARECOPPSAlignment = OutALCARECOPPSAlignment_noDrop.clone() +OutALCARECOPPSAlignment.outputCommands.insert(0, 'drop *') diff --git a/CalibPPS/AlignmentGlobal/python/ALCARECOPPSAlignment_cff.py b/CalibPPS/AlignmentGlobal/python/ALCARECOPPSAlignment_cff.py new file mode 100644 index 0000000000000..3b01706270500 --- /dev/null +++ b/CalibPPS/AlignmentGlobal/python/ALCARECOPPSAlignment_cff.py @@ -0,0 +1,16 @@ +import FWCore.ParameterSet.Config as cms + +from CalibPPS.AlignmentGlobal.ppsAlignmentWorker_cfi import ppsAlignmentWorker + +MEtoEDMConvertPPSAlignment = cms.EDProducer('MEtoEDMConverter', + Name=cms.untracked.string('MEtoEDMConverter'), + Verbosity=cms.untracked.int32(0), + Frequency=cms.untracked.int32(50), + MEPathToSave=cms.untracked.string('AlCaReco/PPSAlignment'), + deleteAfterCopy=cms.untracked.bool(True) +) + +taskALCARECOPPSAlignment = cms.Task( + ppsAlignmentWorker, + MEtoEDMConvertPPSAlignment +) diff --git a/CalibPPS/AlignmentGlobal/python/PPSAlignmentHarvester_cff.py b/CalibPPS/AlignmentGlobal/python/PPSAlignmentHarvester_cff.py new file mode 100644 index 0000000000000..91eb94a8e40e8 --- /dev/null +++ b/CalibPPS/AlignmentGlobal/python/PPSAlignmentHarvester_cff.py @@ -0,0 +1,25 @@ +import FWCore.ParameterSet.Config as cms +from DQMServices.Components.EDMtoMEConverter_cfi import EDMtoMEConverter + +from CalibPPS.AlignmentGlobal.ppsAlignmentHarvester_cfi import ppsAlignmentHarvester as ppsAlignmentHarvester_ + +EDMtoMEConvertPPSAlignment = EDMtoMEConverter.clone() +EDMtoMEConvertPPSAlignment.lumiInputTag = cms.InputTag("MEtoEDMConvertPPSAlignment", "MEtoEDMConverterLumi") +EDMtoMEConvertPPSAlignment.runInputTag = cms.InputTag("MEtoEDMConvertPPSAlignment", "MEtoEDMConverterRun") + +from DQMServices.Core.DQMEDHarvester import DQMEDHarvester +DQMInfoPPSAlignment = DQMEDHarvester('DQMHarvestingMetadata', + subSystemFolder=cms.untracked.string('AlCaReco') + ) + +ppsAlignmentHarvester = ppsAlignmentHarvester_.clone() +ppsAlignmentHarvester.text_results_path = cms.string("") +ppsAlignmentHarvester.write_sqlite_results = cms.bool(True) +ppsAlignmentHarvester.x_ali_rel_final_slope_fixed = cms.bool(False) +ppsAlignmentHarvester.y_ali_final_slope_fixed = cms.bool(False) + +ALCAHARVESTPPSAlignment = cms.Task( + EDMtoMEConvertPPSAlignment, + DQMInfoPPSAlignment, + ppsAlignmentHarvester +) diff --git a/CalibPPS/AlignmentGlobal/python/ppsAlignmentHarvester_cfi.py b/CalibPPS/AlignmentGlobal/python/ppsAlignmentHarvester_cfi.py deleted file mode 100644 index 35214114e8d3d..0000000000000 --- a/CalibPPS/AlignmentGlobal/python/ppsAlignmentHarvester_cfi.py +++ /dev/null @@ -1,7 +0,0 @@ -import FWCore.ParameterSet.Config as cms -from DQMServices.Core.DQMEDHarvester import DQMEDHarvester - -ppsAlignmentHarvester = DQMEDHarvester("PPSAlignmentHarvester", - folder = cms.string("CalibPPS/Common"), - debug = cms.bool(True) -) \ No newline at end of file diff --git a/CalibPPS/AlignmentGlobal/python/ppsAlignmentWorker_cfi.py b/CalibPPS/AlignmentGlobal/python/ppsAlignmentWorker_cfi.py deleted file mode 100644 index 163a7f943f498..0000000000000 --- a/CalibPPS/AlignmentGlobal/python/ppsAlignmentWorker_cfi.py +++ /dev/null @@ -1,9 +0,0 @@ -import FWCore.ParameterSet.Config as cms -from DQMServices.Core.DQMEDAnalyzer import DQMEDAnalyzer - -ppsAlignmentWorker = DQMEDAnalyzer("PPSAlignmentWorker", - tagTracks = cms.InputTag("ctppsLocalTrackLiteProducer"), - folder = cms.string("CalibPPS/Common"), - label = cms.string(""), - debug = cms.bool(False) -) \ No newline at end of file diff --git a/CalibPPS/AlignmentGlobal/test/README.md b/CalibPPS/AlignmentGlobal/test/README.md index abbfe07f85ada..85392e1bc019a 100644 --- a/CalibPPS/AlignmentGlobal/test/README.md +++ b/CalibPPS/AlignmentGlobal/test/README.md @@ -13,38 +13,47 @@ ## Running instructions ``` -cmsRun run_distributions_reference_cfg.py -cmsRun run_distributions_cfg.py -cmsRun run_analysis_manual_cfg.py +cmsRun run_distributions_reference_cfg.py && cmsRun run_distributions_cfg.py && cmsRun run_analysis_cfg.py ``` -## Expected results -### x_alignment - - RP 3: x = -3690.0 +- 17.9 um - - RP 23: x = -41690.0 +- 17.2 um - - RP 103: x = -2700.0 +- 16.9 um - - RP 123: x = -41830.0 +- 16.0 um - -### x_alignment_relative: - - RP 3: x = 18985.6 +- 1.0 um - - RP 23: x = -18985.6 +- 1.0 um - - RP 103: x = 19484.1 +- 1.2 um - - RP 123: x = -19484.1 +- 1.2 um - -### x_alignment_relative_sl_fix: - - RP 3: x = 18983.7 +- 0.2 um - - RP 23: x = -18983.7 +- 0.2 um - - RP 103: x = 19486.6 +- 0.3 um - - RP 123: x = -19486.6 +- 0.3 um - -### y_alignment: - - RP 3: y = 3468.8 +- 44.1 um - - RP 23: y = 4097.6 +- 44.8 um - - RP 103: y = 3025.5 +- 77.8 um - - RP 123: y = 3344.0 +- 66.1 um - -### y_alignment_sl_fix: - - RP 3: y = 3491.7 +- 10.7 um - - RP 23: y = 4167.4 +- 11.6 um - - RP 103: y = 2753.5 +- 18.2 um - - RP 123: y = 3390.2 +- 17.3 um \ No newline at end of file +## Expected results (alignment_results.txt) +``` +1: x_alignment: +RP 3: shift (um) x = -3670.0 +- 19.8, y = 0.0 +- 0.0, z = 0.0 +- 0.0, rotation (mrad) x = 0.0 +- 0.0, y = 0.0 +- 0.0, z = 0.0 +- 0.0 +RP 23: shift (um) x = -41710.0 +- 20.6, y = 0.0 +- 0.0, z = 0.0 +- 0.0, rotation (mrad) x = 0.0 +- 0.0, y = 0.0 +- 0.0, z = 0.0 +- 0.0 +RP 103: shift (um) x = -2700.0 +- 18.8, y = 0.0 +- 0.0, z = 0.0 +- 0.0, rotation (mrad) x = 0.0 +- 0.0, y = 0.0 +- 0.0, z = 0.0 +- 0.0 +RP 123: shift (um) x = -41840.0 +- 19.5, y = 0.0 +- 0.0, z = 0.0 +- 0.0, rotation (mrad) x = 0.0 +- 0.0, y = 0.0 +- 0.0, z = 0.0 +- 0.0 + + +2: x_alignment_relative: +RP 3: shift (um) x = 18984.6 +- 1.2, y = 0.0 +- 0.0, z = 0.0 +- 0.0, rotation (mrad) x = 0.0 +- 0.0, y = 0.0 +- 0.0, z = 0.0 +- 0.0 +RP 23: shift (um) x = -18984.6 +- 1.2, y = 0.0 +- 0.0, z = 0.0 +- 0.0, rotation (mrad) x = 0.0 +- 0.0, y = 0.0 +- 0.0, z = 0.0 +- 0.0 +RP 103: shift (um) x = 19485.3 +- 1.5, y = 0.0 +- 0.0, z = 0.0 +- 0.0, rotation (mrad) x = 0.0 +- 0.0, y = 0.0 +- 0.0, z = 0.0 +- 0.0 +RP 123: shift (um) x = -19485.3 +- 1.5, y = 0.0 +- 0.0, z = 0.0 +- 0.0, rotation (mrad) x = 0.0 +- 0.0, y = 0.0 +- 0.0, z = 0.0 +- 0.0 + +2: x_alignment_relative_sl_fix: +RP 3: shift (um) x = 18983.8 +- 0.3, y = 0.0 +- 0.0, z = 0.0 +- 0.0, rotation (mrad) x = 0.0 +- 0.0, y = 0.0 +- 0.0, z = 0.0 +- 0.0 +RP 23: shift (um) x = -18983.8 +- 0.3, y = 0.0 +- 0.0, z = 0.0 +- 0.0, rotation (mrad) x = 0.0 +- 0.0, y = 0.0 +- 0.0, z = 0.0 +- 0.0 +RP 103: shift (um) x = 19486.8 +- 0.3, y = 0.0 +- 0.0, z = 0.0 +- 0.0, rotation (mrad) x = 0.0 +- 0.0, y = 0.0 +- 0.0, z = 0.0 +- 0.0 +RP 123: shift (um) x = -19486.8 +- 0.3, y = 0.0 +- 0.0, z = 0.0 +- 0.0, rotation (mrad) x = 0.0 +- 0.0, y = 0.0 +- 0.0, z = 0.0 +- 0.0 + + +3: y_alignment: +RP 3: shift (um) x = 0.0 +- 0.0, y = 3443.3 +- 101.7, z = 0.0 +- 0.0, rotation (mrad) x = 0.0 +- 0.0, y = 0.0 +- 0.0, z = 0.0 +- 0.0 +RP 23: shift (um) x = 0.0 +- 0.0, y = 4190.3 +- 87.0, z = 0.0 +- 0.0, rotation (mrad) x = 0.0 +- 0.0, y = 0.0 +- 0.0, z = 0.0 +- 0.0 +RP 103: shift (um) x = 0.0 +- 0.0, y = 2885.9 +- 66.2, z = 0.0 +- 0.0, rotation (mrad) x = 0.0 +- 0.0, y = 0.0 +- 0.0, z = 0.0 +- 0.0 +RP 123: shift (um) x = 0.0 +- 0.0, y = 3491.8 +- 129.5, z = 0.0 +- 0.0, rotation (mrad) x = 0.0 +- 0.0, y = 0.0 +- 0.0, z = 0.0 +- 0.0 + +3: y_alignment_sl_fix: +RP 3: shift (um) x = 0.0 +- 0.0, y = 3490.3 +- 16.0, z = 0.0 +- 0.0, rotation (mrad) x = 0.0 +- 0.0, y = 0.0 +- 0.0, z = 0.0 +- 0.0 +RP 23: shift (um) x = 0.0 +- 0.0, y = 4209.1 +- 15.8, z = 0.0 +- 0.0, rotation (mrad) x = 0.0 +- 0.0, y = 0.0 +- 0.0, z = 0.0 +- 0.0 +RP 103: shift (um) x = 0.0 +- 0.0, y = 2751.2 +- 16.1, z = 0.0 +- 0.0, rotation (mrad) x = 0.0 +- 0.0, y = 0.0 +- 0.0, z = 0.0 +- 0.0 +RP 123: shift (um) x = 0.0 +- 0.0, y = 3417.9 +- 23.9, z = 0.0 +- 0.0, rotation (mrad) x = 0.0 +- 0.0, y = 0.0 +- 0.0, z = 0.0 +- 0.0 + + +final merged results: +RP 3: shift (um) x = -3706.2 +- 19.8, y = 3490.3 +- 16.0, z = 0.0 +- 0.0, rotation (mrad) x = 0.0 +- 0.0, y = 0.0 +- 0.0, z = 0.0 +- 0.0 +RP 23: shift (um) x = -41673.8 +- 20.6, y = 4209.1 +- 15.8, z = 0.0 +- 0.0, rotation (mrad) x = 0.0 +- 0.0, y = 0.0 +- 0.0, z = 0.0 +- 0.0 +RP 103: shift (um) x = -2783.2 +- 18.8, y = 2751.2 +- 16.1, z = 0.0 +- 0.0, rotation (mrad) x = 0.0 +- 0.0, y = 0.0 +- 0.0, z = 0.0 +- 0.0 +RP 123: shift (um) x = -41756.8 +- 19.5, y = 3417.9 +- 23.9, z = 0.0 +- 0.0, rotation (mrad) x = 0.0 +- 0.0, y = 0.0 +- 0.0, z = 0.0 +- 0.0 +``` diff --git a/CalibPPS/AlignmentGlobal/test/config_cff.py b/CalibPPS/AlignmentGlobal/test/config_cff.py index 4c8130f8f16ad..50e7763fdf1f4 100644 --- a/CalibPPS/AlignmentGlobal/test/config_cff.py +++ b/CalibPPS/AlignmentGlobal/test/config_cff.py @@ -1,12 +1,6 @@ import FWCore.ParameterSet.Config as cms -ppsAlignmentConfigESSource = cms.ESSource("PPSAlignmentConfigESSource", - sequence = cms.vstring( - "x_alignment", - "x_alignment_relative", - "y_alignment" - ), - +ppsAlignmentConfigESSource = cms.ESSource("PPSAlignmentConfigurationESSource", sector_45 = cms.PSet( rp_N = cms.PSet( x_max_fit_mode = cms.double(7.0), @@ -39,5 +33,17 @@ cut_h_c = cms.double(-39.26 + 0.33), cut_v_c = cms.double(1.49 - 1.80) + ), + + y_alignment = cms.PSet( + rp_L_F = cms.PSet( + x_min = cms.double(45.5) + ), + rp_L_N = cms.PSet( + x_min = cms.double(7.8) + ), + rp_R_F = cms.PSet( + x_min = cms.double(45.5) + ) ) -) \ No newline at end of file +) diff --git a/CalibPPS/AlignmentGlobal/test/config_reference_cff.py b/CalibPPS/AlignmentGlobal/test/config_reference_cff.py index f925b48787127..f2ee40ad3a18b 100644 --- a/CalibPPS/AlignmentGlobal/test/config_reference_cff.py +++ b/CalibPPS/AlignmentGlobal/test/config_reference_cff.py @@ -1,6 +1,6 @@ import FWCore.ParameterSet.Config as cms -ppsAlignmentConfigESSource = cms.ESSource("PPSAlignmentConfigESSource", +ppsAlignmentConfigESSource = cms.ESSource("PPSAlignmentConfigurationESSource", label = cms.string('reference'), sector_45 = cms.PSet( diff --git a/CalibPPS/AlignmentGlobal/test/run_analysis_cfg.py b/CalibPPS/AlignmentGlobal/test/run_analysis_cfg.py new file mode 100644 index 0000000000000..fceb4d3fab1c1 --- /dev/null +++ b/CalibPPS/AlignmentGlobal/test/run_analysis_cfg.py @@ -0,0 +1,111 @@ +########## Configuration ########## +# if set to True, a file with logs will be produced. +produce_logs = True + +# if set to True, the harvester will produce an extra ROOT file with some debug plots. +# Works only for one-run input. +harvester_debug = True + +# Path for a ROOT file with the histograms. +input_distributions = 'file:dqm_run_distributions_test.root' + +# Reference dataset path. +reference_dataset_path = 'DQM_V0001_CalibPPS_R000314273.root' + +# If set to True, the results will be also written to an SQLite file. +write_sqlite_results = False + +# Output database. Used only if write_sqlite_results is set to True. +output_conditions = 'sqlite_file:alignment_results.db' + +# Database tag. Used only if write_sqlite_results is set to True. +output_db_tag = 'CTPPSRPAlignmentCorrectionsData_test' +################################### + +import sys +import os +import FWCore.ParameterSet.Config as cms + +process = cms.Process('testDistributions') + +process.load('FWCore.MessageService.MessageLogger_cfi') +process.load("DQMServices.Core.DQMStore_cfi") +process.load("CalibPPS.AlignmentGlobal.ppsAlignmentHarvester_cfi") + +if harvester_debug: + process.ppsAlignmentHarvester.debug = cms.bool(True) + +# Message Logger +if produce_logs: + process.MessageLogger = cms.Service("MessageLogger", + destinations = cms.untracked.vstring('run_analysis', + 'cout' + ), + run_analysis = cms.untracked.PSet( + threshold = cms.untracked.string("INFO") + ), + cout = cms.untracked.PSet( + threshold = cms.untracked.string('WARNING') + ) + ) +else: + process.MessageLogger = cms.Service("MessageLogger", + destinations = cms.untracked.vstring('cout'), + cout = cms.untracked.PSet( + threshold = cms.untracked.string('WARNING') + ) + ) + +# load DQM framework +process.load("DQMServices.Components.DQMEnvironment_cfi") +process.dqmEnv.subSystemFolder = "CalibPPS" +process.dqmSaver.convention = 'Offline' +process.dqmSaver.workflow = "/CalibPPS/AlignmentGlobal/CMSSW_12_1_0_pre1" +process.dqmSaver.saveByRun = -1 +process.dqmSaver.saveAtJobEnd = True +process.dqmSaver.forceRunNumber = 999999 + +# Source (histograms) +process.source = cms.Source("DQMRootSource", + fileNames = cms.untracked.vstring(input_distributions), +) + +# Event Setup (test) +from config_cff import ppsAlignmentConfigESSource as ppsAlignmentConfigESSourceTest +process.ppsAlignmentConfigESSourceTest = ppsAlignmentConfigESSourceTest + +# Event Setup (reference) +from config_reference_cff import ppsAlignmentConfigESSource as ppsAlignmentConfigESSourceReference +ppsAlignmentConfigESSourceReference.matching = cms.PSet( + reference_dataset = cms.string(reference_dataset_path) +) +process.ppsAlignmentConfigESSourceReference = ppsAlignmentConfigESSourceReference + +# SQLite results +if write_sqlite_results: + process.load("CondCore.CondDB.CondDB_cfi") + process.CondDB.connect = output_conditions + process.PoolDBOutputService = cms.Service("PoolDBOutputService", + process.CondDB, + timetype = cms.untracked.string('runnumber'), + toPut = cms.VPSet(cms.PSet( + record = cms.string('CTPPSRPAlignmentCorrectionsDataRcd'), + tag = cms.string(output_db_tag) + )) + ) + + # DB object maker parameters + process.ppsAlignmentHarvester.write_sqlite_results = cms.bool(True) + +process.path = cms.Path( + process.ppsAlignmentHarvester +) + +process.end_path = cms.EndPath( + process.dqmSaver +) + +process.schedule = cms.Schedule( + process.path, + process.end_path +) diff --git a/CalibPPS/AlignmentGlobal/test/run_analysis_manual_cfg.py b/CalibPPS/AlignmentGlobal/test/run_analysis_manual_cfg.py deleted file mode 100644 index a2537d6d3ea04..0000000000000 --- a/CalibPPS/AlignmentGlobal/test/run_analysis_manual_cfg.py +++ /dev/null @@ -1,58 +0,0 @@ -import sys -import os -import FWCore.ParameterSet.Config as cms - -from config_cff import ppsAlignmentConfigESSource as ppsAlignmentConfigESSourceTest -from config_reference_cff import ppsAlignmentConfigESSource as ppsAlignmentConfigESSourceReference -ppsAlignmentConfigESSourceReference.matching = cms.PSet( - reference_dataset = cms.string("DQM_V0001_CalibPPS_R000314273.root") -) - -process = cms.Process('testDistributions') - -process.load('FWCore.MessageService.MessageLogger_cfi') -process.load("DQMServices.Core.DQMStore_cfi") -process.load("CalibPPS.AlignmentGlobal.ppsAlignmentHarvester_cfi") - -process.MessageLogger = cms.Service("MessageLogger", - destinations = cms.untracked.vstring(# 'run_analysis_manual', - 'cout' - ), - # run_analysis_manual = cms.untracked.PSet( - # threshold = cms.untracked.string("INFO") - # ), - cout = cms.untracked.PSet( - threshold = cms.untracked.string('WARNING') - ) -) - -# load DQM framework -process.load("DQMServices.Components.DQMEnvironment_cfi") -process.dqmEnv.subSystemFolder = "CalibPPS" -process.dqmSaver.convention = 'Offline' -process.dqmSaver.workflow = "/CalibPPS/AlignmentGlobal/CMSSW_11_2_0_pre6" -process.dqmSaver.saveByRun = -1 -process.dqmSaver.saveAtJobEnd = True -process.dqmSaver.forceRunNumber = 999999 - -process.source = cms.Source("DQMRootSource", - fileNames = cms.untracked.vstring( - "file:dqm_run_distributions_test.root" - ), -) - -process.ppsAlignmentConfigESSourceReference = ppsAlignmentConfigESSourceReference -process.ppsAlignmentConfigESSourceTest = ppsAlignmentConfigESSourceTest - -process.path = cms.Path( - process.ppsAlignmentHarvester -) - -process.end_path = cms.EndPath( - process.dqmSaver -) - -process.schedule = cms.Schedule( - process.path, - process.end_path -) \ No newline at end of file diff --git a/CalibPPS/AlignmentGlobal/test/run_distributions_cfg.py b/CalibPPS/AlignmentGlobal/test/run_distributions_cfg.py index 3a029259a1fbe..3b841ed477084 100644 --- a/CalibPPS/AlignmentGlobal/test/run_distributions_cfg.py +++ b/CalibPPS/AlignmentGlobal/test/run_distributions_cfg.py @@ -1,7 +1,14 @@ +########## Configuration ########## +# if set to True, a file with logs will be produced. +produce_logs = False + +# Path for a ROOT file with the histograms +output_distributions = 'dqm_run_distributions_test.root' +################################### + import FWCore.ParameterSet.Config as cms from input_files_cff import input_files -from config_cff import ppsAlignmentConfigESSource process = cms.Process('testDistributions') @@ -10,39 +17,50 @@ process.load("DQMServices.Core.DQMStore_cfi") # Message Logger -process.MessageLogger = cms.Service("MessageLogger", - destinations = cms.untracked.vstring(# 'run_distributions', - 'cout' - ), - # run_distributions = cms.untracked.PSet( - # threshold = cms.untracked.string("INFO") - # ), - cout = cms.untracked.PSet( - threshold = cms.untracked.string('WARNING') - ) -) +if produce_logs: + process.MessageLogger = cms.Service("MessageLogger", + destinations = cms.untracked.vstring('run_distributions', + 'cout' + ), + run_distributions = cms.untracked.PSet( + threshold = cms.untracked.string("INFO") + ), + cout = cms.untracked.PSet( + threshold = cms.untracked.string('WARNING') + ) + ) +else: + process.MessageLogger = cms.Service("MessageLogger", + destinations = cms.untracked.vstring('cout'), + cout = cms.untracked.PSet( + threshold = cms.untracked.string('WARNING') + ) + ) +# Source process.source = cms.Source("PoolSource", - fileNames = input_files + fileNames = input_files ) process.maxEvents = cms.untracked.PSet(input = cms.untracked.int32(-1)) # Event Setup +from config_cff import ppsAlignmentConfigESSource process.ppsAlignmentConfigESSource = ppsAlignmentConfigESSource +# Output for the histograms process.dqmOutput = cms.OutputModule("DQMRootOutputModule", - fileName = cms.untracked.string("dqm_run_distributions_test.root") + fileName = cms.untracked.string(output_distributions) ) process.path = cms.Path( - process.ppsAlignmentWorker + process.ppsAlignmentWorker ) process.end_path = cms.EndPath( - process.dqmOutput + process.dqmOutput ) process.schedule = cms.Schedule( - process.path, - process.end_path -) \ No newline at end of file + process.path, + process.end_path +) diff --git a/CalibPPS/AlignmentGlobal/test/run_distributions_reference_cfg.py b/CalibPPS/AlignmentGlobal/test/run_distributions_reference_cfg.py index 7d15ba881b38d..d691ada99a77d 100644 --- a/CalibPPS/AlignmentGlobal/test/run_distributions_reference_cfg.py +++ b/CalibPPS/AlignmentGlobal/test/run_distributions_reference_cfg.py @@ -1,7 +1,14 @@ +########## Configuration ########## +# if set to True, a file with logs will be produced. +produce_logs = False + +# Source max processed events +max_events = 1000000 +################################### + import FWCore.ParameterSet.Config as cms from input_files_reference_cff import input_files -from config_reference_cff import ppsAlignmentConfigESSource process = cms.Process('referenceDistributions') @@ -10,33 +17,43 @@ process.load("DQMServices.Core.DQMStore_cfi") # Message Logger -process.MessageLogger = cms.Service("MessageLogger", - destinations = cms.untracked.vstring(# 'run_distributions', - 'cout' - ), - # run_distributions = cms.untracked.PSet( - # threshold = cms.untracked.string("INFO") - # ), - cout = cms.untracked.PSet( - threshold = cms.untracked.string('WARNING') - ) -) - -# load DQM framework -process.load("DQM.Integration.config.environment_cfi") -process.dqmEnv.subSystemFolder = "CalibPPS" -process.dqmSaver.path = "" -process.dqmSaver.tag = "CalibPPS" +if produce_logs: + process.MessageLogger = cms.Service("MessageLogger", + destinations = cms.untracked.vstring('run_distributions', + 'cout' + ), + run_distributions = cms.untracked.PSet( + threshold = cms.untracked.string("INFO") + ), + cout = cms.untracked.PSet( + threshold = cms.untracked.string('WARNING') + ) + ) +else: + process.MessageLogger = cms.Service("MessageLogger", + destinations = cms.untracked.vstring('cout'), + cout = cms.untracked.PSet( + threshold = cms.untracked.string('WARNING') + ) + ) +# Source process.source = cms.Source("PoolSource", fileNames = input_files ) -process.maxEvents = cms.untracked.PSet(input = cms.untracked.int32(2000000)) +process.maxEvents = cms.untracked.PSet(input = cms.untracked.int32(max_events)) # Event Setup +from config_reference_cff import ppsAlignmentConfigESSource process.ppsAlignmentConfigESSource = ppsAlignmentConfigESSource -# Worker config label +# load DQM framework +process.load("DQM.Integration.config.environment_cfi") +process.dqmEnv.subSystemFolder = "CalibPPS" +process.dqmSaver.path = "" +process.dqmSaver.tag = "CalibPPS" + +# Worker config label (for ES product label) process.ppsAlignmentWorker.label = cms.string("reference") process.path = cms.Path( @@ -50,4 +67,4 @@ process.schedule = cms.Schedule( process.path, process.end_path -) \ No newline at end of file +) diff --git a/CalibPPS/ESProducers/python/ppsTopology_cff.py b/CalibPPS/ESProducers/python/ppsTopology_cff.py index 6e63e2b4a7a5d..aca95af3fccac 100644 --- a/CalibPPS/ESProducers/python/ppsTopology_cff.py +++ b/CalibPPS/ESProducers/python/ppsTopology_cff.py @@ -6,4 +6,4 @@ from Configuration.Eras.Modifier_ctpps_2017_cff import ctpps_2017 from Configuration.Eras.Modifier_ctpps_2018_cff import ctpps_2018 -(ctpps_2016 | ctpps_2017 | ctpps_2018).toModify(ppsPixelTopologyESSource, RunType = cms.string('Run2'), simYWidth = cms.double(24.4) ) +(ctpps_2016 | ctpps_2017 | ctpps_2018).toModify(ppsPixelTopologyESSource, RunType = cms.string('Run2'), simYWidth = cms.double(24.4), noOfPixelSimY = cms.int32(156), noOfPixels = cms.int32(24960)) diff --git a/CalibPPS/TimingCalibration/plugins/PPSDiamondSampicTimingCalibrationPCLHarvester.cc b/CalibPPS/TimingCalibration/plugins/PPSDiamondSampicTimingCalibrationPCLHarvester.cc index ed66659cc760a..b711b5e7abf02 100644 --- a/CalibPPS/TimingCalibration/plugins/PPSDiamondSampicTimingCalibrationPCLHarvester.cc +++ b/CalibPPS/TimingCalibration/plugins/PPSDiamondSampicTimingCalibrationPCLHarvester.cc @@ -257,7 +257,7 @@ void PPSDiamondSampicTimingCalibrationPCLHarvester::calibDb(DQMStore::IGetter& i auto calibPPS = PPSTimingCalibration(formula, params, time_info); // write the object edm::Service poolDbService; - poolDbService->writeOne(&calibPPS, poolDbService->currentTime(), "PPSTimingCalibrationRcd"); + poolDbService->writeOneIOV(calibPPS, poolDbService->currentTime(), "PPSTimingCalibrationRcd"); } //------------------------------------------------------------------------------ @@ -287,4 +287,4 @@ void PPSDiamondSampicTimingCalibrationPCLHarvester::fillDescriptions(edm::Config descriptions.add("PPSDiamondSampicTimingCalibrationPCLHarvester", desc); } -DEFINE_FWK_MODULE(PPSDiamondSampicTimingCalibrationPCLHarvester); \ No newline at end of file +DEFINE_FWK_MODULE(PPSDiamondSampicTimingCalibrationPCLHarvester); diff --git a/CalibPPS/TimingCalibration/python/ALCARECOPPSCalTrackBasedSel_Output_cff.py b/CalibPPS/TimingCalibration/python/ALCARECOPPSCalTrackBasedSel_Output_cff.py index 20bee7ec6c60e..6a4171db20554 100644 --- a/CalibPPS/TimingCalibration/python/ALCARECOPPSCalTrackBasedSel_Output_cff.py +++ b/CalibPPS/TimingCalibration/python/ALCARECOPPSCalTrackBasedSel_Output_cff.py @@ -7,9 +7,8 @@ outputCommands = cms.untracked.vstring( 'keep *_ALCARECOPPSCalTrackBasedSel_*_*', 'keep *_ctppsDiamondRawToDigi_*_*', - 'keep *_totemTimingRawToDigi_*_*' - - # will be updated to add the spatial alignment required collections + 'keep *_totemTimingRawToDigi_*_*', + 'keep *_ctppsLocalTrackLiteProducer_*_*' ) ) diff --git a/CalibPPS/TimingCalibration/python/ALCARECOPPSCalTrackBasedSel_cff.py b/CalibPPS/TimingCalibration/python/ALCARECOPPSCalTrackBasedSel_cff.py index 27ad42bb7d8db..f92dda0ee8030 100644 --- a/CalibPPS/TimingCalibration/python/ALCARECOPPSCalTrackBasedSel_cff.py +++ b/CalibPPS/TimingCalibration/python/ALCARECOPPSCalTrackBasedSel_cff.py @@ -15,27 +15,31 @@ # select events passing the filter on pixel tracks from HLTrigger.special.hltPPSPerPotTrackFilter_cfi import hltPPSPerPotTrackFilter as _filter -hltPPSPerPotTrackFilter = _filter.clone( +hltPPSPerPotTrackFilter_45 = _filter.clone( pixelFilter = cms.VPSet( cms.PSet( # sector 45, near pot detid = cms.uint32(2022703104), minTracks = cms.int32(1), - maxTracks = cms.int32(6), + maxTracks = cms.int32(1), ), cms.PSet( # sector 45, far pot detid = cms.uint32(2023227392), minTracks = cms.int32(1), - maxTracks = cms.int32(6), + maxTracks = cms.int32(1), ), + ) +) +hltPPSPerPotTrackFilter_56 = _filter.clone( + pixelFilter = cms.VPSet( cms.PSet( # sector 56, near pot detid = cms.uint32(2039480320), minTracks = cms.int32(1), - maxTracks = cms.int32(6), + maxTracks = cms.int32(1), ), cms.PSet( # sector 56, far pot detid = cms.uint32(2040004608), minTracks = cms.int32(1), - maxTracks = cms.int32(6), + maxTracks = cms.int32(1), ), ) ) @@ -44,5 +48,5 @@ ctppsRawToDigi * recoCTPPS * ALCARECOPPSCalTrackBasedSelHLT * - hltPPSPerPotTrackFilter + (hltPPSPerPotTrackFilter_45 + hltPPSPerPotTrackFilter_56) ) diff --git a/CalibTracker/SiPixelESProducers/src/SiPixelGainCalibrationForHLTService.cc b/CalibTracker/SiPixelESProducers/src/SiPixelGainCalibrationForHLTService.cc index b5700ff664f17..de8d660210f33 100644 --- a/CalibTracker/SiPixelESProducers/src/SiPixelGainCalibrationForHLTService.cc +++ b/CalibTracker/SiPixelESProducers/src/SiPixelGainCalibrationForHLTService.cc @@ -38,8 +38,7 @@ void SiPixelGainCalibrationForHLTService::calibrate( if (isDeadColumn | isNoisyColumn) electron[i++] = 0; else { - float vcal = di->adc() * gain - pedestal * gain; - // float vcal = (di->adc() - DBpedestal) * DBgain; + float vcal = float(di->adc()) * gain - pedestal * gain; electron[i++] = int(vcal * conversionFactor + offset); } } diff --git a/CalibTracker/SiPixelESProducers/src/SiPixelGainCalibrationService.cc b/CalibTracker/SiPixelESProducers/src/SiPixelGainCalibrationService.cc index 9f055401fc051..11b202c057eb6 100644 --- a/CalibTracker/SiPixelESProducers/src/SiPixelGainCalibrationService.cc +++ b/CalibTracker/SiPixelESProducers/src/SiPixelGainCalibrationService.cc @@ -28,8 +28,7 @@ void SiPixelGainCalibrationServiceBase::calibrate( else { float DBgain = getGain(detID, col, row); float DBpedestal = getPedestal(detID, col, row) * DBgain; - float vcal = di->adc() * DBgain - DBpedestal; - // float vcal = (di->adc() - DBpedestal) * DBgain; + float vcal = float(di->adc()) * DBgain - DBpedestal; electron[i++] = int(vcal * conversionFactor + offset); } } diff --git a/CalibTracker/SiStripChannelGain/src/SiStripGainsPCLHarvester.cc b/CalibTracker/SiStripChannelGain/src/SiStripGainsPCLHarvester.cc index eda8165453ba5..2bc536bb90cfe 100644 --- a/CalibTracker/SiStripChannelGain/src/SiStripGainsPCLHarvester.cc +++ b/CalibTracker/SiStripChannelGain/src/SiStripGainsPCLHarvester.cc @@ -133,7 +133,7 @@ void SiStripGainsPCLHarvester::dqmEndJob(DQMStore::IBooker& ibooker_, DQMStore:: if (doStoreOnDB) { if (poolDbService.isAvailable()) - poolDbService->writeOne(theAPVGains.get(), poolDbService->currentTime(), m_Record); + poolDbService->writeOneIOV(*theAPVGains, poolDbService->currentTime(), m_Record); else throw std::runtime_error("PoolDBService required."); } else { diff --git a/CalibTracker/SiStripChannelGain/test/7TeVData/automatic_RunOnCalibTree.py b/CalibTracker/SiStripChannelGain/test/7TeVData/automatic_RunOnCalibTree.py index 6ccac67140a6a..256a26e0c086c 100644 --- a/CalibTracker/SiStripChannelGain/test/7TeVData/automatic_RunOnCalibTree.py +++ b/CalibTracker/SiStripChannelGain/test/7TeVData/automatic_RunOnCalibTree.py @@ -1,9 +1,9 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 from __future__ import print_function import os,sys import getopt -import commands +import subprocess import time import ROOT import urllib @@ -82,7 +82,7 @@ def numberOfEvents(file,mode): #identify last run of the previous calibration if(firstRun<=0): - out = commands.getstatusoutput("ls /afs/cern.ch/cms/tracker/sistrvalidation/WWW/CalibrationValidation/ParticleGain/ | grep Run_ | tail -n 1"); + out = subprocess.getstatusoutput("ls /afs/cern.ch/cms/tracker/sistrvalidation/WWW/CalibrationValidation/ParticleGain/ | grep Run_ | tail -n 1"); firstRun = int(out[1].split('_')[3])+1 print("firstRun set to " +str(firstRun)) print() @@ -104,7 +104,7 @@ def numberOfEvents(file,mode): if(usePCL==True): print("Get the list of PCL output files from DAS") print(initEnv+"das_client.py --limit=9999 --query='dataset=%s'"%PCLDATASET) - dasOutput = commands.getstatusoutput(initEnv+"das_client.py --limit=9999 --query='dataset=%s'"%PCLDATASET)[1] + dasOutput = subprocess.getstatusoutput(initEnv+"das_client.py --limit=9999 --query='dataset=%s'"%PCLDATASET)[1] datasets = [ line for line in dasOutput.splitlines() if not line.startswith('Showing') and 'SCRAM fatal' not in line and len(line)>0 ] print(datasets) @@ -117,7 +117,7 @@ def numberOfEvents(file,mode): runs = [] for dataset in datasets: - runs += [ (dataset, line) for line in commands.getstatusoutput(initEnv+ + runs += [ (dataset, line) for line in subprocess.getstatusoutput(initEnv+ "das_client.py --limit=9999 --query='run dataset=%s'"%dataset)[1].splitlines() if not line.startswith('Showing') and 'SCRAM fatal' not in line and len(line)>0 ] if len( runs )==0 or 'Error' in " ".join(datasets): @@ -136,7 +136,7 @@ def numberOfEvents(file,mode): sys.stdout.write( 'Gathering infos for RUN %i: ' % run ) #check the events available for this run - NEventsDasOut = [ line for line in commands.getstatusoutput(initEnv+ + NEventsDasOut = [ line for line in subprocess.getstatusoutput(initEnv+ "das_client.py --limit=9999 --query='summary dataset=%s run=%i | grep summary.nevents'"%(dataset,run))[1].splitlines() if not line.startswith('Showing') and 'SCRAM fatal' not in line and len(line)>0 ][-1] if(not NEventsDasOut.isdigit() ): @@ -152,7 +152,7 @@ def numberOfEvents(file,mode): continue FileList+="#run=" + str(run) + " --> NEvents="+str(NEvents/1000).rjust(8)+"K\n" - resultsFiles = [ line for line in commands.getstatusoutput(initEnv+ + resultsFiles = [ line for line in subprocess.getstatusoutput(initEnv+ "das_client.py --limit=9999 --query='file dataset=%s run=%i'"%(dataset,run))[1].splitlines() if not line.startswith('Showing') and 'SCRAM fatal' not in line and len(line)>0 ] if len(resultsFiles)==0 or 'Error' in " ".join(resultsFiles): @@ -168,7 +168,7 @@ def numberOfEvents(file,mode): else: print("Get the list of calibTree from castor (eos ls " + CALIBTREEPATH + ")") - calibTreeInfo = commands.getstatusoutput("eos ls -l "+CALIBTREEPATH)[1].split('\n'); + calibTreeInfo = subprocess.getstatusoutput("eos ls -l "+CALIBTREEPATH)[1].split('\n'); print(calibTreeInfo) # collect the list of runs and file size # calibTreeInfo.split()[8] - file name diff --git a/CalibTracker/SiStripChannelGain/test/7TeVData/submitJob.py b/CalibTracker/SiStripChannelGain/test/7TeVData/submitJob.py index 4f814e6420d39..b69851410bf4d 100644 --- a/CalibTracker/SiStripChannelGain/test/7TeVData/submitJob.py +++ b/CalibTracker/SiStripChannelGain/test/7TeVData/submitJob.py @@ -1,9 +1,8 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 from __future__ import print_function import os,sys import getopt -import commands import time import ROOT import urllib diff --git a/CalibTracker/SiStripChannelGain/test/PCL/Launch.py b/CalibTracker/SiStripChannelGain/test/PCL/Launch.py index d4a3efd5023ec..28a13eea2819c 100644 --- a/CalibTracker/SiStripChannelGain/test/PCL/Launch.py +++ b/CalibTracker/SiStripChannelGain/test/PCL/Launch.py @@ -1,17 +1,17 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 from __future__ import print_function import urllib import string import os import sys -import commands +import subprocess DATASET="/MinimumBias/Run2012C-SiStripCalMinBias-v2/ALCARECO" FIRSTRUN=0 #200190 runs = [] -results = sorted(commands.getstatusoutput('dbs search --query="find run,sum(block.numevents) where dataset='+DATASET+' and run>='+str(FIRSTRUN)+'"')[1].splitlines()) +results = sorted(subprocess.getstatusoutput('dbs search --query="find run,sum(block.numevents) where dataset='+DATASET+' and run>='+str(FIRSTRUN)+'"')[1].splitlines()) for line in results: linesplit = line.split(' ') if(len(linesplit)<2):continue @@ -21,18 +21,18 @@ -commands.getstatusoutput('mkdir -p runs') +subprocess.getstatusoutput('mkdir -p runs') for r in runs: initEnv='' initEnv+='cd ' + os.getcwd() + '/runs/'+str(r)+'/;' initEnv+='source /afs/cern.ch/cms/cmsset_default.sh' + ';' initEnv+='eval `scramv1 runtime -sh`;' - commands.getstatusoutput('mkdir -p runs/'+str(r)) + subprocess.getstatusoutput('mkdir -p runs/'+str(r)) print("submitting jobs for run " + str(r)) config_file=open('runs/'+str(r)+'/cmsDriver.sh','w') config_file.write( initEnv + 'cmsDriver.py run'+str(r)+' --datatier ALCARECO --conditions auto:com10 -s ALCA:PromptCalibProdSiStripGains --eventcontent ALCARECO -n -1 --dasquery=\'file dataset=/MinimumBias/Run2012C-SiStripCalMinBias-v2/ALCARECO run='+str(r)+'\' --fileout file:run'+str(r)+'_out.root') config_file.close() - out = commands.getstatusoutput('bsub -q 2nw -J gainPCLrun' + str(r) +' "sh ' + os.getcwd() + '/runs/'+str(r)+'/cmsDriver.sh"') + out = subprocess.getoutput('bsub -q 2nw -J gainPCLrun' + str(r) +' "sh ' + os.getcwd() + '/runs/'+str(r)+'/cmsDriver.sh"') # print('bsub -q 2nw -J gainPCLrun' + str(r) +' " ' + initEnv + 'cmsDriver.py run'+str(r)+' --datatier ALCARECO --conditions auto:com10 -s ALCA:PromptCalibProdSiStripGains --eventcontent ALCARECO -n -1 --dasquery=\'file dataset=/MinimumBias/Run2012C-SiStripCalMinBias-v2/ALCARECO run='+str(r)+'\' --fileout file:run'+str(r)+'_out.root "') diff --git a/CalibTracker/SiStripCommon/test/MakeCalibrationTrees/SubmitJobs.py b/CalibTracker/SiStripCommon/test/MakeCalibrationTrees/SubmitJobs.py index a50b8ac617422..fce16f8dbd9f4 100644 --- a/CalibTracker/SiStripCommon/test/MakeCalibrationTrees/SubmitJobs.py +++ b/CalibTracker/SiStripCommon/test/MakeCalibrationTrees/SubmitJobs.py @@ -1,10 +1,10 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 from __future__ import print_function import urllib import string import os import sys -import commands +import subprocess import time import optparse import submitCalibTree.Config @@ -71,7 +71,7 @@ def mail(STDruns,AAGruns,cleanUpLog): if config.integrity: print("Cleaning up directory...") - cleanUpMessage = commands.getstatusoutput("cd %s; python cleanFolders.py; cd -"%config.RUNDIR)[1] + cleanUpMessage = subprocess.getstatusoutput("cd %s; python cleanFolders.py; cd -"%config.RUNDIR)[1] print(cleanUpMessage) with open("LastRun.txt","r") as lastRun: for line in lastRun: diff --git a/CalibTracker/SiStripCommon/test/MakeCalibrationTrees/submitCalibTree/Config.py b/CalibTracker/SiStripCommon/test/MakeCalibrationTrees/submitCalibTree/Config.py index 494384fb9c687..5cfcdffcee5a9 100644 --- a/CalibTracker/SiStripCommon/test/MakeCalibrationTrees/submitCalibTree/Config.py +++ b/CalibTracker/SiStripCommon/test/MakeCalibrationTrees/submitCalibTree/Config.py @@ -1,6 +1,6 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 from __future__ import print_function -import os, commands,time,sys +import os, time,sys class configuration: datasetPat = '/StreamExpress/Run2018*-SiStripCalMinBias__AAG__-Express-v*/ALCARECO' @@ -73,7 +73,7 @@ def checkIntegrity(self): #Check castor path exists FIXME cmd = self.eosLs.replace("-lrth","")+self.CASTORDIR cmd = cmd[:-2]+"*" - (status,output) = commands.getstatusoutput(cmd) + (status,output) = subprocess.getstatusoutput(cmd) if status or not self.CASTORDIR.split("/")[-1] in output: print(cmd) print(output) diff --git a/CalibTracker/SiStripCommon/test/MakeCalibrationTrees/submitCalibTree/launchJobs.py b/CalibTracker/SiStripCommon/test/MakeCalibrationTrees/submitCalibTree/launchJobs.py index 080c743b93fd6..dd2a02ee61646 100644 --- a/CalibTracker/SiStripCommon/test/MakeCalibrationTrees/submitCalibTree/launchJobs.py +++ b/CalibTracker/SiStripCommon/test/MakeCalibrationTrees/submitCalibTree/launchJobs.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 from __future__ import absolute_import from __future__ import print_function import urllib @@ -6,14 +6,14 @@ import string import os import sys -import commands +import subprocess import time import optparse def dasQuery(query,config): cmd = config.dasClient+" --limit=9999 --query=\"%s\""%query print(cmd) - output = commands.getstatusoutput(config.initEnv+cmd) + output = subprocess.getstatusoutput(config.initEnv+cmd) if output[0]!=0: print("DAS CLIENT ERROR %s"%output[0]) print(output[1]) @@ -183,7 +183,7 @@ def cleanUp(): def checkCorrupted(lastGood, config): calibTreeList = "" print("Get the list of calibTree from" + config.CASTORDIR + ")") - calibTreeInfo = commands.getstatusoutput(config.eosLs +config.CASTORDIR)[1].split('\n'); + calibTreeInfo = subprocess.getstatusoutput(config.eosLs +config.CASTORDIR)[1].split('\n'); NTotalEvents = 0; runList = [] @@ -221,7 +221,7 @@ def checkCorrupted(lastGood, config): # print line #file = "root://eoscms/"+config.CASTORDIR+"/"+subParts[-1] #print("Checking " + file) - #results = commands.getstatusoutput(config.initEnv+'root -l -b -q ' + file) + #results = subprocess.getstatusoutput(config.initEnv+'root -l -b -q ' + file) #if(len(results[1].splitlines())>3): # print(results[1]); # print("add " + str(run) + " to the list of failled runs") @@ -245,7 +245,7 @@ def checkCorrupted(lastGood, config): calibTreeList = "" print("Get the list of calibTree from" + CASTORDIR + ")") - calibTreeInfo = commands.getstatusoutput(initEnv+"eos ls " + CASTORDIR)[1].split('\n'); + calibTreeInfo = subprocess.getstatusoutput(initEnv+"eos ls " + CASTORDIR)[1].split('\n'); NTotalEvents = 0; run = 0 for info in calibTreeInfo: @@ -255,7 +255,7 @@ def checkCorrupted(lastGood, config): run = int(subParts[4].replace("/calibTree_","").replace(".root","").replace(CASTORDIR,"")) file = "root://eoscms//eos/cms"+subParts[4] print("Checking " + file) - results = commands.getstatusoutput(initEnv+'root -l -b -q ' + file) + results = subprocess.getstatusoutput(initEnv+'root -l -b -q ' + file) if(len(results[1].splitlines())>3): print(results[1]); print("add " + str(run) + " to the list of failled runs") diff --git a/CalibTracker/SiStripCommon/test/MakeCalibrationTrees/submitCalibTree/runJob.py b/CalibTracker/SiStripCommon/test/MakeCalibrationTrees/submitCalibTree/runJob.py index 5ac07ba7fc097..7649413e7f30d 100644 --- a/CalibTracker/SiStripCommon/test/MakeCalibrationTrees/submitCalibTree/runJob.py +++ b/CalibTracker/SiStripCommon/test/MakeCalibrationTrees/submitCalibTree/runJob.py @@ -1,9 +1,9 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 from __future__ import absolute_import from __future__ import print_function import os import sys -import commands +import subprocess import time import optparse from . import Config @@ -68,7 +68,7 @@ print("Job Failed with ExitCode "+str(exit_code)) os.system('echo %i %i %i >> FailledRun%s.txt' % (run, firstFile, firstFile+nFiles,'_Aag' if AAG else '')) else: - FileSizeInKBytes =commands.getstatusoutput('ls -lth --block-size=1024 '+PWDDIR+'/'+outfile)[1].split()[4] + FileSizeInKBytes = subprocess.getstatusoutput('ls -lth --block-size=1024 '+PWDDIR+'/'+outfile)[1].split()[4] if(int(FileSizeInKBytes)>10 and stageout): print("Preparing for stageout of " + PWDDIR+'/'+outfile + ' on ' + conf.CASTORDIR+'/'+outfile + '. The file size is %d KB' % int(FileSizeInKBytes)) cpCmd = "eos cp %s/%s "%(PWDDIR,outfile) diff --git a/CalibTracker/SiStripESProducers/plugins/fake/SiStripApvGainBuilderFromTag.cc b/CalibTracker/SiStripESProducers/plugins/fake/SiStripApvGainBuilderFromTag.cc index 3172d50c72b8b..9a0bce90a3a53 100644 --- a/CalibTracker/SiStripESProducers/plugins/fake/SiStripApvGainBuilderFromTag.cc +++ b/CalibTracker/SiStripESProducers/plugins/fake/SiStripApvGainBuilderFromTag.cc @@ -40,7 +40,7 @@ void SiStripApvGainBuilderFromTag::analyze(const edm::Event& evt, const edm::Eve inputApvGain.getDetIds(inputDetIds); // Prepare the new object - SiStripApvGain* obj = new SiStripApvGain(); + SiStripApvGain obj; uint32_t count = 0; for (const auto det : tGeom.detUnits()) { @@ -94,7 +94,7 @@ void SiStripApvGainBuilderFromTag::analyze(const edm::Event& evt, const edm::Eve } count++; SiStripApvGain::Range range(theSiStripVector.begin(), theSiStripVector.end()); - if (!obj->put(detid, range)) + if (!obj.put(detid, range)) edm::LogError("SiStripApvGainGeneratorFromTag") << " detid already exists" << std::endl; } } @@ -104,10 +104,9 @@ void SiStripApvGainBuilderFromTag::analyze(const edm::Event& evt, const edm::Eve if (mydbservice.isAvailable()) { if (mydbservice->isNewTagRequest("SiStripApvGainRcd2")) { - mydbservice->createNewIOV( - obj, mydbservice->beginOfTime(), mydbservice->endOfTime(), "SiStripApvGainRcd2"); + mydbservice->createOneIOV(obj, mydbservice->beginOfTime(), "SiStripApvGainRcd2"); } else { - mydbservice->appendSinceTime(obj, mydbservice->currentTime(), "SiStripApvGainRcd2"); + mydbservice->appendOneIOV(obj, mydbservice->currentTime(), "SiStripApvGainRcd2"); } } else { edm::LogError("SiStripApvGainBuilderFromTag") << "Service is unavailable" << std::endl; diff --git a/CalibTracker/SiStripESProducers/plugins/fake/SiStripNoiseNormalizedWithApvGainBuilder.cc b/CalibTracker/SiStripESProducers/plugins/fake/SiStripNoiseNormalizedWithApvGainBuilder.cc index 1c1f348faf8af..6cabf47381d0a 100644 --- a/CalibTracker/SiStripESProducers/plugins/fake/SiStripNoiseNormalizedWithApvGainBuilder.cc +++ b/CalibTracker/SiStripESProducers/plugins/fake/SiStripNoiseNormalizedWithApvGainBuilder.cc @@ -30,7 +30,7 @@ void SiStripNoiseNormalizedWithApvGainBuilder::analyze(const edm::Event& evt, co inputApvGain.getDetIds(inputDetIds); // Prepare the new object - SiStripNoises* obj = new SiStripNoises(); + SiStripNoises obj; stripLengthMode_ = pset_.getParameter("StripLengthMode"); @@ -72,7 +72,7 @@ void SiStripNoiseNormalizedWithApvGainBuilder::analyze(const edm::Event& evt, co noise = ((linearSlope * stripLength + linearQuote) / electronsPerADC_) * gain; if (count < printDebug_) printLog(detId, stripId + 128 * j, noise); - obj->setData(noise, theSiStripVector); + obj.setData(noise, theSiStripVector); } } } else { @@ -88,13 +88,13 @@ void SiStripNoiseNormalizedWithApvGainBuilder::analyze(const edm::Event& evt, co noise = minimumPosValue_; if (count < printDebug_) printLog(detId, stripId + 128 * j, noise); - obj->setData(noise, theSiStripVector); + obj.setData(noise, theSiStripVector); } } } ++count; - if (!obj->put(detId, theSiStripVector)) { + if (!obj.put(detId, theSiStripVector)) { edm::LogError("SiStripNoisesFakeESSource::produce ") << " detid already exists" << std::endl; } } @@ -105,10 +105,9 @@ void SiStripNoiseNormalizedWithApvGainBuilder::analyze(const edm::Event& evt, co if (mydbservice.isAvailable()) { if (mydbservice->isNewTagRequest("SiStripNoisesRcd")) { - mydbservice->createNewIOV( - obj, mydbservice->beginOfTime(), mydbservice->endOfTime(), "SiStripNoisesRcd"); + mydbservice->createOneIOV(obj, mydbservice->beginOfTime(), "SiStripNoisesRcd"); } else { - mydbservice->appendSinceTime(obj, mydbservice->currentTime(), "SiStripNoisesRcd"); + mydbservice->appendOneIOV(obj, mydbservice->currentTime(), "SiStripNoisesRcd"); } } else { edm::LogError("SiStripNoiseNormalizedWithApvGainBuilder") << "Service is unavailable" << std::endl; diff --git a/CalibTracker/SiStripESProducers/test/CheckPhase2Cabling.cc b/CalibTracker/SiStripESProducers/test/CheckPhase2Cabling.cc index 1f70c014975c4..7dfa34eaa01aa 100644 --- a/CalibTracker/SiStripESProducers/test/CheckPhase2Cabling.cc +++ b/CalibTracker/SiStripESProducers/test/CheckPhase2Cabling.cc @@ -22,7 +22,7 @@ // user include files #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/ESHandle.h" @@ -40,7 +40,7 @@ // class declaration // -class CheckPhase2Cabling : public edm::EDAnalyzer { +class CheckPhase2Cabling : public edm::one::EDAnalyzer<> { public: explicit CheckPhase2Cabling(const edm::ParameterSet&); ~CheckPhase2Cabling(); @@ -48,40 +48,18 @@ class CheckPhase2Cabling : public edm::EDAnalyzer { static void fillDescriptions(edm::ConfigurationDescriptions& descriptions); private: - virtual void beginJob(); virtual void analyze(const edm::Event&, const edm::EventSetup&); - virtual void endJob(); - - //virtual void beginRun(edm::Run const&, edm::EventSetup const&); - //virtual void endRun(edm::Run const&, edm::EventSetup const&); - //virtual void beginLuminosityBlock(edm::LuminosityBlock const&, edm::EventSetup const&); - //virtual void endLuminosityBlock(edm::LuminosityBlock const&, edm::EventSetup const&); // ----------member data --------------------------- + const edm::ESGetToken cablingToken_; }; -// -// constants, enums and typedefs -// - -// -// static data member definitions -// - // // constructors and destructor // -CheckPhase2Cabling::CheckPhase2Cabling(const edm::ParameterSet& iConfig) - -{ - //now do what ever initialization is needed -} - -CheckPhase2Cabling::~CheckPhase2Cabling() { - // do anything here that needs to be done at desctruction time - // (e.g. close files, deallocate resources etc.) -} +CheckPhase2Cabling::CheckPhase2Cabling(const edm::ParameterSet& iConfig) : cablingToken_(esConsumes()) {} +CheckPhase2Cabling::~CheckPhase2Cabling() = default; // // member functions // @@ -90,8 +68,7 @@ CheckPhase2Cabling::~CheckPhase2Cabling() { void CheckPhase2Cabling::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) { using namespace edm; - ESHandle cablingHandle; - iSetup.get().get(cablingHandle); + ESHandle cablingHandle = iSetup.getHandle(cablingToken_); // print general information about the cabling std::cout << cablingHandle->summaryDescription() << std::endl; @@ -116,44 +93,6 @@ void CheckPhase2Cabling::analyze(const edm::Event& iEvent, const edm::EventSetup std::cout << powerGroup.description(1) << std::endl; } -// ------------ method called once each job just before starting event loop ------------ -void CheckPhase2Cabling::beginJob() {} - -// ------------ method called once each job just after ending the event loop ------------ -void CheckPhase2Cabling::endJob() {} - -// ------------ method called when starting to processes a run ------------ -/* -void -CheckPhase2Cabling::beginRun(edm::Run const&, edm::EventSetup const&) -{ -} -*/ - -// ------------ method called when ending the processing of a run ------------ -/* -void -CheckPhase2Cabling::endRun(edm::Run const&, edm::EventSetup const&) -{ -} -*/ - -// ------------ method called when starting to processes a luminosity block ------------ -/* -void -CheckPhase2Cabling::beginLuminosityBlock(edm::LuminosityBlock const&, edm::EventSetup const&) -{ -} -*/ - -// ------------ method called when ending the processing of a luminosity block ------------ -/* -void -CheckPhase2Cabling::endLuminosityBlock(edm::LuminosityBlock const&, edm::EventSetup const&) -{ -} -*/ - // ------------ method fills 'descriptions' with the allowed parameters for the module ------------ void CheckPhase2Cabling::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { //The following says we do not know what parameters are allowed so do no validation diff --git a/CalibTracker/SiStripESProducers/test/SealModules.cc b/CalibTracker/SiStripESProducers/test/SealModules.cc deleted file mode 100644 index c0e0585248f3f..0000000000000 --- a/CalibTracker/SiStripESProducers/test/SealModules.cc +++ /dev/null @@ -1,7 +0,0 @@ -#include "FWCore/PluginManager/interface/ModuleDef.h" - -#include "FWCore/Framework/interface/MakerMacros.h" - -#include "CalibTracker/SiStripESProducers/test/testSiStripQualityESProducer.h" - -DEFINE_FWK_MODULE(testSiStripQualityESProducer); diff --git a/CalibTracker/SiStripESProducers/test/testSiStripQualityESProducer.cc b/CalibTracker/SiStripESProducers/test/testSiStripQualityESProducer.cc index 2eadbb7ccfb7d..fef8924f02a14 100644 --- a/CalibTracker/SiStripESProducers/test/testSiStripQualityESProducer.cc +++ b/CalibTracker/SiStripESProducers/test/testSiStripQualityESProducer.cc @@ -1,20 +1,46 @@ -#include "CalibFormats/SiStripObjects/interface/SiStripQuality.h" -#include "CalibTracker/Records/interface/SiStripQualityRcd.h" - -#include "CalibTracker/SiStripESProducers/test/testSiStripQualityESProducer.h" - +// system includes #include #include #include #include +// user include files +#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/ServiceRegistry/interface/Service.h" +#include "FWCore/MessageLogger/interface/MessageLogger.h" +#include "FWCore/ParameterSet/interface/ParameterSet.h" +#include "CalibFormats/SiStripObjects/interface/SiStripQuality.h" +#include "CalibTracker/Records/interface/SiStripQualityRcd.h" + +class testSiStripQualityESProducer : public edm::one::EDAnalyzer<> { +public: + explicit testSiStripQualityESProducer(const edm::ParameterSet&); + ~testSiStripQualityESProducer() = default; + + void analyze(const edm::Event&, const edm::EventSetup&); + +private: + void printObject(const SiStripQuality*); + + const edm::ESGetToken qualityToken_; + const edm::ESGetToken qualityTokenTwo_; + bool printdebug_; + unsigned long long m_cacheID_; + bool firstIOV; + bool twoRecordComparison_; + SiStripQuality* m_Quality_; +}; + testSiStripQualityESProducer::testSiStripQualityESProducer(const edm::ParameterSet& iConfig) - : printdebug_(iConfig.getUntrackedParameter("printDebug", false)), + : qualityToken_(esConsumes(edm::ESInputTag("", iConfig.getUntrackedParameter("dataLabel", "")))), + qualityTokenTwo_(esConsumes(edm::ESInputTag("", iConfig.getUntrackedParameter("dataLabelTwo", "")))), + printdebug_(iConfig.getUntrackedParameter("printDebug", false)), m_cacheID_(0), firstIOV(true), - twoRecordComparison_(iConfig.getUntrackedParameter("twoRecordComparison", false)), - dataLabel_(iConfig.getUntrackedParameter("dataLabel", "")), - dataLabelTwo_(iConfig.getUntrackedParameter("dataLabelTwo", "")) {} + twoRecordComparison_(iConfig.getUntrackedParameter("twoRecordComparison", false)) {} void testSiStripQualityESProducer::analyze(const edm::Event& e, const edm::EventSetup& iSetup) { unsigned long long cacheID = iSetup.get().cacheIdentifier(); @@ -29,8 +55,7 @@ void testSiStripQualityESProducer::analyze(const edm::Event& e, const edm::Event //&&&&&&&&&&&&&&&&&& //First Record //&&&&&&&&&&&&&&&&&& - edm::ESHandle SiStripQualityESH_; - iSetup.get().get(dataLabel_, SiStripQualityESH_); + edm::ESHandle SiStripQualityESH_ = iSetup.getHandle(qualityToken_); edm::LogInfo("testSiStripQualityESProducer") << canvas << "[testSiStripQualityESProducer::analyze] Print SiStripQualityRecord" << canvas << std::endl; printObject(SiStripQualityESH_.product()); @@ -40,7 +65,7 @@ void testSiStripQualityESProducer::analyze(const edm::Event& e, const edm::Event //&&&&&&&&&&&&&&&&&& edm::ESHandle twoSiStripQualityESH_; if (twoRecordComparison_) { - iSetup.get().get(dataLabelTwo_, twoSiStripQualityESH_); + twoSiStripQualityESH_ = iSetup.getHandle(qualityTokenTwo_); edm::LogInfo("testSiStripQualityESProducer") << canvas << "[testSiStripQualityESProducer::analyze] Print Second SiStripQualityRecord" << canvas << std::endl; printObject(twoSiStripQualityESH_.product()); @@ -128,3 +153,8 @@ void testSiStripQualityESProducer::printObject(const SiStripQuality* SiStripQual edm::LogInfo("testSiStripQualityESProducer") << ss.str(); } + +#include "FWCore/PluginManager/interface/ModuleDef.h" +#include "FWCore/Framework/interface/MakerMacros.h" + +DEFINE_FWK_MODULE(testSiStripQualityESProducer); diff --git a/CalibTracker/SiStripESProducers/test/testSiStripQualityESProducer.h b/CalibTracker/SiStripESProducers/test/testSiStripQualityESProducer.h deleted file mode 100644 index c51e32d30f7f7..0000000000000 --- a/CalibTracker/SiStripESProducers/test/testSiStripQualityESProducer.h +++ /dev/null @@ -1,35 +0,0 @@ -#ifndef testSiStripQualityESProducer_H -#define testSiStripQualityESProducer_H - -// system include files -//#include - -// user include files -#include "FWCore/Framework/interface/Frameworkfwd.h" -#include "FWCore/Framework/interface/EDAnalyzer.h" -#include "FWCore/Framework/interface/Event.h" -#include "FWCore/Framework/interface/EventSetup.h" -#include "FWCore/ServiceRegistry/interface/Service.h" -#include "FWCore/MessageLogger/interface/MessageLogger.h" -#include "FWCore/ParameterSet/interface/ParameterSet.h" - -class SiStripQuality; - -class testSiStripQualityESProducer : public edm::EDAnalyzer { -public: - explicit testSiStripQualityESProducer(const edm::ParameterSet&); - ~testSiStripQualityESProducer(){}; - - void analyze(const edm::Event&, const edm::EventSetup&); - -private: - void printObject(const SiStripQuality*); - bool printdebug_; - unsigned long long m_cacheID_; - bool firstIOV; - bool twoRecordComparison_; - std::string dataLabel_; - std::string dataLabelTwo_; - SiStripQuality* m_Quality_; -}; -#endif diff --git a/CalibTracker/SiStripLorentzAngle/plugins/SiStripCalibLorentzAngle.cc b/CalibTracker/SiStripLorentzAngle/plugins/SiStripCalibLorentzAngle.cc index 8ecea99d05808..fda20dfd99df8 100644 --- a/CalibTracker/SiStripLorentzAngle/plugins/SiStripCalibLorentzAngle.cc +++ b/CalibTracker/SiStripLorentzAngle/plugins/SiStripCalibLorentzAngle.cc @@ -2,7 +2,6 @@ #include #include #include -#include "CondCore/DBOutputService/interface/PoolDBOutputService.h" #include "FWCore/Framework/interface/ESHandle.h" #include "Geometry/TrackerGeometryBuilder/interface/StripGeomDetUnit.h" #include "DataFormats/SiStripDetId/interface/StripSubdetector.h" diff --git a/CalibTracker/SiStripQuality/plugins/SiStripBadStripFromQualityDBWriter.cc b/CalibTracker/SiStripQuality/plugins/SiStripBadStripFromQualityDBWriter.cc index fdd2d2ef2d76e..072e043723a09 100644 --- a/CalibTracker/SiStripQuality/plugins/SiStripBadStripFromQualityDBWriter.cc +++ b/CalibTracker/SiStripQuality/plugins/SiStripBadStripFromQualityDBWriter.cc @@ -55,7 +55,7 @@ void SiStripBadStripFromQualityDBWriter::dqmEndJob(DQMStore::IBooker& /*booker*/ else time = openIOVAtTime_; - dbservice->writeOne(payload.release(), time, rcdName_); + dbservice->writeOneIOV(*payload, time, rcdName_); } else { edm::LogError("SiStripBadStripFromQualityDBWriter") << "Service is unavailable" << std::endl; } diff --git a/Calibration/EcalCalibAlgos/src/ECALpedestalPCLHarvester.cc b/Calibration/EcalCalibAlgos/src/ECALpedestalPCLHarvester.cc index 1876ff44fd6ba..68fb008d3c50d 100644 --- a/Calibration/EcalCalibAlgos/src/ECALpedestalPCLHarvester.cc +++ b/Calibration/EcalCalibAlgos/src/ECALpedestalPCLHarvester.cc @@ -144,7 +144,7 @@ void ECALpedestalPCLHarvester::dqmEndJob(DQMStore::IBooker& ibooker_, DQMStore:: throw std::runtime_error("PoolDBService required."); } - poolDbService->writeOne(&pedestals, poolDbService->currentTime(), "EcalPedestalsRcd"); + poolDbService->writeOneIOV(pedestals, poolDbService->currentTime(), "EcalPedestalsRcd"); } // ------------ method fills 'descriptions' with the allowed parameters for the module ------------ diff --git a/Calibration/HcalAlCaRecoProducers/plugins/AlCaHcalIsotrkFilter.cc b/Calibration/HcalAlCaRecoProducers/plugins/AlCaHcalIsotrkFilter.cc index 9d7cc3d4557b5..ab72e34e345b1 100644 --- a/Calibration/HcalAlCaRecoProducers/plugins/AlCaHcalIsotrkFilter.cc +++ b/Calibration/HcalAlCaRecoProducers/plugins/AlCaHcalIsotrkFilter.cc @@ -1,4 +1,5 @@ // system include files +#include #include #include #include @@ -29,9 +30,10 @@ namespace alcaHcalIsoTrk { }; } // namespace alcaHcalIsoTrk -class AlCaHcalIsotrkFilter : public edm::global::EDFilter > { +class AlCaHcalIsotrkFilter : public edm::global::EDFilter> { public: AlCaHcalIsotrkFilter(edm::ParameterSet const&); + ~AlCaHcalIsotrkFilter() override = default; std::shared_ptr globalBeginRun(edm::Run const&, edm::EventSetup const&) const override; @@ -41,10 +43,11 @@ class AlCaHcalIsotrkFilter : public edm::global::EDFilter tokIsoTrkVar_; + const double pTrackLow_, pTrackHigh_; + const int prescaleLow_, prescaleHigh_; + const edm::InputTag labelIsoTkVar_; + const std::vector debEvents_; + const edm::EDGetTokenT tokIsoTrkVar_; }; // @@ -56,10 +59,12 @@ AlCaHcalIsotrkFilter::AlCaHcalIsotrkFilter(edm::ParameterSet const& iConfig) prescaleLow_(iConfig.getParameter("prescaleLow")), prescaleHigh_(iConfig.getParameter("prescaleHigh")), labelIsoTkVar_(iConfig.getParameter("isoTrackLabel")), + debEvents_(iConfig.getParameter>("debugEvents")), tokIsoTrkVar_(consumes(labelIsoTkVar_)) { edm::LogVerbatim("HcalIsoTrack") << "Parameters read from config file \n\t momentumLow_ " << pTrackLow_ << "\t prescaleLow_ " << prescaleLow_ << "\t momentumHigh_ " << pTrackHigh_ - << "\t prescaleHigh_ " << prescaleHigh_ << "\n\t Labels " << labelIsoTkVar_; + << "\t prescaleHigh_ " << prescaleHigh_ << "\n\t Labels " << labelIsoTkVar_ + << "\tand " << debEvents_.size() << " events to be debugged"; } // AlCaHcalIsotrkFilter::AlCaHcalIsotrkFilter constructor // @@ -71,9 +76,13 @@ bool AlCaHcalIsotrkFilter::filter(edm::StreamID, edm::Event& iEvent, edm::EventS bool accept(false); ++(runCache(iEvent.getRun().index())->nAll_); #ifdef EDM_ML_DEBUG - edm::LogVerbatim("HcalIsoTrack") << "AlCaHcalIsotrkFilter::Run " << iEvent.id().run() << " Event " - << iEvent.id().event() << " Luminosity " << iEvent.luminosityBlock() << " Bunch " - << iEvent.bunchCrossing(); + bool debug = (debEvents_.empty()) + ? true + : (std::find(debEvents_.begin(), debEvents_.end(), iEvent.id().event()) != debEvents_.end()); + if (debug) + edm::LogVerbatim("HcalIsoTrack") << "AlCaHcalIsotrkFilter::Run " << iEvent.id().run() << " Event " + << iEvent.id().event() << " Luminosity " << iEvent.luminosityBlock() << " Bunch " + << iEvent.bunchCrossing(); #endif auto const& isotrkCalibColl = iEvent.getHandle(tokIsoTrkVar_); @@ -90,9 +99,10 @@ bool AlCaHcalIsotrkFilter::filter(edm::StreamID, edm::Event& iEvent, edm::EventS } } #ifdef EDM_ML_DEBUG - edm::LogVerbatim("HcalIsoTrack") << "AlCaHcalIsotrkFilter::Finds " << isotrkCalib->size() - << " entries in HcalIsoTrkCalibVariables collection with inRange " << inRange - << " low " << low << " high " << high; + if (debug) + edm::LogVerbatim("HcalIsoTrack") << "AlCaHcalIsotrkFilter::Finds " << isotrkCalib->size() + << " entries in HcalIsoTrkCalibVariables collection with inRange " << inRange + << " low " << low << " high " << high; #endif if (low) ++(runCache(iEvent.getRun().index())->nLow_); @@ -119,14 +129,17 @@ bool AlCaHcalIsotrkFilter::filter(edm::StreamID, edm::Event& iEvent, edm::EventS } // Return the acceptance flag - if (accept) + if (accept) { ++(runCache(iEvent.getRun().index())->nGood_); + edm::LogVerbatim("HcalIsoTrackX") << "Run " << iEvent.id().run() << " Event " << iEvent.id().event(); + } #ifdef EDM_ML_DEBUG - edm::LogVerbatim("HcalIsoTrack") << "AlCaHcalIsotrkFilter::Accept flag " << accept << " All " - << runCache(iEvent.getRun().index())->nAll_ << " Good " - << runCache(iEvent.getRun().index())->nGood_ << " Low " - << runCache(iEvent.getRun().index())->nLow_ << " High " - << runCache(iEvent.getRun().index())->nHigh_; + if (debug) + edm::LogVerbatim("HcalIsoTrack") << "AlCaHcalIsotrkFilter::Accept flag " << accept << " All " + << runCache(iEvent.getRun().index())->nAll_ << " Good " + << runCache(iEvent.getRun().index())->nGood_ << " Low " + << runCache(iEvent.getRun().index())->nLow_ << " High " + << runCache(iEvent.getRun().index())->nHigh_; #endif return accept; @@ -155,6 +168,8 @@ void AlCaHcalIsotrkFilter::fillDescriptions(edm::ConfigurationDescriptions& desc desc.add("prescaleLow", 1); desc.add("prescaleHigh", 1); desc.add("isoTrackLabel", edm::InputTag("alcaHcalIsotrkProducer", "HcalIsoTrack")); + std::vector events; + desc.add>("debugEvents", events); descriptions.add("alcaHcalIsotrkFilter", desc); } diff --git a/Calibration/HcalAlCaRecoProducers/plugins/AlCaHcalIsotrkProducer.cc b/Calibration/HcalAlCaRecoProducers/plugins/AlCaHcalIsotrkProducer.cc index 67cd96c4c1d9b..10d4050ee2455 100644 --- a/Calibration/HcalAlCaRecoProducers/plugins/AlCaHcalIsotrkProducer.cc +++ b/Calibration/HcalAlCaRecoProducers/plugins/AlCaHcalIsotrkProducer.cc @@ -1,6 +1,7 @@ // -*- C++ -*- // system include files +#include #include #include #include @@ -87,7 +88,7 @@ namespace alcaHcalIsoTracks { }; } // namespace alcaHcalIsoTracks -class AlCaHcalIsotrkProducer : public edm::stream::EDProducer > { +class AlCaHcalIsotrkProducer : public edm::stream::EDProducer> { public: explicit AlCaHcalIsotrkProducer(edm::ParameterSet const&, const alcaHcalIsoTracks::Counters*); ~AlCaHcalIsotrkProducer() override = default; @@ -168,6 +169,7 @@ class AlCaHcalIsotrkProducer : public edm::stream::EDProducer oldID_, newDepth_; const bool hep17_; const std::string labelIsoTkVar_, labelIsoTkEvtVar_; + const std::vector debEvents_; double a_charIsoR_, a_coneR1_, a_coneR2_; const HcalDDDRecConstants* hdc_; @@ -186,7 +188,7 @@ class AlCaHcalIsotrkProducer : public edm::stream::EDProducer tok_hbhe_; edm::EDGetTokenT tok_cala_; edm::EDGetTokenT tok_ew_; - edm::EDGetTokenT > tok_alg_; + edm::EDGetTokenT> tok_alg_; edm::EDGetTokenT tok_Muon_; edm::ESGetToken tok_ddrec_; @@ -197,6 +199,8 @@ class AlCaHcalIsotrkProducer : public edm::stream::EDProducer tok_caloTopology_; edm::ESGetToken tok_htopo_; edm::ESGetToken tok_resp_; + + bool debug_; }; AlCaHcalIsotrkProducer::AlCaHcalIsotrkProducer(edm::ParameterSet const& iConfig, @@ -205,7 +209,7 @@ AlCaHcalIsotrkProducer::AlCaHcalIsotrkProducer(edm::ParameterSet const& iConfig, nAll_(0), nGood_(0), nRange_(0), - trigNames_(iConfig.getParameter >("triggers")), + trigNames_(iConfig.getParameter>("triggers")), theTrackQuality_(iConfig.getParameter("trackQuality")), processName_(iConfig.getParameter("processName")), l1Filter_(iConfig.getParameter("l1Filter")), @@ -246,11 +250,12 @@ AlCaHcalIsotrkProducer::AlCaHcalIsotrkProducer(edm::ParameterSet const& iConfig, labelHBHE_(iConfig.getParameter("labelHBHERecHit")), labelTower_(iConfig.getParameter("labelCaloTower")), l1TrigName_(iConfig.getUntrackedParameter("l1TrigName", "L1_SingleJet60")), - oldID_(iConfig.getUntrackedParameter >("oldID")), - newDepth_(iConfig.getUntrackedParameter >("newDepth")), + oldID_(iConfig.getUntrackedParameter>("oldID")), + newDepth_(iConfig.getUntrackedParameter>("newDepth")), hep17_(iConfig.getUntrackedParameter("hep17")), labelIsoTkVar_(iConfig.getParameter("isoTrackLabel")), - labelIsoTkEvtVar_(iConfig.getParameter("isoTrackEventLabel")) { + labelIsoTkEvtVar_(iConfig.getParameter("isoTrackEventLabel")), + debEvents_(iConfig.getParameter>("debugEvents")) { // Get the run parameters const double isolationRadius(28.9), innerR(10.0), outerR(30.0); reco::TrackBase::TrackQuality trackQuality_ = reco::TrackBase::qualityByName(theTrackQuality_); @@ -296,7 +301,7 @@ AlCaHcalIsotrkProducer::AlCaHcalIsotrkProducer(edm::ParameterSet const& iConfig, tok_ew_ = consumes(edm::InputTag("generator")); tok_parts_ = consumes(edm::InputTag("genParticles")); tok_cala_ = consumes(labelTower_); - tok_alg_ = consumes >(algTag); + tok_alg_ = consumes>(algTag); tok_Muon_ = consumes(labelMuon); tok_recVtx_ = consumes(labelRecVtx_); tok_EB_ = consumes(edm::InputTag("ecalRecHit", labelEB_)); @@ -340,7 +345,8 @@ AlCaHcalIsotrkProducer::AlCaHcalIsotrkProducer(edm::ParameterSet const& iConfig, << " EE " << hitEthrEE0_ << ":" << hitEthrEE1_ << ":" << hitEthrEE2_ << ":" << hitEthrEE3_ << ":" << hitEthrEELo_ << ":" << hitEthrEEHi_; edm::LogVerbatim("HcalIsoTrack") << "Process " << processName_ << " L1Filter:" << l1Filter_ - << " L2Filter:" << l2Filter_ << " L3Filter:" << l3Filter_; + << " L2Filter:" << l2Filter_ << " L3Filter:" << l3Filter_ << " and " + << debEvents_.size() << " events to be debugged"; for (unsigned int k = 0; k < trigNames_.size(); ++k) { edm::LogVerbatim("HcalIsoTrack") << "Trigger[" << k << "] " << trigNames_[k]; } @@ -371,7 +377,7 @@ void AlCaHcalIsotrkProducer::fillDescriptions(edm::ConfigurationDescriptions& de edm::ParameterSetDescription desc; desc.add("processName", "HLT"); std::vector trig; - desc.add >("triggers", trig); + desc.add>("triggers", trig); desc.add("l1Filter", ""); desc.add("l2Filter", "L2Filter"); desc.add("l3Filter", "Filter"); @@ -438,17 +444,24 @@ void AlCaHcalIsotrkProducer::fillDescriptions(edm::ConfigurationDescriptions& de desc.addUntracked("collapseDepth", false); desc.addUntracked("l1TrigName", "L1_SingleJet60"); std::vector dummy; - desc.addUntracked >("oldID", dummy); - desc.addUntracked >("newDepth", dummy); + desc.addUntracked>("oldID", dummy); + desc.addUntracked>("newDepth", dummy); desc.addUntracked("hep17", false); + std::vector events; + desc.add>("debugEvents", events); descriptions.add("alcaHcalIsotrkProducer", desc); } void AlCaHcalIsotrkProducer::produce(edm::Event& iEvent, edm::EventSetup const& iSetup) { nAll_++; + debug_ = (debEvents_.empty()) + ? true + : (std::find(debEvents_.begin(), debEvents_.end(), iEvent.id().event()) != debEvents_.end()); #ifdef EDM_ML_DEBUG - edm::LogVerbatim("HcalIsoTrack") << "Run " << iEvent.id().run() << " Event " << iEvent.id().event() << " Luminosity " - << iEvent.luminosityBlock() << " Bunch " << iEvent.bunchCrossing(); + if (debug_) + edm::LogVerbatim("HcalIsoTrack") << "Run " << iEvent.id().run() << " Event " << iEvent.id().event() + << " Luminosity " << iEvent.luminosityBlock() << " Bunch " + << iEvent.bunchCrossing(); #endif HcalIsoTrkEventVariables isoTrkEvent; @@ -492,9 +505,10 @@ void AlCaHcalIsotrkProducer::produce(edm::Event& iEvent, edm::EventSetup const& leadPV = beamSpotH->position(); } #ifdef EDM_ML_DEBUG - edm::LogVerbatim("HcalIsoTrack") << "Primary Vertex " << leadPV << " out of " << goodPV << " vertex"; - if (beamSpotH.isValid()) { - edm::LogVerbatim("HcalIsoTrack") << " Beam Spot " << beamSpotH->position(); + if (debug_) { + edm::LogVerbatim("HcalIsoTrack") << "Primary Vertex " << leadPV << " out of " << goodPV << " vertex"; + if (beamSpotH.isValid()) + edm::LogVerbatim("HcalIsoTrack") << " Beam Spot " << beamSpotH->position(); } #endif @@ -534,7 +548,7 @@ void AlCaHcalIsotrkProducer::produce(edm::Event& iEvent, edm::EventSetup const& if (!ignoreTrigger_) { //L1 l1GtUtils_->retrieveL1(iEvent, iSetup, tok_alg_); - const std::vector >& finalDecisions = l1GtUtils_->decisionsFinal(); + const std::vector>& finalDecisions = l1GtUtils_->decisionsFinal(); for (const auto& decision : finalDecisions) { if (decision.first.find(l1TrigName_) != std::string::npos) { isoTrkEvent.l1Bit_ = decision.second; @@ -542,8 +556,9 @@ void AlCaHcalIsotrkProducer::produce(edm::Event& iEvent, edm::EventSetup const& } } #ifdef EDM_ML_DEBUG - edm::LogVerbatim("HcalIsoTrack") << "Trigger Information for " << l1TrigName_ << " is " << isoTrkEvent.l1Bit_ - << " from a list of " << finalDecisions.size() << " decisions"; + if (debug_) + edm::LogVerbatim("HcalIsoTrack") << "Trigger Information for " << l1TrigName_ << " is " << isoTrkEvent.l1Bit_ + << " from a list of " << finalDecisions.size() << " decisions"; #endif //HLT @@ -560,8 +575,9 @@ void AlCaHcalIsotrkProducer::produce(edm::Event& iEvent, edm::EventSetup const& if (hlt > 0) isoTrkEvent.trigPass_ = true; #ifdef EDM_ML_DEBUG - edm::LogVerbatim("HcalIsoTrack") - << "This trigger " << names[iHLT] << " Flag " << hlt << ":" << isoTrkEvent.hltbits_[i]; + if (debug_) + edm::LogVerbatim("HcalIsoTrack") + << "This trigger " << names[iHLT] << " Flag " << hlt << ":" << isoTrkEvent.hltbits_[i]; #endif } } @@ -569,8 +585,9 @@ void AlCaHcalIsotrkProducer::produce(edm::Event& iEvent, edm::EventSetup const& } } #ifdef EDM_ML_DEBUG - edm::LogVerbatim("HcalIsoTrack") << "HLT Information shows " << isoTrkEvent.trigPass_ << ":" << trigNames_.empty() - << ":" << okC; + if (debug_) + edm::LogVerbatim("HcalIsoTrack") << "HLT Information shows " << isoTrkEvent.trigPass_ << ":" << trigNames_.empty() + << ":" << okC; #endif } @@ -632,7 +649,8 @@ void AlCaHcalIsotrkProducer::produce(edm::Event& iEvent, edm::EventSetup const& for (unsigned int imodule = 0; imodule < moduleLabels.size(); imodule++) { if (label.find(moduleLabels[imodule]) != std::string::npos) { #ifdef EDM_ML_DEBUG - edm::LogVerbatim("HcalIsoTrack") << "FilterName " << label; + if (debug_) + edm::LogVerbatim("HcalIsoTrack") << "FilterName " << label; #endif for (unsigned int ifiltrKey = 0; ifiltrKey < triggerEvent.filterKeys(ifilter).size(); ++ifiltrKey) { Keys.push_back(triggerEvent.filterKeys(ifilter)[ifiltrKey]); @@ -646,14 +664,16 @@ void AlCaHcalIsotrkProducer::produce(edm::Event& iEvent, edm::EventSetup const& vecL1.push_back(v4); } #ifdef EDM_ML_DEBUG - edm::LogVerbatim("HcalIsoTrack") - << "key " << ifiltrKey << " : pt " << TO.pt() << " eta " << TO.eta() << " phi " << TO.phi() - << " mass " << TO.mass() << " Id " << TO.id(); + if (debug_) + edm::LogVerbatim("HcalIsoTrack") + << "key " << ifiltrKey << " : pt " << TO.pt() << " eta " << TO.eta() << " phi " << TO.phi() + << " mass " << TO.mass() << " Id " << TO.id(); #endif } #ifdef EDM_ML_DEBUG - edm::LogVerbatim("HcalIsoTrack") - << "sizes " << vecL1.size() << ":" << vecL2.size() << ":" << vecL3.size(); + if (debug_) + edm::LogVerbatim("HcalIsoTrack") + << "sizes " << vecL1.size() << ":" << vecL2.size() << ":" << vecL3.size(); #endif } } @@ -787,8 +807,9 @@ std::array AlCaHcalIsotrkProducer::getProducts(int goodPV, isoTk.pt_ = pTrack->pt(); isoTk.phi_ = pTrack->phi(); #ifdef EDM_ML_DEBUG - edm::LogVerbatim("HcalIsoTrack") << "This track : " << nTracks << " (pt|eta|phi|p) :" << isoTk.pt_ << "|" - << pTrack->eta() << "|" << isoTk.phi_ << "|" << isoTk.p_; + if (debug_) + edm::LogVerbatim("HcalIsoTrack") << "This track : " << nTracks << " (pt|eta|phi|p) : " << isoTk.pt_ << "|" + << pTrack->eta() << "|" << isoTk.phi_ << "|" << isoTk.p_; int flag(0); #endif isoTk.mindR2_ = 999; @@ -800,8 +821,9 @@ std::array AlCaHcalIsotrkProducer::getProducts(int goodPV, } isoTk.mindR1_ = (!vecL1.empty()) ? dR(vecL1[0], v4) : 999; #ifdef EDM_ML_DEBUG - edm::LogVerbatim("HcalIsoTrack") << "Closest L3 object at dr :" << isoTk.mindR2_ << " and from L1 " - << isoTk.mindR1_; + if (debug_) + edm::LogVerbatim("HcalIsoTrack") << "Closest L3 object at dr : " << isoTk.mindR2_ << " and from L1 " + << isoTk.mindR1_; #endif isoTk.ieta_ = isoTk.iphi_ = 0; if (trkDetItr->okHCAL) { @@ -833,8 +855,9 @@ std::array AlCaHcalIsotrkProducer::getProducts(int goodPV, if (eIsolation < eIsolate2_) eIsolation = eIsolate2_; #ifdef EDM_ML_DEBUG - edm::LogVerbatim("HcalIsoTrack") << "qltyFlag|okECAL|okHCAL : " << qltyFlag << "|" << trkDetItr->okECAL << "|" - << trkDetItr->okHCAL << " eIsolation " << eIsolation; + if (debug_) + edm::LogVerbatim("HcalIsoTrack") << "qltyFlag|okECAL|okHCAL : " << qltyFlag << "|" << trkDetItr->okECAL << "|" + << trkDetItr->okHCAL << " eIsolation " << eIsolation; if (qltyFlag) flag += 1; if (trkDetItr->okECAL) @@ -872,7 +895,8 @@ std::array AlCaHcalIsotrkProducer::getProducts(int goodPV, eEcal += eHit[k]; } #ifdef EDM_ML_DEBUG - edm::LogVerbatim("HcalIsoTrack") << "eMIP before and after: " << eMipDR << ":" << eEcal; + if (debug_) + edm::LogVerbatim("HcalIsoTrack") << "eMIP before and after: " << eMipDR << ":" << eEcal; #endif isoTk.eMipDR_.emplace_back(eEcal); ////////////////////////////////-MIP STUFF-/////////////////////////////// @@ -897,7 +921,8 @@ std::array AlCaHcalIsotrkProducer::getProducts(int goodPV, eEcal2 += eHit2[k]; } #ifdef EDM_ML_DEBUG - edm::LogVerbatim("HcalIsoTrack") << "eMIP before and after: " << eMipDR2 << ":" << eEcal2; + if (debug_) + edm::LogVerbatim("HcalIsoTrack") << "eMIP before and after: " << eMipDR2 << ":" << eEcal2; #endif isoTk.eMipDR_.emplace_back(eEcal2); ////////////////////////////////-MIP STUFF-2///////////////////////////// @@ -922,7 +947,8 @@ std::array AlCaHcalIsotrkProducer::getProducts(int goodPV, eEcal3 += eHit3[k]; } #ifdef EDM_ML_DEBUG - edm::LogVerbatim("HcalIsoTrack") << "eMIP before and after: " << eMipDR3 << ":" << eEcal3; + if (debug_) + edm::LogVerbatim("HcalIsoTrack") << "eMIP before and after: " << eMipDR3 << ":" << eEcal3; #endif isoTk.eMipDR_.emplace_back(eEcal3); ////////////////////////////////-MIP STUFF-3///////////////////////////// @@ -947,7 +973,8 @@ std::array AlCaHcalIsotrkProducer::getProducts(int goodPV, eEcal4 += eHit4[k]; } #ifdef EDM_ML_DEBUG - edm::LogVerbatim("HcalIsoTrack") << "eMIP before and after: " << eMipDR4 << ":" << eEcal4; + if (debug_) + edm::LogVerbatim("HcalIsoTrack") << "eMIP before and after: " << eMipDR4 << ":" << eEcal4; #endif isoTk.eMipDR_.emplace_back(eEcal4); ////////////////////////////////-MIP STUFF-4///////////////////////////// @@ -972,7 +999,8 @@ std::array AlCaHcalIsotrkProducer::getProducts(int goodPV, eEcal5 += eHit5[k]; } #ifdef EDM_ML_DEBUG - edm::LogVerbatim("HcalIsoTrack") << "eMIP before and after: " << eMipDR5 << ":" << eEcal5; + if (debug_) + edm::LogVerbatim("HcalIsoTrack") << "eMIP before and after: " << eMipDR5 << ":" << eEcal5; #endif isoTk.eMipDR_.emplace_back(eEcal5); ////////////////////////////////-MIP STUFF-5///////////////////////////// @@ -1018,10 +1046,11 @@ std::array AlCaHcalIsotrkProducer::getProducts(int goodPV, theHBHETopology, cellH, hbhe, 3, 3, false, true, -100.0, -100.0, -100.0, -100.0, -100.0, 100.0); isoTk.hAnnular_ = h7x7 - h5x5; #ifdef EDM_ML_DEBUG - edm::LogVerbatim("HcalIsoTrack") << "max p Near (Ecal) " << isoTk.emaxNearP_ << " (Hcal) " << isoTk.hmaxNearP_ - << " Annular E (Ecal) " << e11x11P.first << ":" << e15x15P.first << ":" - << isoTk.eAnnular_ << " (Hcal) " << h5x5 << ":" << h7x7 << ":" - << isoTk.hAnnular_; + if (debug_) + edm::LogVerbatim("HcalIsoTrack") << "max p Near (Ecal) " << isoTk.emaxNearP_ << " (Hcal) " << isoTk.hmaxNearP_ + << " Annular E (Ecal) " << e11x11P.first << ":" << e15x15P.first << ":" + << isoTk.eAnnular_ << " (Hcal) " << h5x5 << ":" << h7x7 << ":" + << isoTk.hAnnular_; if (isoTk.eMipDR_[0] < eEcalMax_) flag += 16; if (isoTk.hmaxNearP_ < eIsolation) @@ -1094,36 +1123,37 @@ std::array AlCaHcalIsotrkProducer::getProducts(int goodPV, isoTk.eHcal30Raw_ = ehcal3.first; isoTk.eHcal30Aux_ = ehcal3.second; + if (isoTk.p_ > pTrackMin_) + accept = true; #ifdef EDM_ML_DEBUG - edm::LogVerbatim("HcalIsoTrack") << "This track : " << nTracks << " (pt|eta|phi|p) :" << isoTk.pt_ << "|" - << pTrack->eta() << "|" << isoTk.phi_ << "|" << isoTk.p_ - << " Generator Level p " << isoTk.gentrackP_; - edm::LogVerbatim("HcalIsoTrack") << "e_MIP " << isoTk.eMipDR_[0] << " Chg Isolation " << isoTk.hmaxNearP_ - << " eHcal" << isoTk.eHcal_ << ":" << isoTk.eHcalRaw_ << ":" << isoTk.eHcalAux_ - << " ieta " << isoTk.ieta_ << " Quality " << isoTk.qltyMissFlag_ << ":" - << isoTk.qltyPVFlag_ << ":" << isoTk.selectTk_; - for (unsigned int ll = 0; ll < isoTk.detIds_.size(); ll++) { + if (accept) + flag += 64; + if (debug_) { + std::string ctype = accept ? " ***** ACCEPT *****" : ""; edm::LogVerbatim("HcalIsoTrack") - << "det id is = " << HcalDetId(isoTk.detIds_[ll]) << " hit enery is = " << isoTk.hitEnergies_[ll] - << " : " << isoTk.hitEnergiesRaw_[ll] << " : " << isoTk.hitEnergiesAux_[ll]; - } - for (unsigned int ll = 0; ll < isoTk.detIds1_.size(); ll++) { + << "This track : " << nTracks << " (pt|eta|phi|p) : " << isoTk.pt_ << "|" << pTrack->eta() << "|" + << isoTk.phi_ << "|" << isoTk.p_ << " Generator Level p " << isoTk.gentrackP_; edm::LogVerbatim("HcalIsoTrack") - << "det id is = " << HcalDetId(isoTk.detIds1_[ll]) << " hit enery is = " << isoTk.hitEnergies1_[ll] - << " : " << isoTk.hitEnergies1Raw_[ll] << " : " << isoTk.hitEnergies1Aux_[ll]; - ; - } - for (unsigned int ll = 0; ll < isoTk.detIds3_.size(); ll++) { - edm::LogVerbatim("HcalIsoTrack") - << "det id is = " << HcalDetId(isoTk.detIds3_[ll]) << " hit enery is = " << isoTk.hitEnergies3_[ll] - << " : " << isoTk.hitEnergies3Raw_[ll] << " : " << isoTk.hitEnergies3Aux_[ll]; - ; + << "e_MIP " << isoTk.eMipDR_[0] << " Chg Isolation " << isoTk.hmaxNearP_ << " eHcal" << isoTk.eHcal_ + << ":" << isoTk.eHcalRaw_ << ":" << isoTk.eHcalAux_ << " ieta " << isoTk.ieta_ << " Quality " + << isoTk.qltyMissFlag_ << ":" << isoTk.qltyPVFlag_ << ":" << isoTk.selectTk_ << ctype; + for (unsigned int ll = 0; ll < isoTk.detIds_.size(); ll++) { + edm::LogVerbatim("HcalIsoTrack") + << "det id is = " << HcalDetId(isoTk.detIds_[ll]) << " hit enery is = " << isoTk.hitEnergies_[ll] + << " : " << isoTk.hitEnergiesRaw_[ll] << " : " << isoTk.hitEnergiesAux_[ll]; + } + for (unsigned int ll = 0; ll < isoTk.detIds1_.size(); ll++) { + edm::LogVerbatim("HcalIsoTrack") + << "det id is = " << HcalDetId(isoTk.detIds1_[ll]) << " hit enery is = " << isoTk.hitEnergies1_[ll] + << " : " << isoTk.hitEnergies1Raw_[ll] << " : " << isoTk.hitEnergies1Aux_[ll]; + } + for (unsigned int ll = 0; ll < isoTk.detIds3_.size(); ll++) { + edm::LogVerbatim("HcalIsoTrack") + << "det id is = " << HcalDetId(isoTk.detIds3_[ll]) << " hit enery is = " << isoTk.hitEnergies3_[ll] + << " : " << isoTk.hitEnergies3Raw_[ll] << " : " << isoTk.hitEnergies3Aux_[ll]; + } } - if (isoTk.p_ > pTrackMin_) - flag += 64; #endif - if (isoTk.p_ > pTrackMin_) - accept = true; if (accept) { hocalib.emplace_back(isoTk); nSave++; @@ -1151,14 +1181,16 @@ std::array AlCaHcalIsotrkProducer::getProducts(int goodPV, } } #ifdef EDM_ML_DEBUG - if (isoTk.eMipDR_.empty()) - edm::LogVerbatim("HcalIsoTrack") << "Track " << nTracks << " Selection Flag " << std::hex << flag << std::dec - << " Accept " << accept << " Momentum " << isoTk.p_ << ":" << pTrackMin_; - else - edm::LogVerbatim("HcalIsoTrack") << "Track " << nTracks << " Selection Flag " << std::hex << flag << std::dec - << " Accept " << accept << " Momentum " << isoTk.p_ << ":" << pTrackMin_ - << " Ecal Energy " << isoTk.eMipDR_[0] << ":" << eEcalMax_ - << " Charge Isolation " << isoTk.hmaxNearP_ << ":" << eIsolation; + if (debug_) { + if (isoTk.eMipDR_.empty()) + edm::LogVerbatim("HcalIsoTrack") << "Track " << nTracks << " Selection Flag " << std::hex << flag << std::dec + << " Accept " << accept << " Momentum " << isoTk.p_ << ":" << pTrackMin_; + else + edm::LogVerbatim("HcalIsoTrack") << "Track " << nTracks << " Selection Flag " << std::hex << flag << std::dec + << " Accept " << accept << " Momentum " << isoTk.p_ << ":" << pTrackMin_ + << " Ecal Energy " << isoTk.eMipDR_[0] << ":" << eEcalMax_ + << " Charge Isolation " << isoTk.hmaxNearP_ << ":" << eIsolation; + } #endif } std::array i3{{nSave, nLoose, nTight}}; @@ -1210,7 +1242,8 @@ double AlCaHcalIsotrkProducer::rhoh(const edm::Handle& towe evt_smdq = (sumPFNallSMDQH2[sumPFNallSMDQH2.size() / 2] + sumPFNallSMDQH2[(sumPFNallSMDQH2.size() - 2) / 2]) / 2.; double rhoh = evt_smdq / (etadist_ * phidist_); #ifdef EDM_ML_DEBUG - edm::LogVerbatim("HcalIsoTrack") << "Rho " << evt_smdq << ":" << rhoh; + if (debug_) + edm::LogVerbatim("HcalIsoTrack") << "Rho " << evt_smdq << ":" << rhoh; #endif return rhoh; } @@ -1290,13 +1323,15 @@ void AlCaHcalIsotrkProducer::storeEnergy(const HcalRespCorrs* respCorrs, } } #ifdef EDM_ML_DEBUG - edm::LogVerbatim("HcalIsoTrack") << "StoreEnergy1::Input to storeEnergy with " << ids.size() << " cells"; - for (unsigned int k = 0; k < ids.size(); ++k) - edm::LogVerbatim("HcalIsoTrack") << "Hit [" << k << "] " << HcalDetId(ids[k]) << " E " << edet[k]; - edm::LogVerbatim("HcalIsoTrack") << "StoreEnergy1::Output of storeEnergy with " << detIds.size() << " cells and Etot " - << eHcal; - for (unsigned int k = 0; k < detIds.size(); ++k) - edm::LogVerbatim("HcalIsoTrack") << "Hit [" << k << "] " << HcalDetId(detIds[k]) << " E " << hitEnergies[k]; + if (debug_) { + edm::LogVerbatim("HcalIsoTrack") << "StoreEnergy1::Input to storeEnergy with " << ids.size() << " cells"; + for (unsigned int k = 0; k < ids.size(); ++k) + edm::LogVerbatim("HcalIsoTrack") << "Hit [" << k << "] " << HcalDetId(ids[k]) << " E " << edet[k]; + edm::LogVerbatim("HcalIsoTrack") << "StoreEnergy1::Output of storeEnergy with " << detIds.size() + << " cells and Etot " << eHcal; + for (unsigned int k = 0; k < detIds.size(); ++k) + edm::LogVerbatim("HcalIsoTrack") << "Hit [" << k << "] " << HcalDetId(detIds[k]) << " E " << hitEnergies[k]; + } #endif } @@ -1340,7 +1375,7 @@ std::pair AlCaHcalIsotrkProducer::storeEnergy(const HcalRespCorr ehcal2 *= hcalScale_; if (collapseDepth_) { - std::map > hitMap; + std::map> hitMap; for (unsigned int k = 0; k < ids.size(); ++k) { HcalDetId id = hdc_->mergedDepthDetId(HcalDetId(ids[k])); auto itr = hitMap.find(id); @@ -1366,11 +1401,13 @@ std::pair AlCaHcalIsotrkProducer::storeEnergy(const HcalRespCorr } } #ifdef EDM_ML_DEBUG - edm::LogVerbatim("HcalIsoTrack") << "StoreEnergy2::Input to storeEnergy with " << ids.size() << " cells"; - edm::LogVerbatim("HcalIsoTrack") << "StoreEnergy2::Output of storeEnergy with " << hitEnergy1.size() - << " cells and Etot " << ehcal1 << ":" << ehcal2; - for (unsigned int k = 0; k < hitEnergy1.size(); ++k) - edm::LogVerbatim("HcalIsoTrack") << "Hit [" << k << "] " << hitEnergy1[k] << " : " << hitEnergy2[k]; + if (debug_) { + edm::LogVerbatim("HcalIsoTrack") << "StoreEnergy2::Input to storeEnergy with " << ids.size() << " cells"; + edm::LogVerbatim("HcalIsoTrack") << "StoreEnergy2::Output of storeEnergy with " << hitEnergy1.size() + << " cells and Etot " << ehcal1 << ":" << ehcal2; + for (unsigned int k = 0; k < hitEnergy1.size(); ++k) + edm::LogVerbatim("HcalIsoTrack") << "Hit [" << k << "] " << hitEnergy1[k] << " : " << hitEnergy2[k]; + } #endif return std::make_pair(ehcal1, ehcal2); } diff --git a/Calibration/HcalAlCaRecoProducers/plugins/AlCaIsoTracksFilter.cc b/Calibration/HcalAlCaRecoProducers/plugins/AlCaIsoTracksFilter.cc index 40764d9d2aec2..74ae44ea9ba33 100644 --- a/Calibration/HcalAlCaRecoProducers/plugins/AlCaIsoTracksFilter.cc +++ b/Calibration/HcalAlCaRecoProducers/plugins/AlCaIsoTracksFilter.cc @@ -1,4 +1,5 @@ // system include files +#include #include #include #include @@ -65,10 +66,10 @@ namespace AlCaIsoTracks { }; } // namespace AlCaIsoTracks -class AlCaIsoTracksFilter : public edm::stream::EDFilter > { +class AlCaIsoTracksFilter : public edm::stream::EDFilter> { public: explicit AlCaIsoTracksFilter(edm::ParameterSet const&, const AlCaIsoTracks::Counters* count); - ~AlCaIsoTracksFilter() override; + ~AlCaIsoTracksFilter() override = default; static std::unique_ptr initializeGlobalCache(edm::ParameterSet const& iConfig) { return std::make_unique(); @@ -99,6 +100,7 @@ class AlCaIsoTracksFilter : public edm::stream::EDFilter debEvents_; spr::trackSelectionParameters selectionParameter_; double a_charIsoR_; unsigned int nRun_, nAll_, nGood_, nRange_, nHigh_; @@ -126,7 +128,7 @@ class AlCaIsoTracksFilter : public edm::stream::EDFilter >("triggers")), + : trigNames_(iConfig.getParameter>("triggers")), labelGenTrack_(iConfig.getParameter("labelTrack")), labelRecVtx_(iConfig.getParameter("labelVertex")), labelEB_(iConfig.getParameter("labelEBRecHit")), @@ -155,6 +157,7 @@ AlCaIsoTracksFilter::AlCaIsoTracksFilter(const edm::ParameterSet& iConfig, const preScale_(iConfig.getParameter("preScaleFactor")), preScaleH_(iConfig.getParameter("preScaleHigh")), theTrackQuality_(iConfig.getParameter("trackQuality")), + debEvents_(iConfig.getParameter>("debugEvents")), nRun_(0), nAll_(0), nGood_(0), @@ -212,14 +215,12 @@ AlCaIsoTracksFilter::AlCaIsoTracksFilter(const edm::ParameterSet& iConfig, const << pTrackHigh_ << " and prescale factor " << preScaleH_ << " for p > " << pTrackH_ << " Threshold for EB " << hitEthrEB_ << " EE " << hitEthrEE0_ << ":" << hitEthrEE1_ << ":" << hitEthrEE2_ << ":" << hitEthrEE3_ << ":" << hitEthrEELo_ << ":" - << hitEthrEEHi_; + << hitEthrEEHi_ << " and " << debEvents_.size() << " events to be debugged"; for (unsigned int k = 0; k < trigNames_.size(); ++k) edm::LogVerbatim("HcalIsoTrack") << "Trigger[" << k << "] " << trigNames_[k]; } // AlCaIsoTracksFilter::AlCaIsoTracksFilter constructor -AlCaIsoTracksFilter::~AlCaIsoTracksFilter() {} - // // member functions // @@ -228,8 +229,15 @@ AlCaIsoTracksFilter::~AlCaIsoTracksFilter() {} bool AlCaIsoTracksFilter::filter(edm::Event& iEvent, edm::EventSetup const& iSetup) { bool accept(false); ++nAll_; - edm::LogVerbatim("HcalIsoTrack") << "Run " << iEvent.id().run() << " Event " << iEvent.id().event() << " Luminosity " - << iEvent.luminosityBlock() << " Bunch " << iEvent.bunchCrossing(); +#ifdef EDM_ML_DEBUG + bool debug = (debEvents_.empty()) + ? true + : (std::find(debEvents_.begin(), debEvents_.end(), iEvent.id().event()) != debEvents_.end()); + if (debug) + edm::LogVerbatim("HcalIsoTrack") << "Run " << iEvent.id().run() << " Event " << iEvent.id().event() + << " Luminosity " << iEvent.luminosityBlock() << " Bunch " + << iEvent.bunchCrossing(); +#endif //Step1: Find if the event passes one of the chosen triggers bool triggerSatisfied(false); @@ -255,8 +263,11 @@ bool AlCaIsoTracksFilter::filter(edm::Event& iEvent, edm::EventSetup const& iSet if (triggerNames_[iHLT].find(trigNames_[i]) != std::string::npos) { if (hlt > 0) triggerSatisfied = true; - edm::LogVerbatim("HcalIsoTrack") - << triggerNames_[iHLT] << " has got HLT flag " << hlt << ":" << triggerSatisfied; +#ifdef EDM_ML_DEBUG + if (debug) + edm::LogVerbatim("HcalIsoTrack") + << triggerNames_[iHLT] << " has got HLT flag " << hlt << ":" << triggerSatisfied; +#endif if (triggerSatisfied) break; } @@ -266,7 +277,8 @@ bool AlCaIsoTracksFilter::filter(edm::Event& iEvent, edm::EventSetup const& iSet } } #ifdef EDM_ML_DEBUG - edm::LogVerbatim("HcalIsoTrack") << "AlCaIsoTracksFilter:: triggerSatisfied: " << triggerSatisfied; + if (debug) + edm::LogVerbatim("HcalIsoTrack") << "AlCaIsoTracksFilter:: triggerSatisfied: " << triggerSatisfied; #endif //Step2: Get geometry/B-field information @@ -293,7 +305,10 @@ bool AlCaIsoTracksFilter::filter(edm::Event& iEvent, edm::EventSetup const& iSet } else if (beamSpotH.isValid()) { leadPV = beamSpotH->position(); } - edm::LogVerbatim("HcalIsoTrack") << "Primary Vertex " << leadPV; +#ifdef EDM_ML_DEBUG + if (debug) + edm::LogVerbatim("HcalIsoTrack") << "Primary Vertex " << leadPV; +#endif // RecHits auto barrelRecHitsHandle = iEvent.getHandle(tok_EB_); @@ -312,7 +327,8 @@ bool AlCaIsoTracksFilter::filter(edm::Event& iEvent, edm::EventSetup const& iSet foundCollections = false; } #ifdef EDM_ML_DEBUG - edm::LogVerbatim("HcalIsoTrack") << "AlCaIsoTracksFilter:: foundCollections: " << foundCollections; + if (debug) + edm::LogVerbatim("HcalIsoTrack") << "AlCaIsoTracksFilter:: foundCollections: " << foundCollections; #endif //Step3 propagate the tracks to calorimeter surface and find @@ -324,8 +340,9 @@ bool AlCaIsoTracksFilter::filter(edm::Event& iEvent, edm::EventSetup const& iSet std::vector::const_iterator trkDetItr; #ifdef EDM_ML_DEBUG - edm::LogVerbatim("HcalIsoTrack") << "AlCaIsoTracksFilter:: Has " << trkCaloDirections.size() - << " propagated tracks from a total of " << trkCollection->size(); + if (debug) + edm::LogVerbatim("HcalIsoTrack") << "AlCaIsoTracksFilter:: Has " << trkCaloDirections.size() + << " propagated tracks from a total of " << trkCollection->size(); #endif unsigned int nTracks(0), nselTracks(0), ntrin(0), ntrout(0), ntrH(0); for (trkDetItr = trkCaloDirections.begin(), nTracks = 0; trkDetItr != trkCaloDirections.end(); @@ -333,9 +350,10 @@ bool AlCaIsoTracksFilter::filter(edm::Event& iEvent, edm::EventSetup const& iSet const reco::Track* pTrack = &(*(trkDetItr->trkItr)); math::XYZTLorentzVector v4(pTrack->px(), pTrack->py(), pTrack->pz(), pTrack->p()); #ifdef EDM_ML_DEBUG - edm::LogVerbatim("HcalIsoTrack") << "This track : " << nTracks << " (pt|eta|phi|p) :" << pTrack->pt() << "|" - << pTrack->eta() << "|" << pTrack->phi() << "|" << pTrack->p() << " OK HCAL " - << trkDetItr->okHCAL; + if (debug) + edm::LogVerbatim("HcalIsoTrack") + << "This track : " << nTracks << " (pt|eta|phi|p) : " << pTrack->pt() << "|" << pTrack->eta() << "|" + << pTrack->phi() << "|" << pTrack->p() << " OK HCAL " << trkDetItr->okHCAL; #endif //Selection of good track int ieta(0); @@ -345,8 +363,9 @@ bool AlCaIsoTracksFilter::filter(edm::Event& iEvent, edm::EventSetup const& iSet } bool qltyFlag = spr::goodTrack(pTrack, leadPV, selectionParameter_, false); #ifdef EDM_ML_DEBUG - edm::LogVerbatim("HcalIsoTrack") << "qltyFlag|okECAL|okHCAL : " << qltyFlag << "|" << trkDetItr->okECAL << "|" - << trkDetItr->okHCAL; + if (debug) + edm::LogVerbatim("HcalIsoTrack") + << "qltyFlag|okECAL|okHCAL : " << qltyFlag << "|" << trkDetItr->okECAL << "|" << trkDetItr->okHCAL; #endif if (qltyFlag && trkDetItr->okECAL && trkDetItr->okHCAL) { double t_p = pTrack->p(); @@ -386,9 +405,13 @@ bool AlCaIsoTracksFilter::filter(edm::Event& iEvent, edm::EventSetup const& iSet if (eIsolation < eIsolate_) eIsolation = eIsolate_; #ifdef EDM_ML_DEBUG - edm::LogVerbatim("HcalIsoTrack") << "This track : " << nTracks << " (pt|eta|phi|p) :" << pTrack->pt() << "|" - << pTrack->eta() << "|" << pTrack->phi() << "|" << t_p << "e_MIP " << eMipDR - << ":" << eEcal << " Chg Isolation " << hmaxNearP << ":" << eIsolation; + std::string ctype = + (t_p > pTrackMin_ && eMipDR < eEcalMax_ && hmaxNearP < eIsolation) ? " ***** ACCEPT *****" : ""; + if (debug) + edm::LogVerbatim("HcalIsoTrack") + << "This track : " << nTracks << " (pt|eta|phi|p) : " << pTrack->pt() << "|" << pTrack->eta() << "|" + << pTrack->phi() << "|" << t_p << " e_MIP " << eMipDR << ":" << eEcal << " Chg Isolation " << hmaxNearP + << ":" << eIsolation << ctype; #endif if (t_p > pTrackMin_ && eMipDR < eEcalMax_ && hmaxNearP < eIsolation) { if (t_p > pTrackLow_ && t_p < pTrackHigh_) @@ -415,11 +438,18 @@ bool AlCaIsoTracksFilter::filter(edm::Event& iEvent, edm::EventSetup const& iSet else if (nHigh_ % preScaleH_ == 1) accept = true; } +#ifdef EDM_ML_DEBUG + if (debug) + edm::LogVerbatim("HcalIsoTrack") << "Summary Range " << ntrout << " Low " << ntrin << " High " << ntrH + << " Accept " << accept; +#endif } } // Step 4: Return the acceptance flag - if (accept) + if (accept) { ++nGood_; + edm::LogVerbatim("HcalIsoTrackX") << "Run " << iEvent.id().run() << " Event " << iEvent.id().event(); + } return accept; } // AlCaIsoTracksFilter::filter @@ -463,7 +493,7 @@ void AlCaIsoTracksFilter::fillDescriptions(edm::ConfigurationDescriptions& descr desc.add("labelTriggerEvent", edm::InputTag("hltTriggerSummaryAOD", "", "HLT")); desc.add("labelTriggerResult", edm::InputTag("TriggerResults", "", "HLT")); std::vector trigger; - desc.add >("triggers", trigger); + desc.add>("triggers", trigger); desc.add("processName", "HLT"); // following 10 parameters are parameters to select good tracks desc.add("trackQuality", "highPurity"); @@ -500,6 +530,8 @@ void AlCaIsoTracksFilter::fillDescriptions(edm::ConfigurationDescriptions& descr desc.add("preScaleFactor", 1); desc.add("momentumHigh", 60.0); desc.add("preScaleHigh", 1); + std::vector events; + desc.add>("debugEvents", events); descriptions.add("alcaIsoTracksFilter", desc); } diff --git a/Calibration/HcalAlCaRecoProducers/test/AlCaHcalIsoTrk_cfg.py b/Calibration/HcalAlCaRecoProducers/test/AlCaHcalIsoTrk_cfg.py index 519aaf83573c2..7300056e51131 100644 --- a/Calibration/HcalAlCaRecoProducers/test/AlCaHcalIsoTrk_cfg.py +++ b/Calibration/HcalAlCaRecoProducers/test/AlCaHcalIsoTrk_cfg.py @@ -14,7 +14,9 @@ process.GlobalTag.globaltag=autoCond['run2_mc'] process.load("RecoLocalCalo.EcalRecAlgos.EcalSeverityLevelESProducer_cfi") +process.MessageLogger.cerr.FwkReport.reportEvery = cms.untracked.int32(1000) if hasattr(process,'MessageLogger'): + process.MessageLogger.HcalIsoTrackX=dict() process.MessageLogger.HcalIsoTrack=dict() process.options = cms.untracked.PSet( @@ -49,13 +51,25 @@ ), eventAutoFlushCompressedSize = cms.untracked.int32(5242880), outputCommands = process.OutALCARECOHcalCalIsoTrkProducerFilter.outputCommands, -# outputCommands = cms.untracked.vstring( -# 'keep *', -# ), fileName = cms.untracked.string('newPoolOutput.root'), - ) +) process.alcaHcalIsotrkProducer.ignoreTriggers = True +process.alcaHcalIsotrkProducer.debugEvents = [640818633, 640797426, 641251898] +process.alcaHcalIsotrkFilter.debugEvents = [640818633, 640797426, 641251898] +#process.alcaHcalIsotrkProducer.debugEvents = [641031809, 641092744, 640862532, +# 640874735, 641845581, 641144982, +# 641124886, 641240201, 640856725, +# 641709599, 641406943, 640794164, +# 641820644, 641053143, 641458751, +# 641554667, 641621481] +#process.alcaHcalIsotrkFilter.debugEvents = [641031809, 641092744, 640862532, +# 640874735, 641845581, 641144982, +# 641124886, 641240201, 640856725, +# 641709599, 641406943, 640794164, +# 641820644, 641053143, 641458751, +# 641554667, 641621481] + # Path and EndPath definitions process.endjob_step = cms.EndPath(process.endOfProcess) diff --git a/Calibration/HcalAlCaRecoProducers/test/AlCaIsoTrackFilterNoHLT_cfg.py b/Calibration/HcalAlCaRecoProducers/test/AlCaIsoTrackFilterNoHLT_cfg.py index a3a0754a2b8ff..bdcd798819c76 100644 --- a/Calibration/HcalAlCaRecoProducers/test/AlCaIsoTrackFilterNoHLT_cfg.py +++ b/Calibration/HcalAlCaRecoProducers/test/AlCaIsoTrackFilterNoHLT_cfg.py @@ -18,6 +18,11 @@ process.load('Configuration.StandardSequences.EndOfProcess_cff') process.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_cff') +process.MessageLogger.cerr.FwkReport.reportEvery = cms.untracked.int32(1000) +if hasattr(process,'MessageLogger'): + process.MessageLogger.HcalIsoTrackX=dict() + process.MessageLogger.HcalIsoTrack=dict() + process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) ) @@ -26,10 +31,7 @@ process.source = cms.Source("PoolSource", fileNames = cms.untracked.vstring( 'file:/afs/cern.ch/user/h/huwang/work/public/for_Sunanda/RECO_data.root', -# 'file:/afs/cern.ch/user/h/huwang/work/public/for_Sunanda/UL_1TeV_pion_gun_RAW_0_0.root', -# "root://cmseos.fnal.gov//eos/uscms/store/user/lpcrutgers/huiwang/HCAL/UL_DoublePion_E-50_RAW_noPU-2020-12-25/UL_1TeV_pion_gun_RAW_0_0.root" ), - #skipEvents = cms.untracked.uint32(516), secondaryFileNames = cms.untracked.vstring() ) @@ -70,6 +72,14 @@ process.endjob_step = cms.EndPath(process.endOfProcess) process.ALCARECOStreamHcalCalIsoTrkFilterOutPath = cms.EndPath(process.ALCARECOStreamHcalCalIsoTrkFilter) +process.alcaIsoTracksFilter.debugEvents = [640818633, 640797426, 641251898] +#process.alcaIsoTracksFilter.debugEvents = [641031809, 641092744, 640862532, +# 640874735, 641845581, 641144982, +# 641124886, 641240201, 640856725, +# 641709599, 641406943, 640794164, +# 641820644, 641053143, 641458751, +# 641554667, 641621481] + # Schedule definition process.schedule = cms.Schedule(process.pathALCARECOHcalCalIsoTrkFilterNoHLT,process.endjob_step,process.ALCARECOStreamHcalCalIsoTrkFilterOutPath) diff --git a/Calibration/HcalCalibAlgos/interface/CommonUsefulStuff.h b/Calibration/HcalCalibAlgos/interface/CommonUsefulStuff.h index c26f54556e5fa..67194f6e318d9 100644 --- a/Calibration/HcalCalibAlgos/interface/CommonUsefulStuff.h +++ b/Calibration/HcalCalibAlgos/interface/CommonUsefulStuff.h @@ -1,21 +1,11 @@ #ifndef Calibration_HcalCalibALgos_CommonUsefulStuff_h #define Calibration_HcalCalibALgos_CommonUsefulStuff_h -#include "FWCore/Framework/interface/Frameworkfwd.h" -#include "FWCore/Framework/interface/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 "Geometry/CaloGeometry/interface/CaloGeometry.h" #include "DataFormats/DetId/interface/DetId.h" #include "DataFormats/HcalDetId/interface/HcalDetId.h" #include "DataFormats/EcalDetId/interface/EEDetId.h" #include "DataFormats/EcalDetId/interface/EBDetId.h" -#include "Geometry/CaloGeometry/interface/CaloSubdetectorGeometry.h" -#include "Geometry/CaloGeometry/interface/CaloCellGeometry.h" -#include "Geometry/Records/interface/CaloGeometryRecord.h" #include "DataFormats/HcalRecHit/interface/HcalRecHitCollections.h" #include "DataFormats/EcalRecHit/interface/EcalRecHitCollections.h" @@ -24,16 +14,7 @@ #include "DataFormats/GeometryVector/interface/GlobalPoint.h" #include "DataFormats/GeometryVector/interface/GlobalVector.h" - -#include "FWCore/ServiceRegistry/interface/Service.h" #include "CommonTools/UtilAlgos/interface/DeltaR.h" -#include "CommonTools/UtilAlgos/interface/TFileService.h" - -#include "TROOT.h" -#include "TFile.h" -#include "TTree.h" -#include "TH1F.h" -#include "TString.h" /* getDist functions by Jim: /uscms/home/jhirsch/IsoTracks_314/CMSSW_3_1_4/src/JetMETCorrections/IsolatedParticles/interface/FindCaloHit.icc diff --git a/Calibration/HcalCalibAlgos/macros/CalibCorr.C b/Calibration/HcalCalibAlgos/macros/CalibCorr.C index e56367ab46951..98c60921e3cd8 100644 --- a/Calibration/HcalCalibAlgos/macros/CalibCorr.C +++ b/Calibration/HcalCalibAlgos/macros/CalibCorr.C @@ -213,7 +213,41 @@ double puFactor(int type, int ieta, double pmom, double eHcal, double ediff, boo if (debug) std::cout << " d2p " << d2p << ":" << DELTA_CUT << " coeff " << icor << ":" << CONST_COR_COEF[icor] << ":" << LINEAR_COR_COEF[icor] << ":" << SQUARE_COR_COEF[icor] << " Fac " << fac; - } else if (type == 99) { // dlphin + } else if (type == 97) { // dlphin Try 3 + const double CONST_COR_COEF[6] = {0.987617, 0.983421, 0.938622, 0.806662, 0.738354, 0.574195}; + const double LINEAR_COR_COEF[6] = {-0.07018610, -0.2494880, -0.1997290, -0.1769320, -0.2427950, -0.1230480}; + const double SQUARE_COR_COEF[6] = {0, 0, 0.0263541, 0.0257008, 0.0426584, 0.0200361}; + const int PU_IETA_1 = 7; + const int PU_IETA_2 = 16; + const int PU_IETA_3 = 25; + const int PU_IETA_4 = 26; + const int PU_IETA_5 = 27; + unsigned icor = (unsigned(jeta >= PU_IETA_1) + unsigned(jeta >= PU_IETA_2) + unsigned(jeta >= PU_IETA_3) + + unsigned(jeta >= PU_IETA_4) + unsigned(jeta >= PU_IETA_5)); + double deltaCut = (icor > 2) ? 1.0 : DELTA_CUT; + if (d2p > deltaCut) + fac = (CONST_COR_COEF[icor] + LINEAR_COR_COEF[icor] * d2p + SQUARE_COR_COEF[icor] * d2p * d2p); + if (debug) + std::cout << " d2p " << d2p << ":" << DELTA_CUT << " coeff " << icor << ":" << CONST_COR_COEF[icor] << ":" + << LINEAR_COR_COEF[icor] << ":" << SQUARE_COR_COEF[icor] << " Fac " << fac; + } else if (type == 98) { // dlphin Try 2 + const double CONST_COR_COEF[6] = {0.987665, 0.983468, 0.938628, 0.807241, 0.739132, 0.529059}; + const double LINEAR_COR_COEF[6] = {-0.0708906, -0.249995, -0.199683, -0.177692, -0.243436, -0.0668783}; + const double SQUARE_COR_COEF[6] = {0, 0, 0.0263163, 0.0260158, 0.0426864, 0.00398778}; + const int PU_IETA_1 = 7; + const int PU_IETA_2 = 16; + const int PU_IETA_3 = 25; + const int PU_IETA_4 = 26; + const int PU_IETA_5 = 27; + unsigned icor = (unsigned(jeta >= PU_IETA_1) + unsigned(jeta >= PU_IETA_2) + unsigned(jeta >= PU_IETA_3) + + unsigned(jeta >= PU_IETA_4) + unsigned(jeta >= PU_IETA_5)); + double deltaCut = (icor > 2) ? 1.0 : DELTA_CUT; + if (d2p > deltaCut) + fac = (CONST_COR_COEF[icor] + LINEAR_COR_COEF[icor] * d2p + SQUARE_COR_COEF[icor] * d2p * d2p); + if (debug) + std::cout << " d2p " << d2p << ":" << DELTA_CUT << " coeff " << icor << ":" << CONST_COR_COEF[icor] << ":" + << LINEAR_COR_COEF[icor] << ":" << SQUARE_COR_COEF[icor] << " Fac " << fac; + } else if (type == 99) { // dlphin Try 1 const double CONST_COR_COEF[6] = {0.98312, 0.978532, 0.972211, 0.756004, 0.638075, 0.547192}; const double LINEAR_COR_COEF[6] = {-0.0472436, -0.186206, -0.247339, -0.166062, -0.159781, -0.118747}; const double SQUARE_COR_COEF[6] = {0, 0, 0.0356827, 0.0202461, 0.01785078, 0.0123003}; diff --git a/Calibration/HcalCalibAlgos/macros/CalibFitPlots.C b/Calibration/HcalCalibAlgos/macros/CalibFitPlots.C index 542bd9f93a7e3..978e23e765615 100644 --- a/Calibration/HcalCalibAlgos/macros/CalibFitPlots.C +++ b/Calibration/HcalCalibAlgos/macros/CalibFitPlots.C @@ -779,7 +779,7 @@ void FitHistExtended(const char* infile, TH1D* hist2 = (TH1D*)hist1->Clone(name); fitOneGauss(hist2, true, debug); hists.push_back(hist2); - results meaner = fitTwoGauss(hist, debug); + results meaner = fitOneGauss(hist, true, debug); value = meaner.mean; error = meaner.errmean; width = meaner.width; @@ -872,7 +872,8 @@ void FitHistExtended(const char* infile, fitLanGau(hist3, debug); hists.push_back(hist3); } - results meaner0 = fitTwoGauss(hist, debug); + // results meaner0 = fitTwoGauss(hist, debug); + results meaner0 = fitOneGauss(hist, true, debug); value = meaner0.mean; error = meaner0.errmean; double rms; @@ -2197,7 +2198,7 @@ void PlotHistCorrFactors(char* infile1, } } - if (nfile > 1) { + if (nfile > 0) { gStyle->SetCanvasBorderMode(0); gStyle->SetCanvasColor(kWhite); gStyle->SetPadColor(kWhite); diff --git a/Calibration/HcalCalibAlgos/macros/CalibMonitor.C b/Calibration/HcalCalibAlgos/macros/CalibMonitor.C index 4f02bdee4df30..b0b195de9c0cb 100644 --- a/Calibration/HcalCalibAlgos/macros/CalibMonitor.C +++ b/Calibration/HcalCalibAlgos/macros/CalibMonitor.C @@ -1634,19 +1634,21 @@ void GetEntries::Init(TTree *tree, const char *dupFileName) { fChain->SetBranchAddress("t_trackType", &t_trackType, &b_t_trackType); Notify(); - ifstream infile(dupFileName); - if (!infile.is_open()) { - std::cout << "Cannot open " << dupFileName << std::endl; - } else { - while (1) { - Long64_t jentry; - infile >> jentry; - if (!infile.good()) - break; - entries_.push_back(jentry); + if (std::string(dupFileName) != "") { + ifstream infile(dupFileName); + if (!infile.is_open()) { + std::cout << "Cannot open " << dupFileName << std::endl; + } else { + while (1) { + Long64_t jentry; + infile >> jentry; + if (!infile.good()) + break; + entries_.push_back(jentry); + } + infile.close(); + std::cout << "Reads a list of " << entries_.size() << " events from " << dupFileName << std::endl; } - infile.close(); - std::cout << "Reads a list of " << entries_.size() << " events from " << dupFileName << std::endl; } h_tk[0] = new TH1I("Track0", "# of tracks produced", 2000, 0, 2000); diff --git a/Calibration/HcalCalibAlgos/macros/CalibPlotProperties.C b/Calibration/HcalCalibAlgos/macros/CalibPlotProperties.C index 54cd9e38388ad..7bd998ac64ecb 100644 --- a/Calibration/HcalCalibAlgos/macros/CalibPlotProperties.C +++ b/Calibration/HcalCalibAlgos/macros/CalibPlotProperties.C @@ -487,19 +487,21 @@ void CalibPlotProperties::Init(TChain *tree, const char *dupFileName) { fChain->SetBranchAddress("t_HitEnergies3", &t_HitEnergies3, &b_t_HitEnergies3); Notify(); - ifstream infil1(dupFileName); - if (!infil1.is_open()) { - std::cout << "Cannot open duplicate file " << dupFileName << std::endl; - } else { - while (1) { - Long64_t jentry; - infil1 >> jentry; - if (!infil1.good()) - break; - entries_.push_back(jentry); + if (std::string(dupFileName) != "") { + ifstream infil1(dupFileName); + if (!infil1.is_open()) { + std::cout << "Cannot open duplicate file " << dupFileName << std::endl; + } else { + while (1) { + Long64_t jentry; + infil1 >> jentry; + if (!infil1.good()) + break; + entries_.push_back(jentry); + } + infil1.close(); + std::cout << "Reads a list of " << entries_.size() << " events from " << dupFileName << std::endl; } - infil1.close(); - std::cout << "Reads a list of " << entries_.size() << " events from " << dupFileName << std::endl; } char name[20], title[200]; diff --git a/Calibration/HcalCalibAlgos/macros/CalibRho.C b/Calibration/HcalCalibAlgos/macros/CalibRho.C index fe6745d33161e..dff047355ca98 100644 --- a/Calibration/HcalCalibAlgos/macros/CalibRho.C +++ b/Calibration/HcalCalibAlgos/macros/CalibRho.C @@ -3,7 +3,7 @@ // Usage: // .L CalibRho.C+g // -// EHcalVsRho c1(inpFilName, dupFileName); +// EHcalVsRho c1(inpFilName, dupFileName); // c1.LoopFill(maxEta, outFile1, logFile); Fills E vs rho plots // FitEvsRho(logFile, parameterFile, outFile2); Fits the area vs iEta // c1.LoopTest(maxEta, parameterFile, rootFile); Makes the corrected histos @@ -13,7 +13,7 @@ // inpFileName (const char*) File name of the input ROOT tree // or name of the file containing a list of // file names of input ROOT trees -// dupFileName (const char*) Name of the file containing list of entries +// dupFileName (const char*) Name of the file containing list of entries // of duplicate events // maxEta (int) Maximum value of |iEta| // outFile1 (const char*) Output ROOT file name which will contain the @@ -21,7 +21,7 @@ // will provide the estimate of "effective area" // logFile (const char*) Name of the text file which will contain the // effective area for each ieta value -// parameterFile (const char*) Name of the text file with values of the +// parameterFile (const char*) Name of the text file with values of the // fitted parameter set // outFile2 (const char*) Name of the ROOT file with the results of // the fit @@ -60,139 +60,140 @@ #include "CalibCorr.C" class EHcalVsRho { -public : - TChain *fChain; //!pointer to the analyzed TTree or TChain - Int_t fCurrent; //!current Tree number in a TChain - +public: + TChain *fChain; //!pointer to the analyzed TTree or TChain + Int_t fCurrent; //!current Tree number in a TChain + EHcalVsRho(const char *inFile, const char *dupFile); virtual ~EHcalVsRho(); - virtual Int_t Cut(Long64_t entry); - virtual Int_t GetEntry(Long64_t entry); + virtual Int_t Cut(Long64_t entry); + virtual Int_t GetEntry(Long64_t entry); virtual Long64_t LoadTree(Long64_t entry); - virtual void Init(TChain *tree, const char* dupFile); - virtual Bool_t Notify(); - virtual void Show(Long64_t entry = -1); - void LoopFill(int maxEta, const char *outFile, const char *logFile); - void LoopTest(int maxEta, const char *inFile, const char *outFile); - double EffCalc(TH1D*, double, double&, double&); - double getEA(const int ieta, const double* par); + virtual void Init(TChain *tree, const char *dupFile); + virtual Bool_t Notify(); + virtual void Show(Long64_t entry = -1); + void LoopFill(int maxEta, const char *outFile, const char *logFile); + void LoopTest(int maxEta, const char *inFile, const char *outFile); + double EffCalc(TH1D *, double, double &, double &); + double getEA(const int ieta, const double *par); private: - // Declaration of leaf types - Int_t t_Run; - Int_t t_Event; - Int_t t_DataType; - Int_t t_ieta; - Int_t t_iphi; - Double_t t_EventWeight; - Int_t t_nVtx; - Int_t t_nTrk; - Int_t t_goodPV; - Double_t t_l1pt; - Double_t t_l1eta; - Double_t t_l1phi; - Double_t t_l3pt; - Double_t t_l3eta; - Double_t t_l3phi; - Double_t t_p; - Double_t t_pt; - Double_t t_phi; - Double_t t_mindR1; - Double_t t_mindR2; - Double_t t_eMipDR; - Double_t t_eHcal; - Double_t t_eHcal10; - Double_t t_eHcal30; - Double_t t_hmaxNearP; - Double_t t_rhoh; - Bool_t t_selectTk; - Bool_t t_qltyFlag; - Bool_t t_qltyMissFlag; - Bool_t t_qltyPVFlag; - Double_t t_gentrackP; + Int_t t_Run; + Int_t t_Event; + Int_t t_DataType; + Int_t t_ieta; + Int_t t_iphi; + Double_t t_EventWeight; + Int_t t_nVtx; + Int_t t_nTrk; + Int_t t_goodPV; + Double_t t_l1pt; + Double_t t_l1eta; + Double_t t_l1phi; + Double_t t_l3pt; + Double_t t_l3eta; + Double_t t_l3phi; + Double_t t_p; + Double_t t_pt; + Double_t t_phi; + Double_t t_mindR1; + Double_t t_mindR2; + Double_t t_eMipDR; + Double_t t_eHcal; + Double_t t_eHcal10; + Double_t t_eHcal30; + Double_t t_hmaxNearP; + Double_t t_rhoh; + Bool_t t_selectTk; + Bool_t t_qltyFlag; + Bool_t t_qltyMissFlag; + Bool_t t_qltyPVFlag; + Double_t t_gentrackP; std::vector *t_DetIds; - std::vector *t_HitEnergies; - std::vector *t_trgbits; + std::vector *t_HitEnergies; + std::vector *t_trgbits; std::vector *t_DetIds1; std::vector *t_DetIds3; - std::vector *t_HitEnergies1; - std::vector *t_HitEnergies3; - + std::vector *t_HitEnergies1; + std::vector *t_HitEnergies3; + // List of branches - TBranch *b_t_Run; //! - TBranch *b_t_Event; //! - TBranch *b_t_DataType; //! - TBranch *b_t_ieta; //! - TBranch *b_t_iphi; //! - TBranch *b_t_EventWeight; //! - TBranch *b_t_nVtx; //! - TBranch *b_t_nTrk; //! - TBranch *b_t_goodPV; //! - TBranch *b_t_l1pt; //! - TBranch *b_t_l1eta; //! - TBranch *b_t_l1phi; //! - TBranch *b_t_l3pt; //! - TBranch *b_t_l3eta; //! - TBranch *b_t_l3phi; //! - TBranch *b_t_p; //! - TBranch *b_t_pt; //! - TBranch *b_t_phi; //! - TBranch *b_t_mindR1; //! - TBranch *b_t_mindR2; //! - TBranch *b_t_eMipDR; //! - TBranch *b_t_eHcal; //! - TBranch *b_t_eHcal10; //! - TBranch *b_t_eHcal30; //! - TBranch *b_t_hmaxNearP; //! - TBranch *b_t_rhoh; //! - TBranch *b_t_selectTk; //! - TBranch *b_t_qltyFlag; //! - TBranch *b_t_qltyMissFlag; //! - TBranch *b_t_qltyPVFlag; //! - TBranch *b_t_gentrackP; //! - TBranch *b_t_DetIds; //! - TBranch *b_t_HitEnergies; //! - TBranch *b_t_trgbits; //! - TBranch *b_t_DetIds1; //! - TBranch *b_t_DetIds3; //! - TBranch *b_t_HitEnergies1; //! - TBranch *b_t_HitEnergies3; //! - - std::vector entries_; + TBranch *b_t_Run; //! + TBranch *b_t_Event; //! + TBranch *b_t_DataType; //! + TBranch *b_t_ieta; //! + TBranch *b_t_iphi; //! + TBranch *b_t_EventWeight; //! + TBranch *b_t_nVtx; //! + TBranch *b_t_nTrk; //! + TBranch *b_t_goodPV; //! + TBranch *b_t_l1pt; //! + TBranch *b_t_l1eta; //! + TBranch *b_t_l1phi; //! + TBranch *b_t_l3pt; //! + TBranch *b_t_l3eta; //! + TBranch *b_t_l3phi; //! + TBranch *b_t_p; //! + TBranch *b_t_pt; //! + TBranch *b_t_phi; //! + TBranch *b_t_mindR1; //! + TBranch *b_t_mindR2; //! + TBranch *b_t_eMipDR; //! + TBranch *b_t_eHcal; //! + TBranch *b_t_eHcal10; //! + TBranch *b_t_eHcal30; //! + TBranch *b_t_hmaxNearP; //! + TBranch *b_t_rhoh; //! + TBranch *b_t_selectTk; //! + TBranch *b_t_qltyFlag; //! + TBranch *b_t_qltyMissFlag; //! + TBranch *b_t_qltyPVFlag; //! + TBranch *b_t_gentrackP; //! + TBranch *b_t_DetIds; //! + TBranch *b_t_HitEnergies; //! + TBranch *b_t_trgbits; //! + TBranch *b_t_DetIds1; //! + TBranch *b_t_DetIds3; //! + TBranch *b_t_HitEnergies1; //! + TBranch *b_t_HitEnergies3; //! + + std::vector entries_; }; EHcalVsRho::EHcalVsRho(const char *inFile, const char *dupFile) : fChain(0) { char treeName[400]; - sprintf (treeName, "HcalIsoTrkAnalyzer/CalibTree"); - TChain *chain = new TChain(treeName); - std::cout << "Create a chain for " << treeName << " from " << inFile - << std::endl; - if (!fillChain(chain,inFile)) { + sprintf(treeName, "HcalIsoTrkAnalyzer/CalibTree"); + TChain *chain = new TChain(treeName); + std::cout << "Create a chain for " << treeName << " from " << inFile << std::endl; + if (!fillChain(chain, inFile)) { std::cout << "*****No valid tree chain can be obtained*****" << std::endl; } else { - std::cout << "Proceed with a tree chain with " << chain->GetEntries() - << " entries" << std::endl; + std::cout << "Proceed with a tree chain with " << chain->GetEntries() << " entries" << std::endl; Init(chain, dupFile); } } EHcalVsRho::~EHcalVsRho() { - if (!fChain) return; + if (!fChain) + return; delete fChain->GetCurrentFile(); } Int_t EHcalVsRho::GetEntry(Long64_t entry) { // Read contents of entry. - if (!fChain) return 0; + if (!fChain) + return 0; return fChain->GetEntry(entry); } Long64_t EHcalVsRho::LoadTree(Long64_t entry) { // Set the environment to read one entry - if (!fChain) return -5; + if (!fChain) + return -5; Long64_t centry = fChain->LoadTree(entry); - if (centry < 0) return centry; + if (centry < 0) + return centry; if (fChain->GetTreeNumber() != fCurrent) { fCurrent = fChain->GetTreeNumber(); Notify(); @@ -200,7 +201,7 @@ Long64_t EHcalVsRho::LoadTree(Long64_t entry) { return centry; } -void EHcalVsRho::Init(TChain *tree, const char* dupFile) { +void EHcalVsRho::Init(TChain *tree, const char *dupFile) { // The Init() function is called when the selector needs to initialize // a new tree or chain. Typically here the branch addresses and branch // pointers of the tree will be set. @@ -208,7 +209,7 @@ void EHcalVsRho::Init(TChain *tree, const char* dupFile) { // code, but the routine can be extended by the user if needed. // Init() will be called many times when running on PROOF // (once per file to be processed). - + // Set object pointer t_DetIds = 0; t_HitEnergies = 0; @@ -218,7 +219,8 @@ void EHcalVsRho::Init(TChain *tree, const char* dupFile) { t_HitEnergies1 = 0; t_HitEnergies3 = 0; // Set branch addresses and branch pointers - if (!tree) return; + if (!tree) + return; fChain = tree; fCurrent = -1; fChain->SetMakeClass(1); @@ -263,19 +265,21 @@ void EHcalVsRho::Init(TChain *tree, const char* dupFile) { fChain->SetBranchAddress("t_HitEnergies3", &t_HitEnergies3, &b_t_HitEnergies3); Notify(); - ifstream infile(dupFile); - if (!infile.is_open()) { - std::cout << "Cannot open " << dupFile << std::endl; - } else { - while (1) { - Long64_t jentry; - infile >> jentry; - if (!infile.good()) break; - entries_.push_back(jentry); + if (std::string(dupFileName) != "") { + ifstream infile(dupFile); + if (!infile.is_open()) { + std::cout << "Cannot open " << dupFile << std::endl; + } else { + while (1) { + Long64_t jentry; + infile >> jentry; + if (!infile.good()) + break; + entries_.push_back(jentry); + } + infile.close(); + std::cout << "Reads a list of " << entries_.size() << " events from " << dupFile << std::endl; } - infile.close(); - std::cout << "Reads a list of " << entries_.size() << " events from " - << dupFile << std::endl; } } @@ -292,7 +296,8 @@ Bool_t EHcalVsRho::Notify() { void EHcalVsRho::Show(Long64_t entry) { // Print contents of entry. // If entry is not specified, print current entry - if (!fChain) return; + if (!fChain) + return; fChain->Show(entry); } @@ -303,172 +308,183 @@ Int_t EHcalVsRho::Cut(Long64_t) { return 1; } -void EHcalVsRho::LoopFill(int maxEta, const char *outFile, const char *logFile){ - if (fChain == 0) return; - TFile *f1 = new TFile(outFile,"RECREATE"); +void EHcalVsRho::LoopFill(int maxEta, const char *outFile, const char *logFile) { + if (fChain == 0) + return; + TFile *f1 = new TFile(outFile, "RECREATE"); char name[100], Title[100], graph[100], proji[100]; - - std::vector VIsoRho; - std::vector Hcal_corr; - for (int ieta = 0; ieta VIsoRho; + std::vector Hcal_corr; + for (int ieta = 0; ieta < maxEta; ieta++) { + sprintf(name, "IsoRho2d%d", ieta + 1); + sprintf(Title, "Iso vs Rho %d", ieta + 1); + VIsoRho.push_back(new TH2D(name, Title, 30, 0, 30, 25000, 0, 250)); + sprintf(name, "IsoRhoProfile%d", ieta + 1); + Hcal_corr.push_back(new TProfile(name, Title, 30, 0, 30)); } Long64_t nentries = fChain->GetEntriesFast(); std::cout << "Total # of entries: " << nentries << std::endl; Long64_t nbytes = 0, nb = 0; Long64_t kount(0), duplicate(0), good(0); - for (Long64_t jentry=0; jentryGetEntry(jentry); nbytes += nb; + if (ientry < 0) + break; + nb = fChain->GetEntry(jentry); + nbytes += nb; ++kount; - if (kount%100000 == 0) std::cout << "Processing Entry " << kount<=40) && (t_p<=60)) { - VIsoRho[absIeta-1]->Fill(t_rhoh,t_eHcal); - Hcal_corr[absIeta-1]->Fill(t_rhoh,t_eHcal); + if ((absIeta <= maxEta) && (t_p >= 40) && (t_p <= 60)) { + VIsoRho[absIeta - 1]->Fill(t_rhoh, t_eHcal); + Hcal_corr[absIeta - 1]->Fill(t_rhoh, t_eHcal); ++good; } } - std::cout << "Uses " << good << " events out of " << kount << " excluding " - << duplicate << " duplicate events" << std::endl; - - gStyle->SetCanvasBorderMode(0); gStyle->SetCanvasColor(kWhite); - gStyle->SetPadColor(kWhite); gStyle->SetFillColor(kWhite); - gStyle->SetOptTitle(0); gStyle->SetOptFit(1); + std::cout << "Uses " << good << " events out of " << kount << " excluding " << duplicate << " duplicate events" + << std::endl; + + gStyle->SetCanvasBorderMode(0); + gStyle->SetCanvasColor(kWhite); + gStyle->SetPadColor(kWhite); + gStyle->SetFillColor(kWhite); + gStyle->SetOptTitle(0); + gStyle->SetOptFit(1); std::ofstream myfile; myfile.open(logFile); - for (int ieta=0; ietaWrite(); Hcal_corr[ieta]->Write(); - TH2D *his_i = dynamic_cast(VIsoRho[ieta]->Clone()); - his_i ->GetEntries(); + TH2D *his_i = dynamic_cast(VIsoRho[ieta]->Clone()); + his_i->GetEntries(); int dim = his_i->GetXaxis()->GetNbins(); double *xcut, *binc, *errXL, *errXH, *errYL, *errYH; double *errX, *errY; - double errX1, errX2, xmax(0); - - xcut = new double[dim]; - binc = new double[dim]; - errX = new double[dim]; - errY = new double[dim]; - errXL = new double[dim]; - errXH = new double[dim]; - errYL = new double[dim]; - errYH = new double[dim]; - - for (int j= 0; j < dim; j++) { - sprintf (proji,"proj%d-%d",ieta+1,j); - TH1D* h_proj = dynamic_cast(his_i->ProjectionY(proji,j,j+1," ")); - binc[j] = his_i->GetXaxis()->GetBinCenter(j+1); - xcut[j] = EffCalc(h_proj,0.90,errX1,errX2); - - errXL[j]=0.0; - errXH[j]=0.0; - errYL[j]=errX1; - errYH[j]=errX2; - - errX[j]=0.0; - errY[j]=0.0; + double errX1, errX2, xmax(0); + + xcut = new double[dim]; + binc = new double[dim]; + errX = new double[dim]; + errY = new double[dim]; + errXL = new double[dim]; + errXH = new double[dim]; + errYL = new double[dim]; + errYH = new double[dim]; + + for (int j = 0; j < dim; j++) { + sprintf(proji, "proj%d-%d", ieta + 1, j); + TH1D *h_proj = dynamic_cast(his_i->ProjectionY(proji, j, j + 1, " ")); + binc[j] = his_i->GetXaxis()->GetBinCenter(j + 1); + xcut[j] = EffCalc(h_proj, 0.90, errX1, errX2); + + errXL[j] = 0.0; + errXH[j] = 0.0; + errYL[j] = errX1; + errYH[j] = errX2; + + errX[j] = 0.0; + errY[j] = 0.0; h_proj->Write(); - if (xcut[j] > xmax) xmax = xcut[j]; + if (xcut[j] > xmax) + xmax = xcut[j]; } - TGraphAsymmErrors * Isovsrho = new TGraphAsymmErrors(dim,binc,xcut,errXL,errXH,errYL,errYH); - sprintf(graph,"IsovsRho%d",ieta+1); - sprintf(name,"EvsRho%d",ieta+1); + TGraphAsymmErrors *Isovsrho = new TGraphAsymmErrors(dim, binc, xcut, errXL, errXH, errYL, errYH); + sprintf(graph, "IsovsRho%d", ieta + 1); + sprintf(name, "EvsRho%d", ieta + 1); - TF1 *fnc = new TF1("fnc","[1]*x + [0]",4,13); - TFitResultPtr fitI = Isovsrho->Fit("fnc","+QSR"); + TF1 *fnc = new TF1("fnc", "[1]*x + [0]", 4, 13); + TFitResultPtr fitI = Isovsrho->Fit("fnc", "+QSR"); double ic = fnc->GetParameter(1); double err = fitI->FitResult::Error(1); - myfile << ieta+1 << " " << ic << " " << err << std::endl; - std::cout << "Fit " << ieta+1 << " " << fnc->GetParameter(0) << " " - << fitI->FitResult::Error(0) << " " << ic << " " << err << "\n"; + myfile << ieta + 1 << " " << ic << " " << err << std::endl; + std::cout << "Fit " << ieta + 1 << " " << fnc->GetParameter(0) << " " << fitI->FitResult::Error(0) << " " << ic + << " " << err << "\n"; gStyle->SetOptFit(1); - TCanvas *pad = new TCanvas(graph,name,0,10,1200,400); + TCanvas *pad = new TCanvas(graph, name, 0, 10, 1200, 400); pad->SetRightMargin(0.10); pad->SetTopMargin(0.10); Isovsrho->SetMarkerStyle(24); Isovsrho->SetMarkerSize(0.4); - Isovsrho->GetXaxis()->SetRangeUser(0,15); + Isovsrho->GetXaxis()->SetRangeUser(0, 15); Isovsrho->GetXaxis()->SetTitle("#rho"); Isovsrho->GetXaxis()->SetLabelSize(0.04); Isovsrho->GetXaxis()->SetTitleSize(0.06); Isovsrho->GetXaxis()->SetTitleOffset(0.8); - Isovsrho->GetYaxis()->SetRangeUser(0,1.25*xmax); + Isovsrho->GetYaxis()->SetRangeUser(0, 1.25 * xmax); Isovsrho->GetYaxis()->SetTitle("Energy (GeV)"); Isovsrho->GetYaxis()->SetLabelSize(0.04); Isovsrho->GetYaxis()->SetTitleSize(0.06); Isovsrho->GetYaxis()->SetTitleOffset(0.6); Isovsrho->Draw("AP"); pad->Update(); - TPaveStats* st1 = (TPaveStats*)Isovsrho->GetListOfFunctions()->FindObject("stats"); + TPaveStats *st1 = (TPaveStats *)Isovsrho->GetListOfFunctions()->FindObject("stats"); if (st1 != nullptr) { - st1->SetY1NDC(0.78); st1->SetY2NDC(0.90); - st1->SetX1NDC(0.65); st1->SetX2NDC(0.90); + st1->SetY1NDC(0.78); + st1->SetY2NDC(0.90); + st1->SetX1NDC(0.65); + st1->SetX2NDC(0.90); } pad->Write(); } myfile.close(); f1->Close(); -} - -double EHcalVsRho::EffCalc(TH1D* h, double perc, double & errXL, - double & errXH) { - double eff, eff_err=0.0, xCut=0.0; +} + +double EHcalVsRho::EffCalc(TH1D *h, double perc, double &errXL, double &errXH) { + double eff, eff_err = 0.0, xCut = 0.0; int tot = h->GetEntries(); int integ = 0; errXL = 0.0; errXH = 0.0; - for(int i = 0; i < (h->GetXaxis()->GetNbins()+1 ); i++) { + for (int i = 0; i < (h->GetXaxis()->GetNbins() + 1); i++) { xCut = h->GetXaxis()->GetBinLowEdge(i); integ += h->GetBinContent(i); - - if (integ != 0 && tot != 0 ) { - eff = (integ*1.0/tot); - eff_err = sqrt ( eff * ( 1 - eff ) / tot ) ; + + if (integ != 0 && tot != 0) { + eff = (integ * 1.0 / tot); + eff_err = sqrt(eff * (1 - eff) / tot); } else { eff = 0.0; } - if (eff > perc) break; + if (eff > perc) + break; } - if (eff == 0.0) xCut = 0.0; + if (eff == 0.0) + xCut = 0.0; errXL = eff_err; errXH = eff_err; return xCut; } void EHcalVsRho::LoopTest(int maxEta, const char *inFile, const char *outFile) { + if (fChain == 0) + return; - if (fChain == 0) return; - - TFile *f1 = new TFile(outFile,"RECREATE"); - std::map histo, histo_uncorr; + TFile *f1 = new TFile(outFile, "RECREATE"); + std::map histo, histo_uncorr; char name[100], title[100]; - for (int ieta =-maxEta; ieta<=maxEta; ieta++) { - sprintf(name, "MPV%d",ieta); - sprintf(title, "Corrected Response (i#eta = %d)", ieta-30); - histo[ieta] = new TH1D(name, title, 100, 0, 2); - sprintf(name, "MPVUn%d",ieta); - sprintf(title, "Uncorrected Response (i#eta = %d)", ieta-30); + for (int ieta = -maxEta; ieta <= maxEta; ieta++) { + sprintf(name, "MPV%d", ieta); + sprintf(title, "Corrected Response (i#eta = %d)", ieta - 30); + histo[ieta] = new TH1D(name, title, 100, 0, 2); + sprintf(name, "MPVUn%d", ieta); + sprintf(title, "Uncorrected Response (i#eta = %d)", ieta - 30); histo_uncorr[ieta] = new TH1D(name, title, 100, 0, 2); } - std::cout << "Initialized histograms from " << -maxEta << ":" << maxEta<<"\n"; - + std::cout << "Initialized histograms from " << -maxEta << ":" << maxEta << "\n"; + double par[10]; ifstream myReadFile; myReadFile.open(inFile); @@ -481,64 +497,66 @@ void EHcalVsRho::LoopTest(int maxEta, const char *inFile, const char *outFile) { } myReadFile.close(); std::cout << "Reads " << npar << " parameters:"; - for (int k=0; k 40) && (t_p < 60.0)); - if (select) { + + select = ((t_qltyFlag) && (t_selectTk) && (t_hmaxNearP < 10.0) && (t_eMipDR < 1.0) && (t_p > 40) && (t_p < 60.0)); + if (select) { double corr_eHcal = 0.0; int absIeta = abs(t_ieta); ++good; if (absIeta <= maxEta) { - corr_eHcal = t_eHcal - t_rhoh*getEA(absIeta,par); - double myEovP = corr_eHcal/(t_p-t_eMipDR); - double myEovP_uncorr = t_eHcal/(t_p-t_eMipDR); - histo[t_ieta]->Fill(myEovP); - histo_uncorr[t_ieta]->Fill(myEovP_uncorr); + corr_eHcal = t_eHcal - t_rhoh * getEA(absIeta, par); + double myEovP = corr_eHcal / (t_p - t_eMipDR); + double myEovP_uncorr = t_eHcal / (t_p - t_eMipDR); + histo[t_ieta]->Fill(myEovP); + histo_uncorr[t_ieta]->Fill(myEovP_uncorr); } } } - for (std::map::iterator itr=histo.begin(); - itr != histo.end(); ++itr) itr->second->Write(); - for (std::map::iterator itr=histo_uncorr.begin(); - itr != histo_uncorr.end(); ++itr) itr->second->Write(); + for (std::map::iterator itr = histo.begin(); itr != histo.end(); ++itr) + itr->second->Write(); + for (std::map::iterator itr = histo_uncorr.begin(); itr != histo_uncorr.end(); ++itr) + itr->second->Write(); f1->Close(); - std::cout << "Processes " << good << " out of " << kount << " events with " - << duplicate << " duplicate entries" << std::endl; + std::cout << "Processes " << good << " out of " << kount << " events with " << duplicate << " duplicate entries" + << std::endl; } -double EHcalVsRho::getEA(const int eta, const double* par) { +double EHcalVsRho::getEA(const int eta, const double *par) { double eA; - if (eta<20) + if (eta < 20) eA = par[0]; - else - eA = (((par[5]*eta+par[4])*eta+par[3])*eta+par[2])*eta+par[1]; + else + eA = (((par[5] * eta + par[4]) * eta + par[3]) * eta + par[2]) * eta + par[1]; return eA; } void FitEvsRho(const char *inFile, const char *outFile, const char *rootFile) { - - const int ndim=30; + const int ndim = 30; double EA[ndim] = {0.0}; - double errEA[ndim]={0.0}; - double ietaEA[ndim]={0.0}; + double errEA[ndim] = {0.0}; + double ietaEA[ndim] = {0.0}; ifstream myReadFile; myReadFile.open(inFile); @@ -546,20 +564,25 @@ void FitEvsRho(const char *inFile, const char *outFile, const char *rootFile) { if (myReadFile.is_open()) { while (!myReadFile.eof()) { myReadFile >> ietaEA[ii] >> EA[ii] >> errEA[ii]; - if (EA[ii] < 0) EA[ii] = 0; + if (EA[ii] < 0) + EA[ii] = 0; ii++; } } myReadFile.close(); std::cout << "Reads " << ii << " points from " << inFile << std::endl; - gStyle->SetCanvasBorderMode(0); gStyle->SetCanvasColor(kWhite); - gStyle->SetPadColor(kWhite); gStyle->SetFillColor(kWhite); - gStyle->SetOptTitle(0); gStyle->SetOptStat(0); + gStyle->SetCanvasBorderMode(0); + gStyle->SetCanvasColor(kWhite); + gStyle->SetPadColor(kWhite); + gStyle->SetFillColor(kWhite); + gStyle->SetOptTitle(0); + gStyle->SetOptStat(0); gStyle->SetOptFit(0); - TFile *f1 = new TFile(rootFile,"RECREATE"); - TGraphErrors * eA = new TGraphErrors(ii,ietaEA,EA,errEA,errEA); - eA->SetMarkerStyle(20); eA->SetMarkerColor(4); + TFile *f1 = new TFile(rootFile, "RECREATE"); + TGraphErrors *eA = new TGraphErrors(ii, ietaEA, EA, errEA, errEA); + eA->SetMarkerStyle(20); + eA->SetMarkerColor(4); eA->SetLineColor(2); eA->GetXaxis()->SetTitle("i#eta"); eA->GetXaxis()->SetTitleOffset(0.6); @@ -568,24 +591,24 @@ void FitEvsRho(const char *inFile, const char *outFile, const char *rootFile) { eA->GetYaxis()->SetTitleOffset(0.6); eA->GetYaxis()->SetTitleSize(0.06); - Double_t par[6]; - const int nmid=19; - TF1 *g1 = new TF1("g1","pol0",1,nmid); - TF1 *g2 = new TF1("g2","pol4",nmid,ii); + Double_t par[6]; + const int nmid = 19; + TF1 *g1 = new TF1("g1", "pol0", 1, nmid); + TF1 *g2 = new TF1("g2", "pol4", nmid, ii); - eA->Fit(g1,"R"); - eA->Fit(g2,"R+"); + eA->Fit(g1, "R"); + eA->Fit(g2, "R+"); g1->GetParameters(&par[0]); g2->GetParameters(&par[1]); - TCanvas *c2 = new TCanvas("EA vs #eta","EA vs ieta",0,10,1200,400); + TCanvas *c2 = new TCanvas("EA vs #eta", "EA vs ieta", 0, 10, 1200, 400); eA->Draw("AP"); c2->Write(); f1->Close(); - + ofstream params; params.open(outFile); - for (int i=0; i<6; i++) { + for (int i = 0; i < 6; i++) { params << par[i] << std::endl; std::cout << "Parameter[" << i << "] = " << par[i] << std::endl; } @@ -593,89 +616,96 @@ void FitEvsRho(const char *inFile, const char *outFile, const char *rootFile) { } void FitEovPwithRho(int maxEta, const char *inFile, const char *outFile) { - TFile *file = new TFile(inFile); - std::map histo, histo_uncorr; + std::map histo, histo_uncorr; char name[100]; - for (int ieta =-maxEta; ieta<=maxEta; ieta++) { - sprintf(name, "MPV%d",ieta); - TH1D* h0 = (TH1D*)file->FindObjectAny(name); - histo[ieta] = (h0 != 0) ? (TH1D*)(h0->Clone()) : 0; - sprintf(name, "MPVUn%d",ieta); - TH1D* h1 = (TH1D*)file->FindObjectAny(name); - histo_uncorr[ieta] = (h1 != 0) ? (TH1D*)(h1->Clone()) : 0; + for (int ieta = -maxEta; ieta <= maxEta; ieta++) { + sprintf(name, "MPV%d", ieta); + TH1D *h0 = (TH1D *)file->FindObjectAny(name); + histo[ieta] = (h0 != 0) ? (TH1D *)(h0->Clone()) : 0; + sprintf(name, "MPVUn%d", ieta); + TH1D *h1 = (TH1D *)file->FindObjectAny(name); + histo_uncorr[ieta] = (h1 != 0) ? (TH1D *)(h1->Clone()) : 0; } - -//TFile *f1 = - new TFile(outFile,"RECREATE"); + + //TFile *f1 = + new TFile(outFile, "RECREATE"); double xlim = maxEta + 0.5; - TH1D* EovPvsieta = new TH1D("Corrected","Corrected",2*maxEta+1,-xlim,xlim); - TH1D* EovPvsieta_uncorr = new TH1D("Uncorrect","Uncorrect",2*maxEta+1,-xlim,xlim); + TH1D *EovPvsieta = new TH1D("Corrected", "Corrected", 2 * maxEta + 1, -xlim, xlim); + TH1D *EovPvsieta_uncorr = new TH1D("Uncorrect", "Uncorrect", 2 * maxEta + 1, -xlim, xlim); - TF1* fnc = new TF1("fnc","gaus"); + TF1 *fnc = new TF1("fnc", "gaus"); unsigned int k1(0), k2(0); - for (int ieta=-maxEta; ieta<=maxEta; ieta++) { - if (ieta == 0) continue; + for (int ieta = -maxEta; ieta <= maxEta; ieta++) { + if (ieta == 0) + continue; if (histo[ieta] != 0) { double mean = histo[ieta]->GetMean(); - double rms = histo[ieta]->GetRMS(); - TFitResultPtr FitG = histo[ieta]->Fit("fnc","QRWLS","",mean-rms,mean+rms); - double a = fnc->GetParameter(1); + double rms = histo[ieta]->GetRMS(); + TFitResultPtr FitG = histo[ieta]->Fit("fnc", "QRWLS", "", mean - rms, mean + rms); + double a = fnc->GetParameter(1); double err = FitG->FitResult::Error(1); histo[ieta]->Write(); ++k1; - int ibin = ieta+maxEta+1; - EovPvsieta->SetBinContent(ibin,a); - EovPvsieta->SetBinError(ibin,err); - std::cout << "Correct[" << k1 << "] " << ieta << " a " << a << " +- " - << err << std::endl; + int ibin = ieta + maxEta + 1; + EovPvsieta->SetBinContent(ibin, a); + EovPvsieta->SetBinError(ibin, err); + std::cout << "Correct[" << k1 << "] " << ieta << " a " << a << " +- " << err << std::endl; } - + if (histo_uncorr[ieta] != 0) { double mean = histo_uncorr[ieta]->GetMean(); - double rms = histo_uncorr[ieta]->GetRMS(); - TFitResultPtr FitG = histo_uncorr[ieta]->Fit("fnc","QRWLS","",mean-rms,mean+rms); - double a = fnc->GetParameter(1); + double rms = histo_uncorr[ieta]->GetRMS(); + TFitResultPtr FitG = histo_uncorr[ieta]->Fit("fnc", "QRWLS", "", mean - rms, mean + rms); + double a = fnc->GetParameter(1); double err = FitG->FitResult::Error(1); histo_uncorr[ieta]->Write(); ++k2; - int ibin = ieta+maxEta+1; - EovPvsieta_uncorr->SetBinContent(ibin,a); - EovPvsieta_uncorr->SetBinError(ibin,err); - std::cout << "Correct[" << k2 << "] " << ieta << " a " << a << " +- " - << err << std::endl; + int ibin = ieta + maxEta + 1; + EovPvsieta_uncorr->SetBinContent(ibin, a); + EovPvsieta_uncorr->SetBinError(ibin, err); + std::cout << "Correct[" << k2 << "] " << ieta << " a " << a << " +- " << err << std::endl; } } - 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->SetOptTitle(0); - gStyle->SetOptStat(10); gStyle->SetOptFit(1); - TCanvas *c3 = new TCanvas("E/P vs ieta","E/P vs ieta",0,10,1200,400); + gStyle->SetOptStat(10); + gStyle->SetOptFit(1); + TCanvas *c3 = new TCanvas("E/P vs ieta", "E/P vs ieta", 0, 10, 1200, 400); EovPvsieta->GetXaxis()->SetTitle("i#eta"); EovPvsieta->GetYaxis()->SetTitle("MPV[E_{Hcal}/(p_{Track}-E_{Ecal})]"); - EovPvsieta->SetMarkerStyle(20); EovPvsieta->SetMarkerColor(2); + EovPvsieta->SetMarkerStyle(20); + EovPvsieta->SetMarkerColor(2); EovPvsieta->SetMarkerSize(1.0); - EovPvsieta->Fit("pol0","+QRWLS","",-maxEta,maxEta); + EovPvsieta->Fit("pol0", "+QRWLS", "", -maxEta, maxEta); - EovPvsieta_uncorr->SetMarkerStyle(24); EovPvsieta_uncorr->SetMarkerColor(4); + EovPvsieta_uncorr->SetMarkerStyle(24); + EovPvsieta_uncorr->SetMarkerColor(4); EovPvsieta_uncorr->SetMarkerSize(1.0); - EovPvsieta->GetYaxis()->SetRangeUser(0.5,2.0); + EovPvsieta->GetYaxis()->SetRangeUser(0.5, 2.0); EovPvsieta->Draw(); c3->Update(); - TPaveStats* st1 = (TPaveStats*)EovPvsieta->GetListOfFunctions()->FindObject("stats"); + TPaveStats *st1 = (TPaveStats *)EovPvsieta->GetListOfFunctions()->FindObject("stats"); if (st1 != nullptr) { - st1->SetY1NDC(0.81); st1->SetY2NDC(0.90); - st1->SetX1NDC(0.65); st1->SetX2NDC(0.90); + st1->SetY1NDC(0.81); + st1->SetY2NDC(0.90); + st1->SetX1NDC(0.65); + st1->SetX2NDC(0.90); } EovPvsieta_uncorr->Draw("sames"); c3->Update(); - st1 = (TPaveStats*)EovPvsieta_uncorr->GetListOfFunctions()->FindObject("stats"); + st1 = (TPaveStats *)EovPvsieta_uncorr->GetListOfFunctions()->FindObject("stats"); std::cout << st1 << std::endl; if (st1 != nullptr) { - st1->SetY1NDC(0.78); st1->SetY2NDC(0.81); - st1->SetX1NDC(0.65); st1->SetX2NDC(0.90); + st1->SetY1NDC(0.78); + st1->SetY2NDC(0.81); + st1->SetX1NDC(0.65); + st1->SetX2NDC(0.90); } c3->Modified(); c3->Update(); @@ -683,67 +713,85 @@ void FitEovPwithRho(int maxEta, const char *inFile, const char *outFile) { EovPvsieta_uncorr->Write(); } -void PlotEvsRho(const char* inFile, int eta=0, int type=0, bool save=false) { - - gStyle->SetCanvasBorderMode(0); gStyle->SetCanvasColor(kWhite); - gStyle->SetPadColor(kWhite); gStyle->SetFillColor(kWhite); +void PlotEvsRho(const char *inFile, int eta = 0, int type = 0, bool save = false) { + gStyle->SetCanvasBorderMode(0); + gStyle->SetCanvasColor(kWhite); + gStyle->SetPadColor(kWhite); + gStyle->SetFillColor(kWhite); gStyle->SetOptTitle(0); - gStyle->SetOptStat(1110); gStyle->SetOptFit(10); - + gStyle->SetOptStat(1110); + gStyle->SetOptFit(10); + TFile *file = new TFile(inFile); int etamin = (eta == 0) ? ((type == 0) ? 1 : 25) : eta; int etamax = (eta == 0) ? 25 : eta; for (int it = etamin; it <= etamax; ++it) { char name[50]; - sprintf (name, "IsovsRho%d", it); - TCanvas* pad; + sprintf(name, "IsovsRho%d", it); + TCanvas *pad; if (type == 0) { - pad = (TCanvas*)(file->FindObjectAny(name)); + pad = (TCanvas *)(file->FindObjectAny(name)); pad->Draw(); } else { - sprintf (name, "MPV%d", it); - pad = new TCanvas(name,name,0,10,800,500); + sprintf(name, "MPV%d", it); + pad = new TCanvas(name, name, 0, 10, 800, 500); pad->SetRightMargin(0.10); pad->SetTopMargin(0.10); - TH1D* h1 = (TH1D*)(file->FindObjectAny(name)); - sprintf (name, "MPVUn%d", it); - TH1D* h2 = (TH1D*)(file->FindObjectAny(name)); + TH1D *h1 = (TH1D *)(file->FindObjectAny(name)); + sprintf(name, "MPVUn%d", it); + TH1D *h2 = (TH1D *)(file->FindObjectAny(name)); double ymx1 = h1->GetMaximum(); double ymx2 = h2->GetMaximum(); double ymax = (ymx1 > ymx2) ? ymx1 : ymx2; - h1->GetXaxis()->SetRangeUser(0.5,2.0); - h2->GetXaxis()->SetRangeUser(0.5,2.0); - h1->GetYaxis()->SetRangeUser(0,1.25*ymax); - h2->GetYaxis()->SetRangeUser(0,1.25*ymax); - h1->GetXaxis()->SetTitleSize(0.048); h1->GetXaxis()->SetTitleOffset(0.8); + h1->GetXaxis()->SetRangeUser(0.5, 2.0); + h2->GetXaxis()->SetRangeUser(0.5, 2.0); + h1->GetYaxis()->SetRangeUser(0, 1.25 * ymax); + h2->GetYaxis()->SetRangeUser(0, 1.25 * ymax); + h1->GetXaxis()->SetTitleSize(0.048); + h1->GetXaxis()->SetTitleOffset(0.8); h1->GetXaxis()->SetTitle("E_{Hcal}/(p-E_{Ecal})"); - h1->GetYaxis()->SetTitleSize(0.048); h1->GetYaxis()->SetTitleOffset(0.8); + h1->GetYaxis()->SetTitleSize(0.048); + h1->GetYaxis()->SetTitleOffset(0.8); h1->GetYaxis()->SetTitle("Tracks"); - h1->SetLineColor(2); h1->Draw(); - pad->Modified(); pad->Update(); - TPaveStats* st1 = (TPaveStats*)h1->GetListOfFunctions()->FindObject("stats"); + h1->SetLineColor(2); + h1->Draw(); + pad->Modified(); + pad->Update(); + TPaveStats *st1 = (TPaveStats *)h1->GetListOfFunctions()->FindObject("stats"); if (st1 != nullptr) { - st1->SetLineColor(2); st1->SetTextColor(2); - st1->SetY1NDC(0.75); st1->SetY2NDC(0.90); - st1->SetX1NDC(0.65); st1->SetX2NDC(0.90); + st1->SetLineColor(2); + st1->SetTextColor(2); + st1->SetY1NDC(0.75); + st1->SetY2NDC(0.90); + st1->SetX1NDC(0.65); + st1->SetX2NDC(0.90); } - h2->SetLineColor(4); h2->Draw("sames"); - pad->Modified(); pad->Update(); - TPaveStats* st2 = (TPaveStats*)h2->GetListOfFunctions()->FindObject("stats"); + h2->SetLineColor(4); + h2->Draw("sames"); + pad->Modified(); + pad->Update(); + TPaveStats *st2 = (TPaveStats *)h2->GetListOfFunctions()->FindObject("stats"); if (st2 != nullptr) { - st2->SetLineColor(4); st2->SetTextColor(4); - st2->SetY1NDC(0.60); st2->SetY2NDC(0.75); - st2->SetX1NDC(0.65); st2->SetX2NDC(0.90); + st2->SetLineColor(4); + st2->SetTextColor(4); + st2->SetY1NDC(0.60); + st2->SetY2NDC(0.75); + st2->SetX1NDC(0.65); + st2->SetX2NDC(0.90); } - pad->Modified(); pad->Update(); - TF1* f1 = (TF1*)h1->GetListOfFunctions()->FindObject("fnc"); - if (f1 != nullptr) f1->SetLineColor(2); - TF1* f2 = (TF1*)h2->GetListOfFunctions()->FindObject("fnc"); - if (f2 != nullptr) f2->SetLineColor(4); - pad->Modified(); pad->Update(); + pad->Modified(); + pad->Update(); + TF1 *f1 = (TF1 *)h1->GetListOfFunctions()->FindObject("fnc"); + if (f1 != nullptr) + f1->SetLineColor(2); + TF1 *f2 = (TF1 *)h2->GetListOfFunctions()->FindObject("fnc"); + if (f2 != nullptr) + f2->SetLineColor(4); + pad->Modified(); + pad->Update(); } if (save) { - sprintf (name, "%s.pdf", pad->GetName()); + sprintf(name, "%s.pdf", pad->GetName()); pad->Print(name); } } diff --git a/Calibration/HcalCalibAlgos/macros/isotrackApplyRegressor.py b/Calibration/HcalCalibAlgos/macros/isotrackApplyRegressor.py index 737c30a549a4a..af41cb0f0ec1b 100644 --- a/Calibration/HcalCalibAlgos/macros/isotrackApplyRegressor.py +++ b/Calibration/HcalCalibAlgos/macros/isotrackApplyRegressor.py @@ -13,17 +13,17 @@ import numpy as np import matplotlib.pyplot as plt import argparse -import keras -from keras.models import Sequential -from keras.layers import Dense -from keras.layers import Dropout -from keras.utils.np_utils import to_categorical -from keras.utils import plot_model -from keras import regularizers +import tensorflow.keras +from tensorflow.keras.models import Sequential +from tensorflow.keras.layers import Dense +from tensorflow.keras.layers import Dropout +from tensorflow.keras.utils import to_categorical +from tensorflow.keras.utils import plot_model +from tensorflow.keras import regularizers from sklearn.metrics import roc_curve, auc -from keras.layers import Activation -from keras import backend as K -from keras.models import load_model +from tensorflow.keras.layers import Activation +from tensorflow.keras import backend as K +from tensorflow.keras.models import load_model import uproot diff --git a/Calibration/HcalCalibAlgos/macros/isotrackTrainRegressor.py b/Calibration/HcalCalibAlgos/macros/isotrackTrainRegressor.py index aeeb2c078ff00..4abcc261de16a 100644 --- a/Calibration/HcalCalibAlgos/macros/isotrackTrainRegressor.py +++ b/Calibration/HcalCalibAlgos/macros/isotrackTrainRegressor.py @@ -10,17 +10,17 @@ import numpy as np import matplotlib.pyplot as plt import argparse -import keras -from keras.models import Sequential -from keras.layers import Dense -from keras.layers import Dropout -from keras.utils.np_utils import to_categorical -from keras.utils import plot_model -from keras import regularizers +import tensorflow.keras +from tensorflow.keras.models import Sequential +from tensorflow.keras.layers import Dense +from tensorflow.keras.layers import Dropout +from tensorflow.keras.utils import to_categorical +from tensorflow.keras.utils import plot_model +from tensorflow.keras import regularizers from sklearn.metrics import roc_curve, auc -from keras.layers import Activation -from keras import backend as K -from keras.models import save_model +from tensorflow.keras.layers import Activation +from tensorflow.keras import backend as K +from tensorflow.keras.models import save_model diff --git a/Calibration/HcalCalibAlgos/plugins/HcalIsoTrackAnalyzer.cc b/Calibration/HcalCalibAlgos/plugins/HcalIsoTrackAnalyzer.cc index 0867b71b6e7d1..c6946eda58bbf 100644 --- a/Calibration/HcalCalibAlgos/plugins/HcalIsoTrackAnalyzer.cc +++ b/Calibration/HcalCalibAlgos/plugins/HcalIsoTrackAnalyzer.cc @@ -46,6 +46,7 @@ class HcalIsoTrackAnalyzer : public edm::one::EDAnalyzer debEvents_; edm::EDGetTokenT tokIsoTrkVar_; edm::EDGetTokenT tokIsoTrkEvt_; unsigned int nRun_, nRange_, nLow_, nHigh_; @@ -81,6 +82,7 @@ HcalIsoTrackAnalyzer::HcalIsoTrackAnalyzer(const edm::ParameterSet& iConfig) dataType_(iConfig.getUntrackedParameter("dataType", 0)), labelIsoTkVar_(iConfig.getParameter("isoTrackVarLabel")), labelIsoTkEvt_(iConfig.getParameter("isoTrackEvtLabel")), + debEvents_(iConfig.getParameter>("debugEvents")), tokIsoTrkVar_(consumes(labelIsoTkVar_)), tokIsoTrkEvt_(consumes(labelIsoTkEvt_)), nRun_(0), @@ -94,7 +96,8 @@ HcalIsoTrackAnalyzer::HcalIsoTrackAnalyzer(const edm::ParameterSet& iConfig) edm::LogVerbatim("HcalIsoTrack") << "Parameters read from config file \n\t momentumLow_ " << pTrackLow_ << "\t momentumHigh_ " << pTrackHigh_ << "\t useRaw_ " << useRaw_ - << "\t dataType_ " << dataType_; + << "\t dataType_ " << dataType_ << " and " << debEvents_.size() + << " events to be debugged"; } void HcalIsoTrackAnalyzer::analyze(edm::Event const& iEvent, edm::EventSetup const& iSetup) { @@ -102,8 +105,13 @@ void HcalIsoTrackAnalyzer::analyze(edm::Event const& iEvent, edm::EventSetup con t_Event = iEvent.id().event(); t_DataType = dataType_; #ifdef EDM_ML_DEBUG - edm::LogVerbatim("HcalIsoTrack") << "Run " << t_Run << " Event " << t_Event << " type " << t_DataType - << " Luminosity " << iEvent.luminosityBlock() << " Bunch " << iEvent.bunchCrossing(); + bool debug = (debEvents_.empty()) + ? true + : (std::find(debEvents_.begin(), debEvents_.end(), iEvent.id().event()) != debEvents_.end()); + if (debug) + edm::LogVerbatim("HcalIsoTrack") << "Run " << t_Run << " Event " << t_Event << " type " << t_DataType + << " Luminosity " << iEvent.luminosityBlock() << " Bunch " + << iEvent.bunchCrossing(); #endif // Fill from IsoTrkCalibVariables collection @@ -111,8 +119,10 @@ void HcalIsoTrackAnalyzer::analyze(edm::Event const& iEvent, edm::EventSetup con if (isotrkCalibColl.isValid()) { auto isotrkCalib = isotrkCalibColl.product(); #ifdef EDM_ML_DEBUG - edm::LogVerbatim("HcalIsoTrack") << "Finds HcalIsoTrkCalibVariablesCollection with " << isotrkCalib->size() - << " entries"; + if (debug) + edm::LogVerbatim("HcalIsoTrack") << "Finds HcalIsoTrkCalibVariablesCollection with " << isotrkCalib->size() + << " entries"; + int k(0); #endif for (auto itr = isotrkCalib->begin(); itr != isotrkCalib->end(); ++itr) { t_ieta = itr->ieta_; @@ -124,6 +134,13 @@ void HcalIsoTrackAnalyzer::analyze(edm::Event const& iEvent, edm::EventSetup con t_p = itr->p_; t_pt = itr->pt_; t_phi = itr->phi_; +#ifdef EDM_ML_DEBUG + ++k; + if (debug) + edm::LogVerbatim("HcalIsoTrack") << "Track " << k << " p:pt:phi " << t_p << ":" << t_pt << ":" << t_phi + << " nvtx:ntrk:goodPV:wt " << t_nVtx << ":" << t_nTrk << ":" << t_goodPV << ":" + << t_EventWeight << " ieta:iphi " << t_ieta << ":" << t_iphi; +#endif t_l1pt = itr->l1pt_; t_l1eta = itr->l1eta_; t_l1phi = itr->l1phi_; @@ -132,21 +149,43 @@ void HcalIsoTrackAnalyzer::analyze(edm::Event const& iEvent, edm::EventSetup con t_l3phi = itr->l3phi_; t_mindR1 = itr->mindR1_; t_mindR2 = itr->mindR2_; +#ifdef EDM_ML_DEBUG + if (debug) + edm::LogVerbatim("HcalIsoTrack") << "L1 pt:eta:phi " << t_l1pt << ":" << t_l1eta << ":" << t_l1phi + << " L3 pt:eta:phi " << t_l3pt << ":" << t_l3eta << ":" << t_l3phi << " R1:R2 " + << t_mindR1 << ":" << t_mindR2; +#endif t_eMipDR = itr->eMipDR_[0]; t_eMipDR2 = itr->eMipDR_[1]; t_eMipDR3 = itr->eMipDR_[2]; t_eMipDR4 = itr->eMipDR_[3]; t_eMipDR5 = itr->eMipDR_[4]; +#ifdef EDM_ML_DEBUG + if (debug) + edm::LogVerbatim("HcalIsoTrack") << "eMIPDR 1:2:3:4:5 " << t_eMipDR << ":" << t_eMipDR2 << ":" << t_eMipDR3 + << ":" << t_eMipDR4 << ":" << t_eMipDR5; +#endif t_hmaxNearP = itr->hmaxNearP_; - t_gentrackP = itr->gentrackP_; t_emaxNearP = itr->emaxNearP_; t_eAnnular = itr->eAnnular_; t_hAnnular = itr->hAnnular_; +#ifdef EDM_ML_DEBUG + if (debug) + edm::LogVerbatim("HcalIsoTrack") << "emaxNearP:hmaxNearP " << t_emaxNearP << ":" << t_hmaxNearP + << " eAnnlar:hAnnular" << t_eAnnular << ":" << t_hAnnular; +#endif + t_gentrackP = itr->gentrackP_; t_rhoh = itr->rhoh_; t_selectTk = itr->selectTk_; t_qltyFlag = itr->qltyFlag_; t_qltyMissFlag = itr->qltyMissFlag_; t_qltyPVFlag = itr->qltyPVFlag_; +#ifdef EDM_ML_DEBUG + if (debug) + edm::LogVerbatim("HcalIsoTrack") << "gentrackP " << t_gentrackP << " rhoh " << t_rhoh + << " qltyFlag:qltyMissFlag:qltyPVFlag:selectTk " << t_qltyFlag << ":" + << t_qltyMissFlag << ":" << t_qltyPVFlag << ":" << t_selectTk; +#endif t_trgbits = itr->trgbits_; t_DetIds = itr->detIds_; t_DetIds1 = itr->detIds1_; @@ -173,7 +212,12 @@ void HcalIsoTrackAnalyzer::analyze(edm::Event const& iEvent, edm::EventSetup con t_HitEnergies1 = itr->hitEnergies1_; t_HitEnergies3 = itr->hitEnergies3_; } +#ifdef EDM_ML_DEBUG + if (debug) + edm::LogVerbatim("HcalIsoTrack") << "eHcal:eHcal10:eHCal30 " << t_eHcal << ":" << t_eHcal10 << t_eHcal30; +#endif tree->Fill(); + edm::LogVerbatim("HcalIsoTrackX") << "Run " << t_Run << " Event " << t_Event; if (t_p < pTrackLow_) { ++nLow_; @@ -192,8 +236,9 @@ void HcalIsoTrackAnalyzer::analyze(edm::Event const& iEvent, edm::EventSetup con if (isotrkEventColl.isValid()) { auto isotrkEvent = isotrkEventColl.product(); #ifdef EDM_ML_DEBUG - edm::LogVerbatim("HcalIsoTrack") << "Finds HcalIsoTrkEventVariablesCollection with " << isotrkEvent->size() - << " entries"; + if (debug) + edm::LogVerbatim("HcalIsoTrack") << "Finds HcalIsoTrkEventVariablesCollection with " << isotrkEvent->size() + << " entries"; #endif auto itr = isotrkEvent->begin(); if (itr != isotrkEvent->end()) { @@ -306,6 +351,8 @@ void HcalIsoTrackAnalyzer::fillDescriptions(edm::ConfigurationDescriptions& desc desc.addUntracked("dataType", 0); desc.add("isoTrackVarLabel", edm::InputTag("alcaHcalIsotrkProducer", "HcalIsoTrack")); desc.add("isoTrackEvtLabel", edm::InputTag("alcaHcalIsotrkProducer", "HcalIsoTrackEvent")); + std::vector events; + desc.add>("debugEvents", events); descriptions.add("hcalIsoTrackAnalyzer", desc); } diff --git a/Calibration/HcalCalibAlgos/plugins/HcalIsoTrkAnalyzer.cc b/Calibration/HcalCalibAlgos/plugins/HcalIsoTrkAnalyzer.cc index 707d03b5c6710..5901f313b5d1f 100644 --- a/Calibration/HcalCalibAlgos/plugins/HcalIsoTrkAnalyzer.cc +++ b/Calibration/HcalCalibAlgos/plugins/HcalIsoTrkAnalyzer.cc @@ -157,6 +157,7 @@ class HcalIsoTrkAnalyzer : public edm::one::EDAnalyzer oldID_, newDepth_; const bool hep17_; + const std::vector debEvents_; unsigned int nRun_, nLow_, nHigh_; double a_charIsoR_, a_coneR1_, a_coneR2_; const HcalDDDRecConstants* hdc_; @@ -174,7 +175,7 @@ class HcalIsoTrkAnalyzer : public edm::one::EDAnalyzer tok_hbhe_; edm::EDGetTokenT tok_cala_; edm::EDGetTokenT tok_ew_; - edm::EDGetTokenT > tok_alg_; + edm::EDGetTokenT> tok_alg_; edm::EDGetTokenT tok_Muon_; edm::ESGetToken tok_ddrec_; @@ -207,10 +208,12 @@ class HcalIsoTrkAnalyzer : public edm::one::EDAnalyzer*t_ietaAll, *t_ietaGood, *t_trackType; + + bool debug_; }; HcalIsoTrkAnalyzer::HcalIsoTrkAnalyzer(const edm::ParameterSet& iConfig) - : trigNames_(iConfig.getParameter >("triggers")), + : trigNames_(iConfig.getParameter>("triggers")), theTrackQuality_(iConfig.getParameter("trackQuality")), processName_(iConfig.getParameter("processName")), l1Filter_(iConfig.getParameter("l1Filter")), @@ -256,9 +259,10 @@ HcalIsoTrkAnalyzer::HcalIsoTrkAnalyzer(const edm::ParameterSet& iConfig) labelHBHE_(iConfig.getParameter("labelHBHERecHit")), labelTower_(iConfig.getParameter("labelCaloTower")), l1TrigName_(iConfig.getUntrackedParameter("l1TrigName", "L1_SingleJet60")), - oldID_(iConfig.getUntrackedParameter >("oldID")), - newDepth_(iConfig.getUntrackedParameter >("newDepth")), + oldID_(iConfig.getUntrackedParameter>("oldID")), + newDepth_(iConfig.getUntrackedParameter>("newDepth")), hep17_(iConfig.getUntrackedParameter("hep17")), + debEvents_(iConfig.getParameter>("debugEvents")), nRun_(0), nLow_(0), nHigh_(0), @@ -309,7 +313,7 @@ HcalIsoTrkAnalyzer::HcalIsoTrkAnalyzer(const edm::ParameterSet& iConfig) tok_ew_ = consumes(edm::InputTag("generator")); tok_parts_ = consumes(edm::InputTag("genParticles")); tok_cala_ = consumes(labelTower_); - tok_alg_ = consumes >(algTag); + tok_alg_ = consumes>(algTag); tok_Muon_ = consumes(labelMuon); if (modnam.empty()) { @@ -362,7 +366,7 @@ HcalIsoTrkAnalyzer::HcalIsoTrkAnalyzer(const edm::ParameterSet& iConfig) << dataType_ << "\t mode_ " << mode_ << "\t unCorrect_ " << unCorrect_ << "\t collapseDepth_ " << collapseDepth_ << "\t L1TrigName_ " << l1TrigName_ << "\nThreshold for EB " << hitEthrEB_ << " EE " << hitEthrEE0_ << ":" << hitEthrEE1_ << ":" << hitEthrEE2_ << ":" << hitEthrEE3_ << ":" << hitEthrEELo_ << ":" - << hitEthrEEHi_; + << hitEthrEEHi_ << " and " << debEvents_.size() << " events to be debugged"; edm::LogVerbatim("HcalIsoTrack") << "Process " << processName_ << " L1Filter:" << l1Filter_ << " L2Filter:" << l2Filter_ << " L3Filter:" << l3Filter_; for (unsigned int k = 0; k < trigNames_.size(); ++k) { @@ -398,9 +402,14 @@ void HcalIsoTrkAnalyzer::analyze(edm::Event const& iEvent, edm::EventSetup const t_Run = iEvent.id().run(); t_Event = iEvent.id().event(); t_DataType = dataType_; + debug_ = (debEvents_.empty()) + ? true + : (std::find(debEvents_.begin(), debEvents_.end(), iEvent.id().event()) != debEvents_.end()); #ifdef EDM_ML_DEBUG - edm::LogVerbatim("HcalIsoTrack") << "Run " << t_Run << " Event " << t_Event << " type " << t_DataType - << " Luminosity " << iEvent.luminosityBlock() << " Bunch " << iEvent.bunchCrossing(); + if (debug_) + edm::LogVerbatim("HcalIsoTrack") << "Run " << t_Run << " Event " << t_Event << " type " << t_DataType + << " Luminosity " << iEvent.luminosityBlock() << " Bunch " + << iEvent.bunchCrossing(); #endif //Get magnetic field and ECAL channel status const MagneticField* bField = &iSetup.getData(tok_bFieldH_); @@ -459,9 +468,10 @@ void HcalIsoTrkAnalyzer::analyze(edm::Event const& iEvent, edm::EventSetup const } t_allvertex = t_goodPV; #ifdef EDM_ML_DEBUG - edm::LogVerbatim("HcalIsoTrack") << "Primary Vertex " << leadPV << " out of " << t_goodPV << " vertex"; - if (beamSpotH.isValid()) { - edm::LogVerbatim("HcalIsoTrack") << " Beam Spot " << beamSpotH->position(); + if (debug_) { + edm::LogVerbatim("HcalIsoTrack") << "Primary Vertex " << leadPV << " out of " << t_goodPV << " vertex"; + if (beamSpotH.isValid()) + edm::LogVerbatim("HcalIsoTrack") << " Beam Spot " << beamSpotH->position(); } #endif // RecHits @@ -502,8 +512,9 @@ void HcalIsoTrkAnalyzer::analyze(edm::Event const& iEvent, edm::EventSetup const t_trgbits->clear(); t_hltbits->clear(); #ifdef EDM_ML_DEBUG - edm::LogVerbatim("HcalIsoTrack") << "# of propagated tracks " << t_TracksProp << " out of " << t_Tracks - << " with Trigger " << ignoreTrigger_; + if (debug_) + edm::LogVerbatim("HcalIsoTrack") << "# of propagated tracks " << t_TracksProp << " out of " << t_Tracks + << " with Trigger " << ignoreTrigger_; #endif //Trigger @@ -517,7 +528,7 @@ void HcalIsoTrkAnalyzer::analyze(edm::Event const& iEvent, edm::EventSetup const if (!ignoreTrigger_) { //L1 l1GtUtils_->retrieveL1(iEvent, iSetup, tok_alg_); - const std::vector >& finalDecisions = l1GtUtils_->decisionsFinal(); + const std::vector>& finalDecisions = l1GtUtils_->decisionsFinal(); for (const auto& decision : finalDecisions) { if (decision.first.find(l1TrigName_) != std::string::npos) { t_L1Bit = decision.second; @@ -525,8 +536,9 @@ void HcalIsoTrkAnalyzer::analyze(edm::Event const& iEvent, edm::EventSetup const } } #ifdef EDM_ML_DEBUG - edm::LogVerbatim("HcalIsoTrack") << "Trigger Information for " << l1TrigName_ << " is " << t_L1Bit - << " from a list of " << finalDecisions.size() << " decisions"; + if (debug_) + edm::LogVerbatim("HcalIsoTrack") << "Trigger Information for " << l1TrigName_ << " is " << t_L1Bit + << " from a list of " << finalDecisions.size() << " decisions"; #endif //HLT @@ -544,8 +556,9 @@ void HcalIsoTrkAnalyzer::analyze(edm::Event const& iEvent, edm::EventSetup const if (hlt > 0) t_TrigPass = true; #ifdef EDM_ML_DEBUG - edm::LogVerbatim("HcalIsoTrack") - << "This trigger " << names[iHLT] << " Flag " << hlt << ":" << t_trgbits->at(i); + if (debug_) + edm::LogVerbatim("HcalIsoTrack") + << "This trigger " << names[iHLT] << " Flag " << hlt << ":" << t_trgbits->at(i); #endif } } @@ -553,8 +566,9 @@ void HcalIsoTrkAnalyzer::analyze(edm::Event const& iEvent, edm::EventSetup const } } #ifdef EDM_ML_DEBUG - edm::LogVerbatim("HcalIsoTrack") << "HLT Information shows " << t_TrigPass << ":" << trigNames_.empty() << ":" - << okC; + if (debug_) + edm::LogVerbatim("HcalIsoTrack") << "HLT Information shows " << t_TrigPass << ":" << trigNames_.empty() << ":" + << okC; #endif } @@ -613,7 +627,8 @@ void HcalIsoTrkAnalyzer::analyze(edm::Event const& iEvent, edm::EventSetup const for (unsigned int imodule = 0; imodule < moduleLabels.size(); imodule++) { if (label.find(moduleLabels[imodule]) != std::string::npos) { #ifdef EDM_ML_DEBUG - edm::LogVerbatim("HcalIsoTrack") << "FilterName " << label; + if (debug_) + edm::LogVerbatim("HcalIsoTrack") << "FilterName " << label; #endif for (unsigned int ifiltrKey = 0; ifiltrKey < triggerEvent.filterKeys(ifilter).size(); ++ifiltrKey) { Keys.push_back(triggerEvent.filterKeys(ifilter)[ifiltrKey]); @@ -627,14 +642,16 @@ void HcalIsoTrkAnalyzer::analyze(edm::Event const& iEvent, edm::EventSetup const vecL1.push_back(v4); } #ifdef EDM_ML_DEBUG - edm::LogVerbatim("HcalIsoTrack") - << "key " << ifiltrKey << " : pt " << TO.pt() << " eta " << TO.eta() << " phi " << TO.phi() - << " mass " << TO.mass() << " Id " << TO.id(); + if (debug_) + edm::LogVerbatim("HcalIsoTrack") + << "key " << ifiltrKey << " : pt " << TO.pt() << " eta " << TO.eta() << " phi " << TO.phi() + << " mass " << TO.mass() << " Id " << TO.id(); #endif } #ifdef EDM_ML_DEBUG - edm::LogVerbatim("HcalIsoTrack") - << "sizes " << vecL1.size() << ":" << vecL2.size() << ":" << vecL3.size(); + if (debug_) + edm::LogVerbatim("HcalIsoTrack") + << "sizes " << vecL1.size() << ":" << vecL2.size() << ":" << vecL3.size(); #endif } } @@ -645,7 +662,8 @@ void HcalIsoTrkAnalyzer::analyze(edm::Event const& iEvent, edm::EventSetup const for (unsigned int i = 0; i < vecL2.size(); i++) { double dr = dR(vecL1[0], vecL2[i]); #ifdef EDM_ML_DEBUG - edm::LogVerbatim("HcalIsoTrack") << "lvl2[" << i << "] dR " << dr; + if (debug_) + edm::LogVerbatim("HcalIsoTrack") << "lvl2[" << i << "] dR " << dr; #endif if (dr < mindR1) { mindR1 = dr; @@ -653,7 +671,8 @@ void HcalIsoTrkAnalyzer::analyze(edm::Event const& iEvent, edm::EventSetup const } } #ifdef EDM_ML_DEBUG - edm::LogVerbatim("HcalIsoTrack") << "L2 object closest to L1 " << mindRvec1 << " at Dr " << mindR1; + if (debug_) + edm::LogVerbatim("HcalIsoTrack") << "L2 object closest to L1 " << mindRvec1 << " at Dr " << mindR1; #endif if (!vecL1.empty()) { @@ -700,8 +719,9 @@ void HcalIsoTrkAnalyzer::analyze(edm::Event const& iEvent, edm::EventSetup const } } #ifdef EDM_ML_DEBUG - edm::LogVerbatim("HcalIsoTrack") << "Final results on selected tracks " << t_TracksSaved << ":" << t_TracksLoose - << ":" << t_TracksTight; + if (debug_) + edm::LogVerbatim("HcalIsoTrack") << "Final results on selected tracks " << t_TracksSaved << ":" << t_TracksLoose + << ":" << t_TracksTight; #endif t_TrigPassSel = (t_TracksSaved > 0); tree2->Fill(); @@ -835,7 +855,7 @@ void HcalIsoTrkAnalyzer::fillDescriptions(edm::ConfigurationDescriptions& descri "HLT_PFJet400", "HLT_PFJet450", "HLT_PFJet500"}; - desc.add >("triggers", trig); + desc.add>("triggers", trig); desc.add("processName", "HLT"); desc.add("l1Filter", ""); desc.add("l2Filter", "L2Filter"); @@ -906,9 +926,11 @@ void HcalIsoTrkAnalyzer::fillDescriptions(edm::ConfigurationDescriptions& descri desc.addUntracked("l1TrigName", "L1_SingleJet60"); desc.addUntracked("outMode", 11); std::vector dummy; - desc.addUntracked >("oldID", dummy); - desc.addUntracked >("newDepth", dummy); + desc.addUntracked>("oldID", dummy); + desc.addUntracked>("newDepth", dummy); desc.addUntracked("hep17", false); + std::vector events; + desc.add>("debugEvents", events); descriptions.add("HcalIsoTrkAnalyzer", desc); } @@ -944,8 +966,9 @@ std::array HcalIsoTrkAnalyzer::fillTree(std::vectorphi(); #ifdef EDM_ML_DEBUG - edm::LogVerbatim("HcalIsoTrack") << "This track : " << nTracks << " (pt|eta|phi|p) :" << t_pt << "|" - << pTrack->eta() << "|" << t_phi << "|" << t_p; + if (debug_) + edm::LogVerbatim("HcalIsoTrack") << "This track : " << nTracks << " (pt|eta|phi|p) : " << t_pt << "|" + << pTrack->eta() << "|" << t_phi << "|" << t_p; #endif t_mindR2 = 999; for (unsigned int k = 0; k < vecL3.size(); ++k) { @@ -956,7 +979,8 @@ std::array HcalIsoTrkAnalyzer::fillTree(std::vector HcalIsoTrkAnalyzer::fillTree(std::vectorokECAL << "|" - << trkDetItr->okHCAL << " eIsolation " << eIsolation; + if (debug_) + edm::LogVerbatim("HcalIsoTrack") << "qltyFlag|okECAL|okHCAL : " << qltyFlag << "|" << trkDetItr->okECAL << "|" + << trkDetItr->okHCAL << " eIsolation " << eIsolation; #endif t_qltyFlag = (qltyFlag && trkDetItr->okECAL && trkDetItr->okHCAL); bool notMuon = (muonh.isValid()) ? notaMuon(pTrack, muonh) : true; @@ -1015,7 +1040,8 @@ std::array HcalIsoTrkAnalyzer::fillTree(std::vector HcalIsoTrkAnalyzer::fillTree(std::vector HcalIsoTrkAnalyzer::fillTree(std::vector HcalIsoTrkAnalyzer::fillTree(std::vector HcalIsoTrkAnalyzer::fillTree(std::vector HcalIsoTrkAnalyzer::fillTree(std::vector HcalIsoTrkAnalyzer::fillTree(std::vectoreta() << "|" << t_phi << "|" << t_p << " Generator Level p " - << t_gentrackP; - edm::LogVerbatim("HcalIsoTrack") << "e_MIP " << t_eMipDR << " Chg Isolation " << t_hmaxNearP << " eHcal" - << t_eHcal << " ieta " << t_ieta << " Quality " << t_qltyMissFlag << ":" - << t_qltyPVFlag << ":" << t_selectTk; - for (unsigned int ll = 0; ll < t_DetIds->size(); ll++) { + if (debug_) { edm::LogVerbatim("HcalIsoTrack") - << "det id is = " << t_DetIds->at(ll) << " hit enery is = " << t_HitEnergies->at(ll); - } - for (unsigned int ll = 0; ll < t_DetIds1->size(); ll++) { - edm::LogVerbatim("HcalIsoTrack") - << "det id is = " << t_DetIds1->at(ll) << " hit enery is = " << t_HitEnergies1->at(ll); - } - for (unsigned int ll = 0; ll < t_DetIds3->size(); ll++) { + << "This track : " << nTracks << " (pt|eta|phi|p) : " << t_pt << "|" << pTrack->eta() << "|" << t_phi + << "|" << t_p << " Generator Level p " << t_gentrackP; edm::LogVerbatim("HcalIsoTrack") - << "det id is = " << t_DetIds3->at(ll) << " hit enery is = " << t_HitEnergies3->at(ll); + << "e_MIP " << t_eMipDR << " Chg Isolation " << t_hmaxNearP << " eHcal" << t_eHcal << " ieta " << t_ieta + << " Quality " << t_qltyMissFlag << ":" << t_qltyPVFlag << ":" << t_selectTk; + for (unsigned int ll = 0; ll < t_DetIds->size(); ll++) { + edm::LogVerbatim("HcalIsoTrack") + << "det id is = " << t_DetIds->at(ll) << " hit enery is = " << t_HitEnergies->at(ll); + } + for (unsigned int ll = 0; ll < t_DetIds1->size(); ll++) { + edm::LogVerbatim("HcalIsoTrack") + << "det id is = " << t_DetIds1->at(ll) << " hit enery is = " << t_HitEnergies1->at(ll); + } + for (unsigned int ll = 0; ll < t_DetIds3->size(); ll++) { + edm::LogVerbatim("HcalIsoTrack") + << "det id is = " << t_DetIds3->at(ll) << " hit enery is = " << t_HitEnergies3->at(ll); + } } #endif bool accept(false); @@ -1254,6 +1287,7 @@ std::array HcalIsoTrkAnalyzer::fillTree(std::vectorFill(); + edm::LogVerbatim("HcalIsoTrackX") << "Run " << t_RunNo << " Event " << t_EventNo; nSave++; int type(0); if (t_eMipDR < 1.0) { @@ -1271,8 +1305,10 @@ std::array HcalIsoTrkAnalyzer::fillTree(std::vectoremplace_back(type); } #ifdef EDM_ML_DEBUG - for (unsigned int k = 0; k < t_trgbits->size(); k++) { - edm::LogVerbatim("HcalIsoTrack") << "trigger bit is = " << t_trgbits->at(k); + if (debug_) { + for (unsigned int k = 0; k < t_trgbits->size(); k++) { + edm::LogVerbatim("HcalIsoTrack") << "trigger bit is = " << t_trgbits->at(k); + } } #endif } @@ -1329,7 +1365,8 @@ double HcalIsoTrkAnalyzer::rhoh(const edm::Handle& tower) { evt_smdq = (sumPFNallSMDQH2[sumPFNallSMDQH2.size() / 2] + sumPFNallSMDQH2[(sumPFNallSMDQH2.size() - 2) / 2]) / 2.; double rhoh = evt_smdq / (etadist_ * phidist_); #ifdef EDM_ML_DEBUG - edm::LogVerbatim("HcalIsoTrack") << "Rho " << evt_smdq << ":" << rhoh; + if (debug_) + edm::LogVerbatim("HcalIsoTrack") << "Rho " << evt_smdq << ":" << rhoh; #endif return rhoh; } @@ -1410,12 +1447,14 @@ void HcalIsoTrkAnalyzer::storeEnergy(int indx, } } #ifdef EDM_ML_DEBUG - edm::LogVerbatim("HcalIsoTrack") << "Input to storeEnergy with " << ids.size() << " cells"; - for (unsigned int k = 0; k < ids.size(); ++k) - edm::LogVerbatim("HcalIsoTrack") << "Hit [" << k << "] " << HcalDetId(ids[k]) << " E " << edet[k]; - edm::LogVerbatim("HcalIsoTrack") << "Output of storeEnergy with " << detIds->size() << " cells and Etot " << eHcal; - for (unsigned int k = 0; k < detIds->size(); ++k) - edm::LogVerbatim("HcalIsoTrack") << "Hit [" << k << "] " << HcalDetId((*detIds)[k]) << " E " << (*hitEnergies)[k]; + if (debug_) { + edm::LogVerbatim("HcalIsoTrack") << "Input to storeEnergy with " << ids.size() << " cells"; + for (unsigned int k = 0; k < ids.size(); ++k) + edm::LogVerbatim("HcalIsoTrack") << "Hit [" << k << "] " << HcalDetId(ids[k]) << " E " << edet[k]; + edm::LogVerbatim("HcalIsoTrack") << "Output of storeEnergy with " << detIds->size() << " cells and Etot " << eHcal; + for (unsigned int k = 0; k < detIds->size(); ++k) + edm::LogVerbatim("HcalIsoTrack") << "Hit [" << k << "] " << HcalDetId((*detIds)[k]) << " E " << (*hitEnergies)[k]; + } #endif } diff --git a/Calibration/HcalCalibAlgos/plugins/ValidIsoTrkCalib.cc b/Calibration/HcalCalibAlgos/plugins/ValidIsoTrkCalib.cc index dffecbb577041..ace99c9b1d445 100644 --- a/Calibration/HcalCalibAlgos/plugins/ValidIsoTrkCalib.cc +++ b/Calibration/HcalCalibAlgos/plugins/ValidIsoTrkCalib.cc @@ -24,10 +24,11 @@ See the twiki page for details: // user include files #include "FWCore/Framework/interface/Frameworkfwd.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" +#include "FWCore/Framework/interface/Event.h" +#include "FWCore/Framework/interface/MakerMacros.h" +#include "FWCore/ParameterSet/interface/ParameterSet.h" +#include "FWCore/ServiceRegistry/interface/Service.h" +#include "CommonTools/UtilAlgos/interface/TFileService.h" #include "DataFormats/HcalRecHit/interface/HcalRecHitCollections.h" #include "DataFormats/EcalRecHit/interface/EcalRecHitCollections.h" diff --git a/Calibration/HcalCalibAlgos/test/DiJetAnalyzer.cc b/Calibration/HcalCalibAlgos/test/DiJetAnalyzer.cc index 7ad3da9edb3e5..217f4403135fa 100644 --- a/Calibration/HcalCalibAlgos/test/DiJetAnalyzer.cc +++ b/Calibration/HcalCalibAlgos/test/DiJetAnalyzer.cc @@ -5,8 +5,10 @@ // #include "DiJetAnalyzer.h" +#include "FWCore/ServiceRegistry/interface/Service.h" DiJetAnalyzer::DiJetAnalyzer(const edm::ParameterSet& iConfig) { + usesResource(TFileService::kSharedResource); // set parameters pfJetCollName_ = iConfig.getParameter("pfJetCollName"); pfJetCorrName_ = iConfig.getParameter("pfJetCorrName"); @@ -32,8 +34,6 @@ DiJetAnalyzer::DiJetAnalyzer(const edm::ParameterSet& iConfig) { tok_geom_ = esConsumes(); } -DiJetAnalyzer::~DiJetAnalyzer() {} - // // member functions // @@ -1131,11 +1131,11 @@ void DiJetAnalyzer::analyze(const edm::Event& iEvent, const edm::EventSetup& evS // ------------ method called once each job just before starting event loop ------------ void DiJetAnalyzer::beginJob() { // book histograms - rootfile_ = new TFile(rootHistFilename_.c_str(), "RECREATE"); - h_PassSelPF_ = new TH1D("h_PassSelectionPF", "Selection Pass Failures PFJets", 200, -0.5, 199.5); + edm::Service fs; + h_PassSelPF_ = fs->make("h_PassSelectionPF", "Selection Pass Failures PFJets", 200, -0.5, 199.5); - tree_ = new TTree("dijettree", "tree for dijet balancing"); + tree_ = fs->make("dijettree", "tree for dijet balancing"); tree_->Branch("tpfjet_pt", &tpfjet_pt_, "tpfjet_pt/F"); tree_->Branch("tpfjet_p", &tpfjet_p_, "tpfjet_p/F"); @@ -1286,15 +1286,7 @@ void DiJetAnalyzer::beginJob() { } // ------------ method called once each job just after ending the event loop ------------ -void DiJetAnalyzer::endJob() { - // write histograms - rootfile_->cd(); - - h_PassSelPF_->Write(); - tree_->Write(); - - rootfile_->Close(); -} +void DiJetAnalyzer::endJob() {} // helper function diff --git a/Calibration/HcalCalibAlgos/test/DiJetAnalyzer.h b/Calibration/HcalCalibAlgos/test/DiJetAnalyzer.h index e27e1596d4c5b..2d502a0107abf 100644 --- a/Calibration/HcalCalibAlgos/test/DiJetAnalyzer.h +++ b/Calibration/HcalCalibAlgos/test/DiJetAnalyzer.h @@ -15,8 +15,9 @@ #include "TClonesArray.h" // user include files +#include "CommonTools/UtilAlgos/interface/TFileService.h" #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" @@ -50,7 +51,6 @@ // forward declarations class TH1D; class TH2D; -class TFile; class TTree; // @@ -83,15 +83,15 @@ class JetCorretPair : protected std::pair { private: }; -class DiJetAnalyzer : public edm::EDAnalyzer { +class DiJetAnalyzer : public edm::one::EDAnalyzer { public: explicit DiJetAnalyzer(const edm::ParameterSet&); - ~DiJetAnalyzer(); + ~DiJetAnalyzer() override = default; private: - virtual void beginJob(); //(const edm::EventSetup&); - virtual void analyze(const edm::Event&, const edm::EventSetup&); - virtual void endJob(); + void beginJob() override; //(const edm::EventSetup&); + void analyze(const edm::Event&, const edm::EventSetup&) override; + void endJob() override; // parameters bool debug_; // print debug statements @@ -118,8 +118,6 @@ class DiJetAnalyzer : public edm::EDAnalyzer { edm::ESGetToken tok_geom_; // root file/histograms - TFile* rootfile_; - TH1D* h_PassSelPF_; TTree* tree_; diff --git a/Calibration/HcalCalibAlgos/test/GammaJetAnalysis.cc b/Calibration/HcalCalibAlgos/test/GammaJetAnalysis.cc index 809c249e53167..ed5c83cd2ad92 100644 --- a/Calibration/HcalCalibAlgos/test/GammaJetAnalysis.cc +++ b/Calibration/HcalCalibAlgos/test/GammaJetAnalysis.cc @@ -136,6 +136,7 @@ inline unsigned int helper_findTrigger(const std::vector& list, con GammaJetAnalysis::GammaJetAnalysis(const edm::ParameterSet& iConfig) : hltPrescaleProvider_(iConfig, consumesCollector(), *this) { + usesResource(TFileService::kSharedResource); // set parameters debug_ = iConfig.getUntrackedParameter("debug", 0); debugHLTTrigNames = iConfig.getUntrackedParameter("debugHLTTrigNames", 1); @@ -1405,10 +1406,9 @@ void GammaJetAnalysis::analyze(const edm::Event& iEvent, const edm::EventSetup& // ------------ method called once each job just before starting event loop ------------ void GammaJetAnalysis::beginJob() { - rootfile_ = new TFile(rootHistFilename_.c_str(), "RECREATE"); + edm::Service fs; if (doPFJets_) { - pf_tree_ = new TTree("pf_gammajettree", "tree for gamma+jet balancing using PFJets"); - assert(pf_tree_); + pf_tree_ = fs->make("pf_gammajettree", "tree for gamma+jet balancing using PFJets"); } for (int iJet = 0; iJet < 2; iJet++) { @@ -1660,18 +1660,14 @@ void GammaJetAnalysis::beginJob() { // ------------ method called once each job just after ending the event loop ------------ void GammaJetAnalysis::endJob() { - rootfile_->cd(); - if (doPFJets_) { pf_tree_->Write(); } // write miscItems // Save info about the triggers and other misc items { - rootfile_->cd(); - rootfile_->mkdir("miscItems"); - rootfile_->cd("miscItems"); - misc_tree_ = new TTree("misc_tree", "tree for misc.info"); + edm::Service fs; + misc_tree_ = fs->make("misc_tree", "tree for misc.info"); misc_tree_->Branch("ignoreHLT", &ignoreHLT_, "ignoreHLT/O"); misc_tree_->Branch("doPFJets", &doPFJets_, "doPFJets/O"); misc_tree_->Branch("doGenJets", &doGenJets_, "doGenJets/O"); @@ -1689,10 +1685,7 @@ void GammaJetAnalysis::endJob() { date.Write(str.Data()); misc_tree_->Fill(); misc_tree_->Write(); - rootfile_->cd(); } - - rootfile_->Close(); } // --------------------------------------------------------------------- diff --git a/Calibration/HcalCalibAlgos/test/GammaJetAnalysis.h b/Calibration/HcalCalibAlgos/test/GammaJetAnalysis.h index 09d5d43f0906f..b91ddf9b3d0e1 100644 --- a/Calibration/HcalCalibAlgos/test/GammaJetAnalysis.h +++ b/Calibration/HcalCalibAlgos/test/GammaJetAnalysis.h @@ -7,12 +7,14 @@ // user include files #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" #include "FWCore/ParameterSet/interface/ParameterSet.h" +#include "FWCore/ServiceRegistry/interface/Service.h" +#include "CommonTools/UtilAlgos/interface/TFileService.h" #include "DataFormats/EgammaCandidates/interface/PhotonFwd.h" #include "DataFormats/EgammaCandidates/interface/Photon.h" #include "DataFormats/JetReco/interface/CaloJetCollection.h" @@ -125,10 +127,10 @@ class PFJetCorretPair : protected std::pair { // Main class // -------------------------------------------- -class GammaJetAnalysis : public edm::EDAnalyzer { +class GammaJetAnalysis : public edm::one::EDAnalyzer { public: explicit GammaJetAnalysis(const edm::ParameterSet&); - ~GammaJetAnalysis(); + ~GammaJetAnalysis() override; float pfEcalIso(const reco::Photon* localPho1, edm::Handle pfHandle, @@ -159,10 +161,11 @@ class GammaJetAnalysis : public edm::EDAnalyzer { reco::PFCandidate::ParticleType pfToUse); private: - virtual void beginJob(); //(const edm::EventSetup&); - virtual void analyze(const edm::Event&, const edm::EventSetup&); - virtual void endJob(); - void beginRun(const edm::Run&, const edm::EventSetup&); + void beginJob() override; //(const edm::EventSetup&); + void analyze(const edm::Event&, const edm::EventSetup&) override; + void endJob() override; + void beginRun(const edm::Run&, const edm::EventSetup&) override; + void endRun(edm::Run const&, edm::EventSetup const&) override {} // parameters int debug_; // print debug statements @@ -225,8 +228,6 @@ class GammaJetAnalysis : public edm::EDAnalyzer { bool ignoreHLT_; // root file/histograms - TFile* rootfile_; - TTree* misc_tree_; // misc.information. Will be filled only once TTree* calo_tree_; TTree* pf_tree_; diff --git a/Calibration/HcalCalibAlgos/test/HcalConstantsASCIIWriter.h b/Calibration/HcalCalibAlgos/test/HcalConstantsASCIIWriter.h index 65e91836e9f90..890660cbbce53 100644 --- a/Calibration/HcalCalibAlgos/test/HcalConstantsASCIIWriter.h +++ b/Calibration/HcalCalibAlgos/test/HcalConstantsASCIIWriter.h @@ -8,7 +8,7 @@ // user include files #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/Framework/interface/EDProducer.h" @@ -32,23 +32,18 @@ #include "CondFormats/HcalObjects/interface/HcalRespCorrs.h" #include "CondFormats/DataRecord/interface/HcalRespCorrsRcd.h" -#include "TFile.h" -#include "TH1.h" -#include "TH2.h" -#include "TTree.h" -#include #include - #include #include #include #include +#include // // class decleration // namespace cms { - class HcalConstantsASCIIWriter : public edm::EDAnalyzer { + class HcalConstantsASCIIWriter : public edm::one::EDAnalyzer<> { public: explicit HcalConstantsASCIIWriter(const edm::ParameterSet &); ~HcalConstantsASCIIWriter(); diff --git a/Calibration/HcalCalibAlgos/test/HcalCorrPFCalculation.cc b/Calibration/HcalCalibAlgos/test/HcalCorrPFCalculation.cc index 62873ec5f6b9e..5bf0e07a470d8 100644 --- a/Calibration/HcalCalibAlgos/test/HcalCorrPFCalculation.cc +++ b/Calibration/HcalCalibAlgos/test/HcalCorrPFCalculation.cc @@ -1,13 +1,19 @@ +#include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/one/EDAnalyzer.h" +#include "FWCore/Framework/interface/EventSetup.h" +#include "FWCore/Framework/interface/MakerMacros.h" +#include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/Utilities/interface/InputTag.h" +#include "FWCore/ServiceRegistry/interface/Service.h" +#include "CommonTools/UtilAlgos/interface/TFileService.h" #include "Geometry/Records/interface/CaloGeometryRecord.h" #include "TrackingTools/TrackAssociator/interface/TrackDetectorAssociator.h" #include "DataFormats/HcalRecHit/interface/HcalRecHitCollections.h" #include "DataFormats/HcalRecHit/interface/HcalSourcePositionData.h" -#include -#include +#include "DataFormats/EcalDetId/interface/EBDetId.h" +#include "DataFormats/EcalDetId/interface/EEDetId.h" #include "DataFormats/HcalDetId/interface/HcalElectronicsId.h" #include "DataFormats/HcalDigi/interface/HcalDigiCollections.h" @@ -31,6 +37,7 @@ #include #include "TProfile.h" +#include "TTree.h" //#define EDM_ML_DEBUG diff --git a/Calibration/HcalCalibAlgos/test/ValidationHcalIsoTrackAlCaReco.cc b/Calibration/HcalCalibAlgos/test/ValidationHcalIsoTrackAlCaReco.cc index 73abf2037a0e5..ebab93b180026 100644 --- a/Calibration/HcalCalibAlgos/test/ValidationHcalIsoTrackAlCaReco.cc +++ b/Calibration/HcalCalibAlgos/test/ValidationHcalIsoTrackAlCaReco.cc @@ -22,8 +22,6 @@ // user include files #include "FWCore/Framework/interface/Frameworkfwd.h" -#include "FWCore/Framework/interface/EDAnalyzer.h" - #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/MakerMacros.h" diff --git a/Calibration/HcalCalibAlgos/test/python/dijetanalysis_cfg.py b/Calibration/HcalCalibAlgos/test/python/dijetanalysis_cfg.py index cb5c545a18c74..138cdb1a0344d 100644 --- a/Calibration/HcalCalibAlgos/test/python/dijetanalysis_cfg.py +++ b/Calibration/HcalCalibAlgos/test/python/dijetanalysis_cfg.py @@ -58,6 +58,10 @@ jetsInput = cms.InputTag("iterativeCone5CaloJets") ) +process.TFileService = cms.Service("TFileService", + fileName = cms.string('hi.root') +) + #process.DiJetsRecoPool = cms.OutputModule("PoolOutputModule", # outputCommands = cms.untracked.vstring('drop *', # 'keep *_DiJetsReco_*_*'), diff --git a/Calibration/HcalCalibAlgos/test/python/gammaJetAnalysis_cfg.py b/Calibration/HcalCalibAlgos/test/python/gammaJetAnalysis_cfg.py index abb00f559b1b2..e6656f3e2721a 100644 --- a/Calibration/HcalCalibAlgos/test/python/gammaJetAnalysis_cfg.py +++ b/Calibration/HcalCalibAlgos/test/python/gammaJetAnalysis_cfg.py @@ -22,6 +22,8 @@ process.GammaJetAnalysis.rootHistFilename = cms.string('PhoJet_tree_CHS.root') process.GammaJetAnalysis.doPFJets = cms.bool(True) process.GammaJetAnalysis.doGenJets = cms.bool(False) +process.TFileService = cms.Service("TFileService", + fileName = cms.string('PhoJet_tree_CHS.root')) # trigger names should not end with '_' process.GammaJetAnalysis.photonTriggers = cms.vstring( diff --git a/Calibration/HcalCalibAlgos/test/python/gammaJetAnalysis_data2012_cfg.py b/Calibration/HcalCalibAlgos/test/python/gammaJetAnalysis_data2012_cfg.py index 313525051b162..d4f1283a12cb8 100644 --- a/Calibration/HcalCalibAlgos/test/python/gammaJetAnalysis_data2012_cfg.py +++ b/Calibration/HcalCalibAlgos/test/python/gammaJetAnalysis_data2012_cfg.py @@ -23,6 +23,8 @@ process.GammaJetAnalysis.rootHistFilename = cms.string('PhoJet_tree_CHS_data2012.root') process.GammaJetAnalysis.doPFJets = cms.bool(True) process.GammaJetAnalysis.doGenJets = cms.bool(False) +process.TFileService = cms.Service("TFileService", + fileName = cms.string('PhoJet_tree_CHS_data2012.root')) # trigger names should not end with '_' process.GammaJetAnalysis.photonTriggers = cms.vstring( diff --git a/Calibration/HcalCalibAlgos/test/python/gammaJetAnalysis_data2012_noGJetProd_cfg.py b/Calibration/HcalCalibAlgos/test/python/gammaJetAnalysis_data2012_noGJetProd_cfg.py index c84036ad68d58..031381aba4c94 100644 --- a/Calibration/HcalCalibAlgos/test/python/gammaJetAnalysis_data2012_noGJetProd_cfg.py +++ b/Calibration/HcalCalibAlgos/test/python/gammaJetAnalysis_data2012_noGJetProd_cfg.py @@ -22,6 +22,8 @@ process.GammaJetAnalysis.rootHistFilename = cms.string('PhoJet_tree_CHS_data2012_noGJetProd.root') process.GammaJetAnalysis.doPFJets = cms.bool(True) process.GammaJetAnalysis.doGenJets = cms.bool(False) +process.TFileService = cms.Service("TFileService", + fileName = cms.string('PhoJet_tree_CHS_data2012_noGJetProd.root')) # trigger names should not end with '_' process.GammaJetAnalysis.photonTriggers = cms.vstring( diff --git a/Calibration/HcalCalibAlgos/test/python/gammaJetAnalysis_noGJetProd_cfg.py b/Calibration/HcalCalibAlgos/test/python/gammaJetAnalysis_noGJetProd_cfg.py index 47608413db77c..9d7cf10bbb316 100644 --- a/Calibration/HcalCalibAlgos/test/python/gammaJetAnalysis_noGJetProd_cfg.py +++ b/Calibration/HcalCalibAlgos/test/python/gammaJetAnalysis_noGJetProd_cfg.py @@ -23,6 +23,8 @@ process.GammaJetAnalysis.rootHistFilename = cms.string('PhoJet_tree_CHS_noGJetProd.root') process.GammaJetAnalysis.doPFJets = cms.bool(True) process.GammaJetAnalysis.doGenJets = cms.bool(True) +process.TFileService = cms.Service("TFileService", + fileName = cms.string('PhoJet_tree_CHS_noGJetProd.root')) # trigger names should not end with '_' process.GammaJetAnalysis.photonTriggers = cms.vstring( diff --git a/Calibration/HcalCalibAlgos/test/python/isoTrackAlCaAnalysis_cfg.py b/Calibration/HcalCalibAlgos/test/python/isoTrackAlCaAnalysis_cfg.py index abaa2c3fe6dee..a69eebf7f6fa6 100644 --- a/Calibration/HcalCalibAlgos/test/python/isoTrackAlCaAnalysis_cfg.py +++ b/Calibration/HcalCalibAlgos/test/python/isoTrackAlCaAnalysis_cfg.py @@ -12,10 +12,11 @@ from Configuration.AlCa.autoCond import autoCond process.GlobalTag.globaltag=autoCond['run2_data'] +process.MessageLogger.cerr.FwkReport.reportEvery = cms.untracked.int32(1000) if 'MessageLogger' in process.__dict__: + process.MessageLogger.HcalIsoTrackX=dict() process.MessageLogger.HcalIsoTrack=dict() -process.MessageLogger.cerr.FwkReport.reportEvery = 1 process.options = cms.untracked.PSet( wantSummary = cms.untracked.bool(True) ) process.load('RecoLocalCalo.CaloTowersCreator.calotowermaker_cfi') @@ -28,14 +29,13 @@ process.load('Calibration.HcalCalibAlgos.HcalIsoTrkAnalyzer_cff') process.HcalIsoTrkAnalyzer.triggers = [] -process.HcalIsoTrkAnalyzer.useRaw = 0 # 2 for Raw +process.HcalIsoTrkAnalyzer.useRaw = 0 # 1 for Raw process.HcalIsoTrkAnalyzer.ignoreTriggers = True +process.HcalIsoTrkAnalyzer.debugEvents = [640818633, 640797426, 641251898] process.source = cms.Source("PoolSource", - fileNames = cms.untracked.vstring( - 'file:oldPoolOutput.root' - ) - ) + fileNames = cms.untracked.vstring('file:oldPoolOutput.root') +) process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) ) diff --git a/Calibration/HcalCalibAlgos/test/python/isoTrackNewAlCaAnalysis_cfg.py b/Calibration/HcalCalibAlgos/test/python/isoTrackNewAlCaAnalysis_cfg.py new file mode 100644 index 0000000000000..938bb5c39bc56 --- /dev/null +++ b/Calibration/HcalCalibAlgos/test/python/isoTrackNewAlCaAnalysis_cfg.py @@ -0,0 +1,37 @@ +import FWCore.ParameterSet.Config as cms + +from Configuration.Eras.Era_Run2_2018_cff import Run2_2018 +process = cms.Process("ANALYSIS",Run2_2018) + +process.load("FWCore.MessageService.MessageLogger_cfi") +process.load('Configuration.StandardSequences.Services_cff') +process.load("Configuration.StandardSequences.GeometryRecoDB_cff") +process.load("Configuration.StandardSequences.MagneticField_cff") +process.load("RecoLocalCalo.EcalRecAlgos.EcalSeverityLevelESProducer_cfi") +process.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_cff') +from Configuration.AlCa.autoCond import autoCond +process.GlobalTag.globaltag=autoCond['run2_data'] + +process.MessageLogger.cerr.FwkReport.reportEvery = cms.untracked.int32(1000) +if 'MessageLogger' in process.__dict__: + process.MessageLogger.HcalIsoTrackX=dict() + process.MessageLogger.HcalIsoTrack=dict() + +process.options = cms.untracked.PSet( wantSummary = cms.untracked.bool(True) ) + +process.load('Calibration.HcalCalibAlgos.hcalIsoTrackAnalyzer_cfi') +process.hcalIsoTrackAnalyzer.useRaw = 0 # 1 for Raw +process.hcalIsoTrackAnalyzer.debugEvents = [640818633, 640797426, 641251898] + +process.source = cms.Source("PoolSource", + fileNames = cms.untracked.vstring('file:newPoolOutput.root') +) + +process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) ) + +process.TFileService = cms.Service("TFileService", + fileName = cms.string('output_newalca.root') +) + +process.p = cms.Path(process.hcalIsoTrackAnalyzer) + diff --git a/Calibration/HcalConnectivity/src/HcalCableMapper.cc b/Calibration/HcalConnectivity/src/HcalCableMapper.cc index 932672c159d21..bc3dcd7446d28 100644 --- a/Calibration/HcalConnectivity/src/HcalCableMapper.cc +++ b/Calibration/HcalConnectivity/src/HcalCableMapper.cc @@ -1,6 +1,6 @@ #include "DataFormats/Common/interface/Handle.h" #include "DataFormats/HcalDigi/interface/HcalDigiCollections.h" -#include "FWCore/Framework/interface/EDAnalyzer.h" +#include "FWCore/Framework/interface/one/EDAnalyzer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include @@ -12,9 +12,10 @@ using namespace std; author Kevin Klapoetke - Minnesota*/ -class HcalCableMapper : public edm::EDAnalyzer { +class HcalCableMapper : public edm::one::EDAnalyzer<> { public: explicit HcalCableMapper(edm::ParameterSet const &conf); + ~HcalCableMapper() override = default; void analyze(edm::Event const &e, edm::EventSetup const &c) override; void endJob() override; // std::string sourceDigi_; @@ -121,7 +122,6 @@ void HcalCableMapper::process(const PathSet &ps, const IdMap &im) { } } else if (ieta + 64 == 0x75) { ieta = ((ss[2].adc()) & 0x3F); - z_ieta = (((ss[2].adc()) >> 6) & 0x1); iphi = ((ss[3].adc()) & 0x7F); depth = ((ss[4].adc()) & 0x7); det = (((ss[4].adc()) >> 3) & 0xF); @@ -139,8 +139,7 @@ void HcalCableMapper::process(const PathSet &ps, const IdMap &im) { if ((spigot == eid.spigot()) && (fiber + 1 == eid.fiberIndex()) && (fiber_chan == eid.fiberChanId()) && (H_slot == eid.htrSlot()) && (G_Dcc == eid.dccid()) && (TB == eid.htrTopBottom()) && (crate == eid.readoutVMECrateId()) && (iphi == dd.iphi()) && (depth == dd.depth()) && (det == dd.subdet()) && - (ieta == dd.ietaAbs())) { //&&(z_ieta==dd.zside()) - + (ieta == dd.ietaAbs())) { std::cout << "Pathway match (SHIFT)" << std::endl; } else { is_header = " DATA SHIFT"; diff --git a/Calibration/Tools/BuildFile.xml b/Calibration/Tools/BuildFile.xml index 2da7792e7f3ab..89c013216def4 100644 --- a/Calibration/Tools/BuildFile.xml +++ b/Calibration/Tools/BuildFile.xml @@ -11,10 +11,7 @@ - - - diff --git a/Calibration/Tools/plugins/BuildFile.xml b/Calibration/Tools/plugins/BuildFile.xml index 7eced6aa1e733..bc090720a67e5 100644 --- a/Calibration/Tools/plugins/BuildFile.xml +++ b/Calibration/Tools/plugins/BuildFile.xml @@ -1,25 +1,10 @@ - - - - - - - - - - - - - - - diff --git a/Calibration/Tools/test/BuildFile.xml b/Calibration/Tools/test/BuildFile.xml index 81a7b93d2fc61..7a2fc1a0a0733 100644 --- a/Calibration/Tools/test/BuildFile.xml +++ b/Calibration/Tools/test/BuildFile.xml @@ -1,6 +1,7 @@ + diff --git a/CommonTools/MVAUtils/plugins/GBRForestWriter.cc b/CommonTools/MVAUtils/plugins/GBRForestWriter.cc index 285d181c139f8..46bb2a84cb69e 100644 --- a/CommonTools/MVAUtils/plugins/GBRForestWriter.cc +++ b/CommonTools/MVAUtils/plugins/GBRForestWriter.cc @@ -169,7 +169,7 @@ void GBRForestWriter::analyze(const edm::Event&, const edm::EventSetup&) { std::string outputRecord = (*job)->outputRecord_; if (gbrForests.size() > 1) outputRecord.append("_").append(gbrForest->first); - dbService->writeOne(gbrForest->second, dbService->beginOfTime(), outputRecord); + dbService->writeOneIOV(*gbrForest->second, dbService->beginOfTime(), outputRecord); } } diff --git a/CommonTools/MVAUtils/src/GBRForestTools.cc b/CommonTools/MVAUtils/src/GBRForestTools.cc index 71e39cd60f23e..f61390d41996c 100644 --- a/CommonTools/MVAUtils/src/GBRForestTools.cc +++ b/CommonTools/MVAUtils/src/GBRForestTools.cc @@ -80,9 +80,9 @@ namespace { } else { int thisidx = tree.CutIndices().size(); - int selector; - float cutval; - bool ctype; + int selector = 0; + float cutval = 0.; + bool ctype = false; node->QueryIntAttribute("IVar", &selector); node->QueryFloatAttribute("Cut", &cutval); @@ -158,8 +158,12 @@ namespace { e = e->NextSiblingElement("Info")) { const char* name; const char* value; - e->QueryStringAttribute("name", &name); - e->QueryStringAttribute("value", &value); + if (tinyxml2::XML_SUCCESS != e->QueryStringAttribute("name", &name)) { + throw cms::Exception("XMLERROR") << "no 'name' attribute found in 'Info' element in " << weightsFileFullPath; + } + if (tinyxml2::XML_SUCCESS != e->QueryStringAttribute("value", &value)) { + throw cms::Exception("XMLERROR") << "no 'value' attribute found in 'Info' element in " << weightsFileFullPath; + } info[name] = value; } @@ -172,7 +176,9 @@ namespace { for (tinyxml2::XMLElement* e = optionsElem->FirstChildElement("Option"); e != nullptr; e = e->NextSiblingElement("Option")) { const char* name; - e->QueryStringAttribute("name", &name); + if (tinyxml2::XML_SUCCESS != e->QueryStringAttribute("name", &name)) { + throw cms::Exception("XMLERROR") << "no 'name' attribute found in 'Option' element in " << weightsFileFullPath; + } options[name] = e->GetText(); } @@ -194,7 +200,10 @@ namespace { e = e->NextSiblingElement("BinaryTree")) { hasTrees = true; double w; - e->QueryDoubleAttribute("boostWeight", &w); + if (tinyxml2::XML_SUCCESS != e->QueryDoubleAttribute("boostWeight", &w)) { + throw cms::Exception("XMLERROR") << "problem with 'boostWeight' attribute found in 'BinaryTree' element in " + << weightsFileFullPath; + } boostWeights.push_back(w); } if (!hasTrees) { diff --git a/CommonTools/PileupAlgos/src/PuppiContainer.cc b/CommonTools/PileupAlgos/src/PuppiContainer.cc index 72d91d5425aa7..ceb08185e561a 100644 --- a/CommonTools/PileupAlgos/src/PuppiContainer.cc +++ b/CommonTools/PileupAlgos/src/PuppiContainer.cc @@ -101,18 +101,26 @@ double PuppiContainer::var_within_R(int iId, if (dr2 < 0.0001) continue; auto const pt = cand.pt; - if (iId == 5) - var += (pt * pt / dr2); - else if (iId == 4) - var += pt; - else if (iId == 3) - var += (1. / dr2); - else if (iId == 2) - var += (1. / dr2); - else if (iId == 1) - var += pt; - else if (iId == 0) - var += (pt / dr2); + switch (iId) { + case 5: + var += (pt * pt / dr2); + break; + case 4: + var += pt; + break; + case 3: + var += (1. / dr2); + break; + case 2: + var += (1. / dr2); + break; + case 1: + var += pt; + break; + case 0: + var += (pt / dr2); + break; + } } } } diff --git a/CommonTools/RecoAlgos/plugins/CaloRecHitCandidateProducer.cc b/CommonTools/RecoAlgos/plugins/CaloRecHitCandidateProducer.cc index 23f49490bb3ff..2ffd9274ac5bc 100644 --- a/CommonTools/RecoAlgos/plugins/CaloRecHitCandidateProducer.cc +++ b/CommonTools/RecoAlgos/plugins/CaloRecHitCandidateProducer.cc @@ -1,4 +1,4 @@ -#include "FWCore/Framework/interface/EDProducer.h" +#include "FWCore/Framework/interface/global/EDProducer.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "DataFormats/RecoCandidate/interface/CaloRecHitCandidate.h" @@ -6,7 +6,7 @@ namespace reco { namespace modules { template - class CaloRecHitCandidateProducer : public edm::EDProducer { + class CaloRecHitCandidateProducer : public edm::global::EDProducer<> { public: /// constructor CaloRecHitCandidateProducer(const edm::ParameterSet &cfg) @@ -16,9 +16,9 @@ namespace reco { private: /// process one event - void produce(edm::Event &, const edm::EventSetup &) override; + void produce(edm::StreamID, edm::Event &, const edm::EventSetup &) const override; /// source collection tag - edm::EDGetTokenT srcToken_; + const edm::EDGetTokenT srcToken_; }; } // namespace modules } // namespace reco @@ -31,7 +31,9 @@ namespace reco { namespace modules { template - void CaloRecHitCandidateProducer::produce(edm::Event &evt, const edm::EventSetup &) { + void CaloRecHitCandidateProducer::produce(edm::StreamID, + edm::Event &evt, + const edm::EventSetup &) const { using namespace edm; using namespace reco; using namespace std; diff --git a/CommonTools/RecoAlgos/plugins/PrimaryVertexSorter.h b/CommonTools/RecoAlgos/plugins/PrimaryVertexSorter.h index e4e8e5b98cc4e..58fa0c9f8c6eb 100644 --- a/CommonTools/RecoAlgos/plugins/PrimaryVertexSorter.h +++ b/CommonTools/RecoAlgos/plugins/PrimaryVertexSorter.h @@ -22,6 +22,9 @@ #include "CommonTools/RecoAlgos/interface/PrimaryVertexSorting.h" #include "DataFormats/PatCandidates/interface/PackedCandidate.h" +#include "TrackingTools/TransientTrack/interface/TransientTrackBuilder.h" +#include "TrackingTools/Records/interface/TransientTrackRecord.h" + /**\class PrimaryVertexSorter * \author Andrea Rizzi @@ -56,6 +59,8 @@ class PrimaryVertexSorter : public edm::stream::EDProducer<> { edm::EDGetTokenT> tokenTrackTimeTag_; edm::EDGetTokenT> tokenTrackTimeResoTag_; + edm::ESGetToken tokenBuilder_; + bool produceOriginalMapping_; bool produceSortedVertices_; bool producePFPileUp_; @@ -75,8 +80,6 @@ class PrimaryVertexSorter : public edm::stream::EDProducer<> { }; #include "DataFormats/VertexReco/interface/Vertex.h" -#include "TrackingTools/TransientTrack/interface/TransientTrackBuilder.h" -#include "TrackingTools/Records/interface/TransientTrackRecord.h" #include "FWCore/Framework/interface/ESHandle.h" // #include "FWCore/MessageLogger/interface/MessageLogger.h" @@ -90,6 +93,7 @@ PrimaryVertexSorter::PrimaryVertexSorter(const edm::Paramet tokenCandidates_(consumes(iConfig.getParameter("particles"))), tokenVertices_(consumes(iConfig.getParameter("vertices"))), tokenJets_(consumes>(iConfig.getParameter("jets"))), + tokenBuilder_(esConsumes(edm::ESInputTag("", "TransientTrackBuilder"))), produceOriginalMapping_(iConfig.getParameter("produceAssociationToOriginalVertices")), produceSortedVertices_(iConfig.getParameter("produceSortedVertices")), producePFPileUp_(iConfig.getParameter("producePileUpCollection")), @@ -140,8 +144,7 @@ void PrimaryVertexSorter::produce(edm::Event& iEvent, const Handle> jets; iEvent.getByToken(tokenJets_, jets); - edm::ESHandle builder; - iSetup.get().get("TransientTrackBuilder", builder); + TransientTrackBuilder const& builder = iSetup.getData(tokenBuilder_); Handle vertices; iEvent.getByToken(tokenVertices_, vertices); @@ -174,7 +177,7 @@ void PrimaryVertexSorter::produce(edm::Event& iEvent, const for (auto const& pf : particles) { std::pair vtxWithQuality = - runAlgo(*vertices, pf, trackTimeTag, trackTimeResoTag, *jets, *builder); + runAlgo(*vertices, pf, trackTimeTag, trackTimeResoTag, *jets, builder); pfToPVVector.push_back(vtxWithQuality.first); pfToPVQualityVector.push_back(vtxWithQuality.second); } diff --git a/CommonTools/RecoAlgos/plugins/ShallowCloneProducer.cc b/CommonTools/RecoAlgos/plugins/ShallowCloneProducer.cc index 900e143d56843..7f33fd71be5ac 100644 --- a/CommonTools/RecoAlgos/plugins/ShallowCloneProducer.cc +++ b/CommonTools/RecoAlgos/plugins/ShallowCloneProducer.cc @@ -13,13 +13,13 @@ */ #include "DataFormats/Candidate/interface/ShallowCloneCandidate.h" -#include "FWCore/Framework/interface/EDProducer.h" +#include "FWCore/Framework/interface/global/EDProducer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/Utilities/interface/InputTag.h" template -class ShallowCloneProducer : public edm::EDProducer { +class ShallowCloneProducer : public edm::global::EDProducer<> { public: /// constructor from parameter set explicit ShallowCloneProducer(const edm::ParameterSet&); @@ -28,9 +28,9 @@ class ShallowCloneProducer : public edm::EDProducer { private: /// process an event - void produce(edm::Event&, const edm::EventSetup&) override; + void produce(edm::StreamID, edm::Event&, const edm::EventSetup&) const override; /// labels of the collection to be converted - edm::EDGetTokenT srcToken_; + const edm::EDGetTokenT srcToken_; }; template @@ -43,7 +43,7 @@ template ShallowCloneProducer::~ShallowCloneProducer() {} template -void ShallowCloneProducer::produce(edm::Event& evt, const edm::EventSetup&) { +void ShallowCloneProducer::produce(edm::StreamID, edm::Event& evt, const edm::EventSetup&) const { std::unique_ptr coll(new reco::CandidateCollection); edm::Handle masterCollection; evt.getByToken(srcToken_, masterCollection); diff --git a/CommonTools/Statistics/interface/hsm_1d.icc b/CommonTools/Statistics/interface/hsm_1d.h similarity index 96% rename from CommonTools/Statistics/interface/hsm_1d.icc rename to CommonTools/Statistics/interface/hsm_1d.h index a9b426fe5d614..f094904ad07cf 100644 --- a/CommonTools/Statistics/interface/hsm_1d.icc +++ b/CommonTools/Statistics/interface/hsm_1d.h @@ -1,5 +1,5 @@ -#ifndef _HSM_1D_ICC_ -#define _HSM_1D_ICC_ +#ifndef CommonTools_Statistics_hsm_1d_h +#define CommonTools_Statistics_hsm_1d_h #include "CommonTools/Statistics/interface/StatisticsException.h" diff --git a/CommonTools/Statistics/interface/lms_1d.icc b/CommonTools/Statistics/interface/lms_1d.h similarity index 93% rename from CommonTools/Statistics/interface/lms_1d.icc rename to CommonTools/Statistics/interface/lms_1d.h index cc62e6680d838..51081c46a7740 100644 --- a/CommonTools/Statistics/interface/lms_1d.icc +++ b/CommonTools/Statistics/interface/lms_1d.h @@ -1,5 +1,5 @@ -#ifndef _LMS_1D_ICC_ -#define _LMS_1D_ICC_ +#ifndef CommonTools_Statistics_lms_1d_h +#define CommonTools_Statistics_lms_1d_h #include "CommonTools/Statistics/interface/StatisticsException.h" diff --git a/CommonTools/Statistics/interface/median.icc b/CommonTools/Statistics/interface/median.h similarity index 90% rename from CommonTools/Statistics/interface/median.icc rename to CommonTools/Statistics/interface/median.h index 7253a463e3fe2..6869be4b994e2 100644 --- a/CommonTools/Statistics/interface/median.icc +++ b/CommonTools/Statistics/interface/median.h @@ -1,5 +1,5 @@ -#ifndef MEDIAN_ICC -#define MEDIAN_ICC +#ifndef CommonTools_Statistics_median_h +#define CommonTools_Statistics_median_h #include #include diff --git a/CommonTools/Statistics/src/hsm_1d.cc b/CommonTools/Statistics/src/hsm_1d.cc deleted file mode 100644 index c668d1f463134..0000000000000 --- a/CommonTools/Statistics/src/hsm_1d.cc +++ /dev/null @@ -1 +0,0 @@ -#include "CommonTools/Statistics/interface/hsm_1d.icc" diff --git a/CommonTools/Statistics/src/lms_1d.cc b/CommonTools/Statistics/src/lms_1d.cc deleted file mode 100644 index 28d437ede63f6..0000000000000 --- a/CommonTools/Statistics/src/lms_1d.cc +++ /dev/null @@ -1 +0,0 @@ -#include "CommonTools/Statistics/interface/lms_1d.icc" diff --git a/CommonTools/Statistics/src/median.cc b/CommonTools/Statistics/src/median.cc deleted file mode 100644 index 2d0231fbd1fb3..0000000000000 --- a/CommonTools/Statistics/src/median.cc +++ /dev/null @@ -1 +0,0 @@ -#include "CommonTools/Statistics/interface/median.icc" diff --git a/CondCore/AlignmentPlugins/plugins/TrackerAlignment_PayloadInspector.cc b/CondCore/AlignmentPlugins/plugins/TrackerAlignment_PayloadInspector.cc index 1633380424575..56d2b9e245151 100644 --- a/CondCore/AlignmentPlugins/plugins/TrackerAlignment_PayloadInspector.cc +++ b/CondCore/AlignmentPlugins/plugins/TrackerAlignment_PayloadInspector.cc @@ -305,11 +305,11 @@ namespace { //******************************************// template - class TrackerAlignmentSummary : public PlotImage { + class TrackerAlignmentSummary : public PlotImage { public: TrackerAlignmentSummary() - : PlotImage("Comparison of all coordinates between two geometries for " + - getStringFromPart(q)) {} + : PlotImage("Comparison of all coordinates between two geometries for " + + getStringFromPart(q)) {} bool fill() override { auto tag = PlotBase::getTag<0>(); diff --git a/CondCore/CTPPSPlugins/src/plugin.cc b/CondCore/CTPPSPlugins/src/plugin.cc index 1c8892df4218e..f2eb460050b5e 100644 --- a/CondCore/CTPPSPlugins/src/plugin.cc +++ b/CondCore/CTPPSPlugins/src/plugin.cc @@ -26,6 +26,12 @@ #include "CondFormats/PPSObjects/interface/PPSAssociationCuts.h" #include "CondFormats/DataRecord/interface/PPSAssociationCutsRcd.h" +namespace { + struct InitAssociationCuts { + void operator()(PPSAssociationCuts &cuts) { cuts.initialize(); } + }; +} // namespace + REGISTER_PLUGIN(CTPPSBeamParametersRcd, CTPPSBeamParameters); REGISTER_PLUGIN(CTPPSPixelDAQMappingRcd, CTPPSPixelDAQMapping); REGISTER_PLUGIN(CTPPSPixelAnalysisMaskRcd, CTPPSPixelAnalysisMask); @@ -39,4 +45,5 @@ REGISTER_PLUGIN(PPSDirectSimulationDataRcd, PPSDirectSimulationData); REGISTER_PLUGIN(PPSPixelTopologyRcd, PPSPixelTopology); REGISTER_PLUGIN(PPSAlignmentConfigRcd, PPSAlignmentConfig); REGISTER_PLUGIN(PPSAlignmentConfigurationRcd, PPSAlignmentConfiguration); -REGISTER_PLUGIN(PPSAssociationCutsRcd, PPSAssociationCuts); + +REGISTER_PLUGIN_INIT(PPSAssociationCutsRcd, PPSAssociationCuts, InitAssociationCuts); diff --git a/CondCore/HLTPlugins/plugins/AlCaRecoTriggerBits_PayloadInspector.cc b/CondCore/HLTPlugins/plugins/AlCaRecoTriggerBits_PayloadInspector.cc index 2a19317a2f8c1..6a283545caa45 100644 --- a/CondCore/HLTPlugins/plugins/AlCaRecoTriggerBits_PayloadInspector.cc +++ b/CondCore/HLTPlugins/plugins/AlCaRecoTriggerBits_PayloadInspector.cc @@ -18,14 +18,13 @@ namespace { /************************************************ Display AlCaRecoTriggerBits mapping *************************************************/ - class AlCaRecoTriggerBits_Display : public PlotImage { + class AlCaRecoTriggerBits_Display : public PlotImage { public: - AlCaRecoTriggerBits_Display() : PlotImage("Table of AlCaRecoTriggerBits") { - setSingleIov(true); - } + AlCaRecoTriggerBits_Display() : PlotImage("Table of AlCaRecoTriggerBits") {} - bool fill(const std::vector > &iovs) override { - auto iov = iovs.front(); + bool fill() override { + auto tag = PlotBase::getTag<0>(); + auto iov = tag.iovs.front(); std::shared_ptr payload = fetchPayload(std::get<1>(iov)); std::string IOVsince = std::to_string(std::get<0>(iov)); @@ -51,7 +50,7 @@ namespace { y_x1.push_back(y); s_x1.push_back("#scale[1.2]{Key}"); y_x2.push_back(y); - s_x2.push_back("#scale[1.2]{in IOV: " + IOVsince + "}"); + s_x2.push_back("#scale[1.2]{tag: " + tag.name + " in IOV: " + IOVsince + "}"); y -= pitch / 2.; y_line.push_back(y); diff --git a/CondCore/PhysicsToolsPlugins/interface/DropBoxMetaDataPayloadInspectorHelper.h b/CondCore/PhysicsToolsPlugins/interface/DropBoxMetaDataPayloadInspectorHelper.h new file mode 100644 index 0000000000000..f5cdfa9d824e6 --- /dev/null +++ b/CondCore/PhysicsToolsPlugins/interface/DropBoxMetaDataPayloadInspectorHelper.h @@ -0,0 +1,184 @@ +#ifndef DropBoxMetaDataPayloadInspectorHelper_H +#define DropBoxMetaDataPayloadInspectorHelper_H + +#include "TH1.h" +#include "TH2.h" +#include "TStyle.h" +#include "TCanvas.h" + +#include +#include +#include +#include +#include "CondFormats/Common/interface/DropBoxMetadata.h" +#include "FWCore/MessageLogger/interface/MessageLogger.h" + +namespace DBoxMetadataHelper { + class RecordMetaDataInfo { + public: + /// Constructor + RecordMetaDataInfo(DropBoxMetadata::Parameters params) { + const auto& theParameters = params.getParameterMap(); + for (const auto& [key, val] : theParameters) { + if (key.find("prep") != std::string::npos) { + m_prepmetadata = val; + } else if (key.find("prod") != std::string::npos) { + m_prodmetadata = val; + } else if (key.find("mult") != std::string::npos) { + m_multimetadata = val; + } + } + } + /// Destructor + ~RecordMetaDataInfo() = default; + + public: + const std::string getPrepMetaData() const { return m_prepmetadata; } + const std::string getProdMetaData() const { return m_prodmetadata; } + const std::string getMultiMetaData() const { return m_multimetadata; } + const bool hasMultiMetaData() const { return !m_multimetadata.empty(); } + + private: + std::string m_prepmetadata; + std::string m_prodmetadata; + std::string m_multimetadata; + }; + + using recordMap = std::map; + + inline const std::vector getAllRecords(const DBoxMetadataHelper::recordMap& recordSet) { + std::vector records; + std::transform(recordSet.begin(), + recordSet.end(), + std::inserter(records, records.end()), + [](std::pair recordSetEntry) -> std::string { + return recordSetEntry.first; + }); + return records; + } + + inline std::vector set_difference(std::vector const& v1, + std::vector const& v2) { + std::vector diff; + std::set_difference(std::begin(v1), std::end(v1), std::begin(v2), std::end(v2), std::back_inserter(diff)); + return diff; + } + + inline std::vector set_intersection(std::vector const& v1, + std::vector const& v2) { + std::vector common; + std::set_intersection(std::begin(v1), std::end(v1), std::begin(v2), std::end(v2), std::back_inserter(common)); + return common; + } + + class DBMetaDataTableDisplay { + public: + DBMetaDataTableDisplay(DBoxMetadataHelper::recordMap theMap) : m_Map(theMap) {} + ~DBMetaDataTableDisplay() = default; + + void printMetaDatas() { + for (const auto& [key, val] : m_Map) { + edm::LogPrint("DropBoxMetadataPIHelper") << "key: " << key << "\n\n" << std::endl; + edm::LogPrint("DropBoxMetadataPIHelper") << "prep: " << cleanJson(val.getPrepMetaData()) << "\n" << std::endl; + edm::LogPrint("DropBoxMetadataPIHelper") << "prod: " << cleanJson(val.getProdMetaData()) << "\n" << std::endl; + // check, since it's optional + if (val.hasMultiMetaData()) { + edm::LogPrint("DropBoxMetadataPIHelper") << "multi: " << cleanJson(val.getMultiMetaData()) << "\n" + << std::endl; + } + } + } + + void printOneKey(const DBoxMetadataHelper::RecordMetaDataInfo& oneKey) { + edm::LogPrint("DropBoxMetadataPIHelper") << "prep: " << cleanJson(oneKey.getPrepMetaData()) << std::endl; + edm::LogPrint("DropBoxMetadataPIHelper") << "prod: " << cleanJson(oneKey.getProdMetaData()) << std::endl; + // check, since it's optional + if (oneKey.hasMultiMetaData()) { + edm::LogPrint("DropBoxMetadataPIHelper") << "multi: " << cleanJson(oneKey.getMultiMetaData()) << std::endl; + } + edm::LogPrint("DropBoxMetadataPIHelper") << "\n" << std::endl; + } + + void printDiffWithMetadata(const DBoxMetadataHelper::recordMap& theRefMap) { + edm::LogPrint("DropBoxMetadataPIHelper") + << "Target has: " << m_Map.size() << " records, reference has: " << theRefMap.size() << " records" + << std::endl; + + const auto& ref_records = DBoxMetadataHelper::getAllRecords(theRefMap); + const auto& tar_records = DBoxMetadataHelper::getAllRecords(m_Map); + + const auto& diff = DBoxMetadataHelper::set_difference(ref_records, tar_records); + const auto& common = DBoxMetadataHelper::set_intersection(ref_records, tar_records); + + // do first the common parts + for (const auto& key : common) { + edm::LogPrint("DropBoxMetadataPIHelper") << "key: " << key << "\n" << std::endl; + const auto& val = m_Map.at(key); + const auto& refval = theRefMap.at(key); + + if ((val.getPrepMetaData()).compare(refval.getPrepMetaData()) != 0) { + edm::LogPrint("DropBoxMetadataPIHelper") << "found difference in prep metadata!" << std::endl; + edm::LogPrint("DropBoxMetadataPIHelper") << " in target: " << cleanJson(val.getPrepMetaData()) << std::endl; + edm::LogPrint("DropBoxMetadataPIHelper") + << " in reference: " << cleanJson(refval.getPrepMetaData()) << std::endl; + } + if ((val.getProdMetaData()).compare(refval.getProdMetaData()) != 0) { + edm::LogPrint("DropBoxMetadataPIHelper") << "found difference in prod metadata!" << std::endl; + edm::LogPrint("DropBoxMetadataPIHelper") << " in target: " << cleanJson(val.getProdMetaData()) << std::endl; + edm::LogPrint("DropBoxMetadataPIHelper") + << " in reference: " << cleanJson(refval.getProdMetaData()) << std::endl; + } + if ((val.getMultiMetaData()).compare(refval.getMultiMetaData()) != 0) { + edm::LogPrint("DropBoxMetadataPIHelper") << "found difference in multi metadata!" << std::endl; + edm::LogPrint("DropBoxMetadataPIHelper") << " in target: " << cleanJson(val.getMultiMetaData()) << std::endl; + edm::LogPrint("DropBoxMetadataPIHelper") + << " in reference: " << cleanJson(refval.getMultiMetaData()) << std::endl; + } + edm::LogPrint("DropBoxMetadataPIHelper") << "\n" << std::endl; + } + + // if interesction is not the union check for extra differences + if (!diff.empty()) { + // check if the reference has more records than target + if (ref_records.size() > tar_records.size()) { + for (const auto& ref : ref_records) { + if (std::find(tar_records.begin(), tar_records.end(), ref) == tar_records.end()) { + const auto& refval = theRefMap.at(ref); + edm::LogPrint("DropBoxMetadataPIHelper") << "key: " << ref << " not present in target! \n" << std::endl; + printOneKey(refval); + } + } + } + // then check if the target has more records than the reference + else if (tar_records.size() > ref_records.size()) { + for (const auto& tar : tar_records) { + if (std::find(ref_records.begin(), ref_records.end(), tar) == ref_records.end()) { + const auto& tarval = m_Map.at(tar); + edm::LogPrint("DropBoxMetadataPIHelper") << "key: " << tar << " not present in reference! \n" + << std::endl; + printOneKey(tarval); + } + } + } + } + } + + private: + DBoxMetadataHelper::recordMap m_Map; + + std::string replaceAll(std::string str, const std::string& from, const std::string& to) { + size_t start_pos = 0; + while ((start_pos = str.find(from, start_pos)) != std::string::npos) { + str.replace(start_pos, from.length(), to); + start_pos += to.length(); // Handles case where 'to' is a substring of 'from' + } + return str; + } + + std::string cleanJson(std::string str) { + std::string out = replaceAll(str, std::string("""), std::string("'")); + return out; + } + }; +} // namespace DBoxMetadataHelper +#endif diff --git a/CondCore/PhysicsToolsPlugins/plugins/BuildFile.xml b/CondCore/PhysicsToolsPlugins/plugins/BuildFile.xml new file mode 100644 index 0000000000000..b7de51348d77c --- /dev/null +++ b/CondCore/PhysicsToolsPlugins/plugins/BuildFile.xml @@ -0,0 +1,4 @@ + + + + diff --git a/CondCore/PhysicsToolsPlugins/plugins/DropBoxMetadata_PayloadInspector.cc b/CondCore/PhysicsToolsPlugins/plugins/DropBoxMetadata_PayloadInspector.cc new file mode 100644 index 0000000000000..076c9fbc5feea --- /dev/null +++ b/CondCore/PhysicsToolsPlugins/plugins/DropBoxMetadata_PayloadInspector.cc @@ -0,0 +1,197 @@ +/*! + \file DropBoxMetadata_PayloadInspector + \Payload Inspector Plugin for DropBoxMetadata + \author M. Musich + \version $Revision: 1.0 $ + \date $Date: 2018/03/18 10:01:00 $ +*/ + +#include "CondCore/Utilities/interface/PayloadInspectorModule.h" +#include "CondCore/Utilities/interface/PayloadInspector.h" +#include "CondCore/CondDB/interface/Time.h" + +// the data format of the condition to be inspected +#include "CondFormats/Common/interface/DropBoxMetadata.h" +#include "FWCore/MessageLogger/interface/MessageLogger.h" + +// helper classes +#include "CondCore/PhysicsToolsPlugins/interface/DropBoxMetaDataPayloadInspectorHelper.h" + +// system includes +#include +#include +#include +#include + +// include ROOT +#include "TProfile.h" +#include "TH2F.h" +#include "TLegend.h" +#include "TCanvas.h" +#include "TLine.h" +#include "TStyle.h" +#include "TLatex.h" +#include "TPave.h" +#include "TPaveStats.h" +#include "TPaletteAxis.h" + +namespace { + + using namespace cond::payloadInspector; + + /************************************************ + DropBoxMetadata Payload Inspector of 1 IOV + *************************************************/ + class DropBoxMetadataTest : public Histogram1D { + public: + DropBoxMetadataTest() + : Histogram1D("Test DropBoxMetadata", "Test DropBoxMetadata", 1, 0.0, 1.0) {} + + bool fill() override { + auto tag = PlotBase::getTag<0>(); + for (auto const& iov : tag.iovs) { + std::shared_ptr payload = Base::fetchPayload(std::get<1>(iov)); + if (payload.get()) { + std::vector records = payload->getAllRecords(); + for (const auto& record : records) { + edm::LogPrint("DropBoxMetadata_PayloadInspector") << "record: " << record << std::endl; + const auto& parameters = payload->getRecordParameters(record); + const auto& recordParams = parameters.getParameterMap(); + for (const auto& [key, val] : recordParams) { + if (val.find(""") != std::string::npos) { + const auto& replaced = replaceAll(val, std::string("""), std::string("'")); + edm::LogPrint("DropBoxMetadata_PayloadInspector") << key << " : " << replaced << std::endl; + } else { + edm::LogPrint("DropBoxMetadata_PayloadInspector") << key << " : " << val << std::endl; + } + } + } + } + } + return true; + } + + private: + std::string replaceAll(std::string str, const std::string& from, const std::string& to) { + size_t start_pos = 0; + while ((start_pos = str.find(from, start_pos)) != std::string::npos) { + str.replace(start_pos, from.length(), to); + start_pos += to.length(); // Handles case where 'to' is a substring of 'from' + } + return str; + } + }; + + /************************************************ + DropBoxMetadata Payload Inspector of 1 IOV + *************************************************/ + class DropBoxMetadata_Display : public PlotImage { + public: + DropBoxMetadata_Display() : PlotImage("DropBoxMetadata Display of contents") {} + + bool fill() override { + auto tag = PlotBase::getTag<0>(); + auto iov = tag.iovs.front(); + std::shared_ptr payload = fetchPayload(std::get<1>(iov)); + + std::vector records = payload->getAllRecords(); + TCanvas canvas("Canv", "Canv", 1200, 100 * records.size()); + + DBoxMetadataHelper::recordMap theRecordMap; + for (const auto& record : records) { + edm::LogPrint("DropBoxMetadata_PayloadInspector") << "record: " << record << std::endl; + const auto& parameters = payload->getRecordParameters(record); + theRecordMap.insert(std::make_pair(record, DBoxMetadataHelper::RecordMetaDataInfo(parameters))); + } + + DBoxMetadataHelper::DBMetaDataTableDisplay theDisplay(theRecordMap); + theDisplay.printMetaDatas(); + + std::string fileName(m_imageFileName); + canvas.SaveAs(fileName.c_str()); + return true; + } + + private: + }; + + /************************************************ + DropBoxMetadata Payload Comparator of 2 IOVs + *************************************************/ + template + class DropBoxMetadata_CompareBase : public PlotImage { + public: + DropBoxMetadata_CompareBase() + : PlotImage("DropBoxMetadata comparison of contents") {} + + bool fill() override { + // trick to deal with the multi-ioved tag and two tag case at the same time + auto theIOVs = PlotBase::getTag<0>().iovs; + auto f_tagname = PlotBase::getTag<0>().name; + std::string l_tagname = ""; + auto firstiov = theIOVs.front(); + std::tuple lastiov; + + // we don't support (yet) comparison with more than 2 tags + assert(this->m_plotAnnotations.ntags < 3); + + if (this->m_plotAnnotations.ntags == 2) { + auto tag2iovs = PlotBase::getTag<1>().iovs; + l_tagname = PlotBase::getTag<1>().name; + lastiov = tag2iovs.front(); + } else { + lastiov = theIOVs.back(); + } + + std::shared_ptr last_payload = this->fetchPayload(std::get<1>(lastiov)); + std::shared_ptr first_payload = this->fetchPayload(std::get<1>(firstiov)); + + std::string lastIOVsince = std::to_string(std::get<0>(lastiov)); + std::string firstIOVsince = std::to_string(std::get<0>(firstiov)); + + // first payload + std::vector f_records = first_payload->getAllRecords(); + DBoxMetadataHelper::recordMap f_theRecordMap; + for (const auto& record : f_records) { + //edm::LogPrint("DropBoxMetadata_PayloadInspector") << "record: " << record << std::endl; + const auto& parameters = first_payload->getRecordParameters(record); + f_theRecordMap.insert(std::make_pair(record, DBoxMetadataHelper::RecordMetaDataInfo(parameters))); + } + + DBoxMetadataHelper::DBMetaDataTableDisplay f_theDisplay(f_theRecordMap); + //f_theDisplay.printMetaDatas(); + + // last payload + std::vector l_records = last_payload->getAllRecords(); + DBoxMetadataHelper::recordMap l_theRecordMap; + for (const auto& record : l_records) { + //edm::LogPrint("DropBoxMetadata_PayloadInspector") << "record: " << record << std::endl; + const auto& parameters = last_payload->getRecordParameters(record); + l_theRecordMap.insert(std::make_pair(record, DBoxMetadataHelper::RecordMetaDataInfo(parameters))); + } + + DBoxMetadataHelper::DBMetaDataTableDisplay l_theDisplay(l_theRecordMap); + //l_theDisplay.printMetaDatas(); + + l_theDisplay.printDiffWithMetadata(f_theRecordMap); + + TCanvas canvas("Canv", "Canv", 1200, 100 * std::max(f_records.size(), l_records.size())); + std::string fileName(this->m_imageFileName); + canvas.SaveAs(fileName.c_str()); + return true; + } + + private: + }; + + using DropBoxMetadata_Compare = DropBoxMetadata_CompareBase; + using DropBoxMetadata_CompareTwoTags = DropBoxMetadata_CompareBase; + +} // namespace + +PAYLOAD_INSPECTOR_MODULE(DropBoxMetadata) { + PAYLOAD_INSPECTOR_CLASS(DropBoxMetadataTest); + PAYLOAD_INSPECTOR_CLASS(DropBoxMetadata_Display); + PAYLOAD_INSPECTOR_CLASS(DropBoxMetadata_Compare); + PAYLOAD_INSPECTOR_CLASS(DropBoxMetadata_CompareTwoTags); +} diff --git a/CondCore/PhysicsToolsPlugins/test/BuildFile.xml b/CondCore/PhysicsToolsPlugins/test/BuildFile.xml new file mode 100644 index 0000000000000..da7f22199b381 --- /dev/null +++ b/CondCore/PhysicsToolsPlugins/test/BuildFile.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/CondCore/PhysicsToolsPlugins/test/test_DropBoxMetadata_PayloadInspector.cpp b/CondCore/PhysicsToolsPlugins/test/test_DropBoxMetadata_PayloadInspector.cpp new file mode 100644 index 0000000000000..29285845e6d48 --- /dev/null +++ b/CondCore/PhysicsToolsPlugins/test/test_DropBoxMetadata_PayloadInspector.cpp @@ -0,0 +1,42 @@ +#include +#include +#include "CondCore/Utilities/interface/PayloadInspector.h" +#include "CondCore/PhysicsToolsPlugins/plugins/DropBoxMetadata_PayloadInspector.cc" + +#include "FWCore/PluginManager/interface/PluginManager.h" +#include "FWCore/PluginManager/interface/standard.h" +#include "FWCore/ServiceRegistry/interface/ServiceRegistry.h" +#include "FWCore/MessageLogger/interface/MessageLogger.h" + +int main(int argc, char** argv) { + Py_Initialize(); + edmplugin::PluginManager::Config config; + edmplugin::PluginManager::configure(edmplugin::standard::config()); + + std::vector psets; + edm::ParameterSet pSet; + pSet.addParameter("@service_type", std::string("SiteLocalConfigService")); + psets.push_back(pSet); + edm::ServiceToken servToken(edm::ServiceRegistry::createSet(psets)); + edm::ServiceRegistry::Operate operate(servToken); + + std::string connectionString("frontier://FrontierProd/CMS_CONDITIONS"); + + std::string tag = "DropBoxMetadata_v5.1_express"; + cond::Time_t start = static_cast(1); + cond::Time_t end = static_cast(346361); + + edm::LogPrint("test_DropBoxMetadata_PayloadInspector") << "## test Display" << std::endl; + + DropBoxMetadata_Display histo1; + histo1.process(connectionString, PI::mk_input(tag, start, start)); + edm::LogPrint("test_DropBoxMetadata_PayloadInspector") << histo1.data() << std::endl; + + edm::LogPrint("test_DropBoxMetadata_PayloadInspector") << "## test Compare" << std::endl; + + DropBoxMetadata_Compare histo2; + histo2.process(connectionString, PI::mk_input(tag, start, end)); + edm::LogPrint("test_DropBoxMetadata_PayloadInspector") << histo2.data() << std::endl; + + Py_Finalize(); +} diff --git a/CondCore/PhysicsToolsPlugins/test/test_DropBoxMetadata_PayloadInspector.sh b/CondCore/PhysicsToolsPlugins/test/test_DropBoxMetadata_PayloadInspector.sh new file mode 100755 index 0000000000000..4c58b11d0f02b --- /dev/null +++ b/CondCore/PhysicsToolsPlugins/test/test_DropBoxMetadata_PayloadInspector.sh @@ -0,0 +1,37 @@ +#!/bin/bash +# Save current working dir so img can be outputted there later +W_DIR=$(pwd); +# Set SCRAM architecture var +SCRAM_ARCH=slc7_amd64_gcc900; +export SCRAM_ARCH; +source /afs/cern.ch/cms/cmsset_default.sh; +eval `scram run -sh`; + +mkdir -p $W_DIR/results + +getPayloadData.py \ + --plugin pluginDropBoxMetadata_PayloadInspector \ + --plot plot_DropBoxMetadataTest \ + --tag DropBoxMetadata_v5.1_express \ + --time_type Run \ + --iovs '{"start_iov": "345684", "end_iov": "345684"}' \ + --db Prod \ + --test + +getPayloadData.py \ + --plugin pluginDropBoxMetadata_PayloadInspector \ + --plot plot_DropBoxMetadata_Display \ + --tag DropBoxMetadata_v5.1_express \ + --time_type Run \ + --iovs '{"start_iov": "345684", "end_iov": "345684"}' \ + --db Prod \ + --test + +getPayloadData.py \ + --plugin pluginDropBoxMetadata_PayloadInspector \ + --plot plot_DropBoxMetadata_Compare \ + --tag DropBoxMetadata_v5.1_express \ + --time_type Run \ + --iovs '{"start_iov": "345684", "end_iov": "346361"}' \ + --db Prod \ + --test diff --git a/CondCore/Utilities/test/iovInspector_test.py b/CondCore/Utilities/test/iovInspector_test.py index 9065993317dca..009ea9bc2c42e 100644 --- a/CondCore/Utilities/test/iovInspector_test.py +++ b/CondCore/Utilities/test/iovInspector_test.py @@ -1,7 +1,7 @@ from __future__ import print_function # test of iovInpector -import os,os.path,string,commands +import os,os.path,string import pluginCondDBPyInterface as CondDB from CondCore.Utilities import iovInspector as inspect diff --git a/CondFormats/BTauObjects/interface/BTagCalibration.h b/CondFormats/BTauObjects/interface/BTagCalibration.h index 26edd475b4932..b7bf7a49995eb 100644 --- a/CondFormats/BTauObjects/interface/BTagCalibration.h +++ b/CondFormats/BTauObjects/interface/BTagCalibration.h @@ -28,7 +28,7 @@ class BTagCalibration { public: BTagCalibration() {} BTagCalibration(const std::string &tagger); - BTagCalibration(const std::string &tagger, const std::string &filename); + BTagCalibration(const std::string &tagger, const std::string &filename, bool validate); ~BTagCalibration() {} std::string tagger() const { return tagger_; } @@ -36,8 +36,8 @@ class BTagCalibration { void addEntry(const BTagEntry &entry); const std::vector &getEntries(const BTagEntry::Parameters &par) const; - void readCSV(std::istream &s); - void readCSV(const std::string &s); + void readCSV(std::istream &s, bool validate); + void readCSV(const std::string &s, bool validate); void makeCSV(std::ostream &s) const; std::string makeCSV() const; diff --git a/CondFormats/BTauObjects/interface/BTagEntry.h b/CondFormats/BTauObjects/interface/BTagEntry.h index 94064868b09db..fe9465ef9f316 100644 --- a/CondFormats/BTauObjects/interface/BTagEntry.h +++ b/CondFormats/BTauObjects/interface/BTagEntry.h @@ -62,7 +62,7 @@ class BTagEntry { }; BTagEntry() {} - BTagEntry(const std::string& csvLine); + BTagEntry(const std::string& csvLine, bool validate); BTagEntry(const std::string& func, Parameters p); BTagEntry(const TF1* func, Parameters p); BTagEntry(const TH1* histo, Parameters p); diff --git a/CondFormats/BTauObjects/src/BTagCalibration.cc b/CondFormats/BTauObjects/src/BTagCalibration.cc index f7ad510c04f62..0dcb80b756ccf 100644 --- a/CondFormats/BTauObjects/src/BTagCalibration.cc +++ b/CondFormats/BTauObjects/src/BTagCalibration.cc @@ -6,12 +6,13 @@ BTagCalibration::BTagCalibration(const std::string &taggr) : tagger_(taggr) {} -BTagCalibration::BTagCalibration(const std::string &taggr, const std::string &filename) : tagger_(taggr) { +BTagCalibration::BTagCalibration(const std::string &taggr, const std::string &filename, bool validate) + : tagger_(taggr) { std::ifstream ifs(filename); if (!ifs.good()) { throw cms::Exception("BTagCalibration") << "input file not available: " << filename; } - readCSV(ifs); + readCSV(ifs, validate); ifs.close(); } @@ -25,18 +26,18 @@ const std::vector &BTagCalibration::getEntries(const BTagEntry::Param return data_.at(tok); } -void BTagCalibration::readCSV(const std::string &s) { +void BTagCalibration::readCSV(const std::string &s, bool validate) { std::stringstream buff(s); - readCSV(buff); + readCSV(buff, validate); } -void BTagCalibration::readCSV(std::istream &s) { +void BTagCalibration::readCSV(std::istream &s, bool validate) { std::string line; // firstline might be the header getline(s, line); if (line.find("OperatingPoint") == std::string::npos) { - addEntry(BTagEntry(line)); + addEntry(BTagEntry(line, validate)); } while (getline(s, line)) { @@ -44,7 +45,7 @@ void BTagCalibration::readCSV(std::istream &s) { if (line.empty()) { // skip empty lines continue; } - addEntry(BTagEntry(line)); + addEntry(BTagEntry(line, validate)); } } diff --git a/CondFormats/BTauObjects/src/BTagEntry.cc b/CondFormats/BTauObjects/src/BTagEntry.cc index a0781f53d7f68..29d5dc6021a42 100644 --- a/CondFormats/BTauObjects/src/BTagEntry.cc +++ b/CondFormats/BTauObjects/src/BTagEntry.cc @@ -28,7 +28,7 @@ BTagEntry::Parameters::Parameters(OperatingPoint op, std::transform(sysType.begin(), sysType.end(), sysType.begin(), ::tolower); } -BTagEntry::BTagEntry(const std::string& csvLine) { +BTagEntry::BTagEntry(const std::string& csvLine, bool validate) { // make tokens std::stringstream buff(csvLine); std::vector vec; @@ -54,9 +54,11 @@ BTagEntry::BTagEntry(const std::string& csvLine) { // make formula formula = vec[10]; - TF1 f1("", formula.c_str()); // compile formula to check validity - if (f1.IsZombie()) { - throw cms::Exception("BTagCalibration") << "Invalid csv line; formula does not compile: " << csvLine; + if (validate) { + TF1 f1("", formula.c_str()); // compile formula to check validity + if (f1.IsZombie()) { + throw cms::Exception("BTagCalibration") << "Invalid csv line; formula does not compile: " << csvLine; + } } // make parameters diff --git a/CondFormats/BTauObjects/test/testBTagCalibration.cpp b/CondFormats/BTauObjects/test/testBTagCalibration.cpp index 6e4203f7dc844..aba8e919c456f 100644 --- a/CondFormats/BTauObjects/test/testBTagCalibration.cpp +++ b/CondFormats/BTauObjects/test/testBTagCalibration.cpp @@ -18,7 +18,7 @@ int main() { "0, comb, down, 0, 1, 2, 3, 4, 5, 6, \"2*x\" \n"); stringstream csv1Stream(csv1); BTagCalibration b1("csv"); - b1.readCSV(csv1Stream); + b1.readCSV(csv1Stream, true); // assert correct length of vectors auto e1 = b1.getEntries(BTagEntry::Parameters(BTagEntry::OP_LOOSE, "comb", "central")); @@ -37,7 +37,7 @@ int main() { csv2Stream1 << tggr << ";" << BTagEntry::makeCSVHeader() << csv2_1 << csv2_2; csv2Stream2 << tggr << ";" << BTagEntry::makeCSVHeader() << csv2_2 << csv2_1; BTagCalibration b2(tggr); - b2.readCSV(csv2Stream1); + b2.readCSV(csv2Stream1, true); stringstream csv3Stream; b2.makeCSV(csv3Stream); diff --git a/CondFormats/BTauObjects/test/testBTagEntry.cpp b/CondFormats/BTauObjects/test/testBTagEntry.cpp index becb2427a44ee..5a01392431d7e 100644 --- a/CondFormats/BTauObjects/test/testBTagEntry.cpp +++ b/CondFormats/BTauObjects/test/testBTagEntry.cpp @@ -39,7 +39,7 @@ int main() { // csv constructor string csv = "0, comb, up, 0, 1, 2, 3, 4, 5, 6, \"2*x\" \n"; - auto b4 = BTagEntry(csv); + auto b4 = BTagEntry(csv, true); auto csv2 = b4.makeCSVLine(); assert(b4.params.etaMin == 1); assert(b4.params.etaMax == 2); diff --git a/CondFormats/Common/interface/DropBoxMetadata.h b/CondFormats/Common/interface/DropBoxMetadata.h index b86d39687bab7..c00e22cda0d7f 100644 --- a/CondFormats/Common/interface/DropBoxMetadata.h +++ b/CondFormats/Common/interface/DropBoxMetadata.h @@ -43,6 +43,8 @@ class DropBoxMetadata { bool knowsRecord(const std::string& record) const; + const std::vector getAllRecords() const; + protected: private: std::map recordSet; diff --git a/CondFormats/Common/src/DropBoxMetadata.cc b/CondFormats/Common/src/DropBoxMetadata.cc index a6d890024f79e..18ac6f7dc0a2f 100644 --- a/CondFormats/Common/src/DropBoxMetadata.cc +++ b/CondFormats/Common/src/DropBoxMetadata.cc @@ -8,6 +8,7 @@ */ #include "CondFormats/Common/interface/DropBoxMetadata.h" +#include // for std::transform using std::map; using std::string; @@ -43,3 +44,14 @@ bool DropBoxMetadata::knowsRecord(const std::string& record) const { return false; } + +const std::vector DropBoxMetadata::getAllRecords() const { + std::vector records; + std::transform(recordSet.begin(), + recordSet.end(), + std::inserter(records, records.end()), + [](std::pair recordSetEntry) -> std::string { + return recordSetEntry.first; + }); + return records; +} diff --git a/CondFormats/Common/test/CTPPSRPAlignmentCorrectionsDataRcd_prep.json b/CondFormats/Common/test/CTPPSRPAlignmentCorrectionsDataRcd_prep.json new file mode 100644 index 0000000000000..06bdbaee63228 --- /dev/null +++ b/CondFormats/Common/test/CTPPSRPAlignmentCorrectionsDataRcd_prep.json @@ -0,0 +1,9 @@ +{ + "destinationDatabase": "oracle://cms_orcoff_prep/CMS_CONDITIONS", + "destinationTags": { + "CTPPSRPAlignment_byPCL_v0_prompt": {} + }, + "inputTag": "CTPPSRPAlignment_real_pcl", + "since": null, + "userText": "Tier0 PCL Upload for CTPPSRPAlignment" +} diff --git a/CondFormats/Common/test/CTPPSRPAlignmentCorrectionsDataRcd_prod.json b/CondFormats/Common/test/CTPPSRPAlignmentCorrectionsDataRcd_prod.json new file mode 100644 index 0000000000000..d5c5077599827 --- /dev/null +++ b/CondFormats/Common/test/CTPPSRPAlignmentCorrectionsDataRcd_prod.json @@ -0,0 +1,9 @@ +{ + "destinationDatabase": "oracle://cms_orcon_prod/CMS_CONDITIONS", + "destinationTags": { + "CTPPSRPAlignment_byPCL_v0_prompt": {} + }, + "inputTag": "CTPPSRPAlignment_real_pcl", + "since": null, + "userText": "Tier0 PCL Upload for CTPPSRPAlignment" +} diff --git a/CondFormats/Common/test/PPSTimingCalibrationRcd_Sampic_prep.json b/CondFormats/Common/test/PPSTimingCalibrationRcd_Sampic_prep.json new file mode 100644 index 0000000000000..715f2b5cdd7c0 --- /dev/null +++ b/CondFormats/Common/test/PPSTimingCalibrationRcd_Sampic_prep.json @@ -0,0 +1,9 @@ +{ + "destinationDatabase": "oracle://cms_orcoff_prep/CMS_CONDITIONS", + "destinationTags": { + "CTPPPSTimingCalibration_SAMPIC_byPCL_v0_prompt": {} + }, + "inputTag": "DiamondSampicCalibration", + "since": null, + "userText": "Tier0 PCL Upload for PPSDiamondTimingCalibration (Sampic)" +} diff --git a/CondFormats/Common/test/PPSTimingCalibrationRcd_Sampic_prod.json b/CondFormats/Common/test/PPSTimingCalibrationRcd_Sampic_prod.json new file mode 100644 index 0000000000000..e876a5850632e --- /dev/null +++ b/CondFormats/Common/test/PPSTimingCalibrationRcd_Sampic_prod.json @@ -0,0 +1,9 @@ +{ + "destinationDatabase": "oracle://cms_orcon_prod/CMS_CONDITIONS", + "destinationTags": { + "CTPPPSTimingCalibration_SAMPIC_byPCL_v0_prompt": {} + }, + "inputTag": "DiamondSampicCalibration", + "since": null, + "userText": "Tier0 PCL Upload for PPSDiamondTimingCalibration (Sampic)" +} diff --git a/CondFormats/Common/test/PPSTimingCalibrationRcd_prep.json b/CondFormats/Common/test/PPSTimingCalibrationRcd_prep.json new file mode 100644 index 0000000000000..50a6d8e7977b2 --- /dev/null +++ b/CondFormats/Common/test/PPSTimingCalibrationRcd_prep.json @@ -0,0 +1,9 @@ +{ + "destinationDatabase": "oracle://cms_orcoff_prep/CMS_CONDITIONS", + "destinationTags": { + "CTPPPSTimingCalibration_HPTDC_byPCL_v0_prompt": {} + }, + "inputTag": "PPSDiamondTimingCalibration_pcl", + "since": null, + "userText": "Tier0 PCL Upload for PPSDiamondTimingCalibration (HPTDC)" +} diff --git a/CondFormats/Common/test/PPSTimingCalibrationRcd_prod.json b/CondFormats/Common/test/PPSTimingCalibrationRcd_prod.json new file mode 100644 index 0000000000000..8f84eca130899 --- /dev/null +++ b/CondFormats/Common/test/PPSTimingCalibrationRcd_prod.json @@ -0,0 +1,9 @@ +{ + "destinationDatabase": "oracle://cms_orcon_prod/CMS_CONDITIONS", + "destinationTags": { + "CTPPPSTimingCalibration_HPTDC_byPCL_v0_prompt": {} + }, + "inputTag": "PPSDiamondTimingCalibration_pcl", + "since": null, + "userText": "Tier0 PCL Upload for PPSDiamondTimingCalibration (HPTDC)" +} diff --git a/CondFormats/Common/test/ProduceDropBoxMetadata.py b/CondFormats/Common/test/ProduceDropBoxMetadata.py index 3abffa9f09d3e..98e22e0705e06 100644 --- a/CondFormats/Common/test/ProduceDropBoxMetadata.py +++ b/CondFormats/Common/test/ProduceDropBoxMetadata.py @@ -70,7 +70,7 @@ def encodeJsonInString(filename): LumiCorrectionsRcd_prod_str = encodeJsonInString("LumiCorrections_prod.json") LumiCorrectionsRcd_prep_str = encodeJsonInString("LumiCorrections_prep.json") -#PixelQuality +#SiPixelQuality SiPixelQualityFromDbRcd_prompt_prod_str = encodeJsonInString("SiPixelQualityFromDbRcd_prompt_prod.json") SiPixelQualityFromDbRcd_prompt_prep_str = encodeJsonInString("SiPixelQualityFromDbRcd_prompt_prep.json") SiPixelQualityFromDbRcd_stuckTBM_prod_str = encodeJsonInString("SiPixelQualityFromDbRcd_stuckTBM_prod.json") @@ -78,6 +78,21 @@ def encodeJsonInString(filename): SiPixelQualityFromDbRcd_other_prod_str = encodeJsonInString("SiPixelQualityFromDbRcd_other_prod.json") SiPixelQualityFromDbRcd_other_prep_str = encodeJsonInString("SiPixelQualityFromDbRcd_other_prep.json") +#SiPixelLorenzAngle +SiPixelLorentzAngleRcd_prod_str = encodeJsonInString("SiPixelLorentzAngleRcd_prod.json") +SiPixelLorentzAngleRcd_multirun_prod_str = encodeJsonInString("SiPixelLorentzAngleRcd_multirun_prod.json") +SiPixelLorentzAngleRcd_prep_str = encodeJsonInString("SiPixelLorentzAngleRcd_prep.json") +SiPixelLorentzAngleRcd_multirun_prep_str = encodeJsonInString("SiPixelLorentzAngleRcd_multirun_prep.json") + +#CT-PPS alignment and timing +CTPPSRPAlignmentCorrectionsDataRcd_prod_str = encodeJsonInString("CTPPSRPAlignmentCorrectionsDataRcd_prod.json") +CTPPSRPAlignmentCorrectionsDataRcd_prep_str = encodeJsonInString("CTPPSRPAlignmentCorrectionsDataRcd_prep.json") +PPSTimingCalibrationRcd_prod_str = encodeJsonInString("PPSTimingCalibrationRcd_prod.json") +PPSTimingCalibrationRcd_prep_str = encodeJsonInString("PPSTimingCalibrationRcd_prep.json") +PPSTimingCalibrationRcd_Sampic_prod_str = encodeJsonInString("PPSTimingCalibrationRcd_Sampic_prod.json") +PPSTimingCalibrationRcd_Sampic_prep_str = encodeJsonInString("PPSTimingCalibrationRcd_Sampic_prep.json") + + # given a set of .json files in the current dir, ProduceDropBoxMetadata produces a sqlite containign the payload with the prod/and/prep metadata process.mywriter = cms.EDAnalyzer("ProduceDropBoxMetadata", # set to True if you want to write out a sqlite.db translating the json's into a payload @@ -172,13 +187,39 @@ def encodeJsonInString(filename): prodMetaData = cms.untracked.string(SiPixelQualityFromDbRcd_other_prod_str), prepMetaData = cms.untracked.string(SiPixelQualityFromDbRcd_other_prep_str), ), + cms.PSet(record = cms.untracked.string('SiPixelLorentzAngleRcd'), + Source = cms.untracked.string("AlcaHarvesting"), + FileClass = cms.untracked.string("ALCA"), + prodMetaData = cms.untracked.string(SiPixelLorentzAngleRcd_prod_str), + prodMetaDataMultiRun = cms.untracked.string(SiPixelLorentzAngleRcd_multirun_prod_str), + prepMetaData = cms.untracked.string(SiPixelLorentzAngleRcd_prep_str), + prepMetaDataMultiRun = cms.untracked.string(SiPixelLorentzAngleRcd_multirun_prep_str), + ), + cms.PSet(record = cms.untracked.string('CTPPSRPAlignmentCorrectionsDataRcd'), + Source = cms.untracked.string("AlcaHarvesting"), + FileClass = cms.untracked.string("ALCA"), + prodMetaData = cms.untracked.string(CTPPSRPAlignmentCorrectionsDataRcd_prod_str), + prepMetaData = cms.untracked.string(CTPPSRPAlignmentCorrectionsDataRcd_prep_str), + ), + cms.PSet(record = cms.untracked.string('PPSTimingCalibrationRcd'), + Source = cms.untracked.string("AlcaHarvesting"), + 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 read = cms.untracked.bool(False), - # toRead lists of record naemes to be sought inside the DropBoxMetadataRcd payload avaialble to the ProduceDropBoxMetadata; for instance, if write is True, you're reading back the metadata you've just entered in the payload from the .json files - toRead = cms.untracked.vstring('BeamSpotObjectsRcdByRun','BeamSpotObjectsRcdByLumi','BeamSpotObjectsRcdHPByLumi','BeamSpotObjectsRcdHPByRun','SiStripBadStripRcd','SiStripApvGainRcd','TrackerAlignmentRcd','SiStripApvGainRcdAfterAbortGap','SiStripApvGainRcdAAG','EcalPedestalsRcd',"LumiCorrectionsRcd","SiPixelQualityFromDbRcd_prompt","SiPixelQualityFromDbRcd_stuckTBM","SiPixelQualityFromDbRcd_other") # same strings as fType + # toRead lists of record names to be sought inside the DropBoxMetadataRcd payload avaialble to the ProduceDropBoxMetadata; for instance, if write is True, you're reading back the metadata you've just entered in the payload from the .json files + toRead = cms.untracked.vstring('BeamSpotObjectsRcdByRun','BeamSpotObjectsRcdByLumi','BeamSpotObjectsRcdHPByLumi','BeamSpotObjectsRcdHPByRun','SiStripBadStripRcd','SiStripApvGainRcd','TrackerAlignmentRcd','SiStripApvGainRcdAfterAbortGap','SiStripApvGainRcdAAG','EcalPedestalsRcd',"LumiCorrectionsRcd","SiPixelQualityFromDbRcd_prompt","SiPixelQualityFromDbRcd_stuckTBM","SiPixelQualityFromDbRcd_other","SiPixelLorentzAngleRcd","CTPPSRPAlignmentCorrectionsDataRcd","PPSTimingCalibrationRcd","PPSTimingCalibrationRcd_Sampic") # same strings as fType ) process.p = cms.Path(process.mywriter) @@ -201,10 +242,7 @@ def encodeJsonInString(filename): ) process.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_cff') -process.GlobalTag.globaltag = '92X_dataRun2_Express_Queue' - -#process.GlobalTag.connect = 'frontier://PromptProd/CMS_CONDITIONS' -#process.GlobalTag.connect = 'sqlite_file:/data/franzoni/92x/CMSSW_9_2_X_2017-05-16-1100_metadata/src/CondFormats/Common/test/last-iov-DropBoxMetadata_v5.1_express.db' +process.GlobalTag.globaltag = '121X_dataRun3_Express_Queue' # Set to True if you want to read a DropBoxMetadata payload from a local sqlite # specify the name of the sqlitefile.db and the tag name; the payload loaded will be for run 300000 diff --git a/CondFormats/Common/test/SiPixelLorentzAngleRcd_multirun_prep.json b/CondFormats/Common/test/SiPixelLorentzAngleRcd_multirun_prep.json new file mode 100644 index 0000000000000..ff39c072ed734 --- /dev/null +++ b/CondFormats/Common/test/SiPixelLorentzAngleRcd_multirun_prep.json @@ -0,0 +1,9 @@ +{ + "destinationDatabase": "oracle://cms_orcoff_prep/CMS_CONDITIONS", + "destinationTags": { + "SiPixelLorentzAngle_byPCL_multirun_v0_prompt": {} + }, + "inputTag": "SiPixelLA_pcl", + "since": null, + "userText": "Multirun Upload for SiPixelLA (prep)" +} diff --git a/CondFormats/Common/test/SiPixelLorentzAngleRcd_multirun_prod.json b/CondFormats/Common/test/SiPixelLorentzAngleRcd_multirun_prod.json new file mode 100644 index 0000000000000..df32cdc305153 --- /dev/null +++ b/CondFormats/Common/test/SiPixelLorentzAngleRcd_multirun_prod.json @@ -0,0 +1,9 @@ +{ + "destinationDatabase": "oracle://cms_orcon_prod/CMS_CONDITIONS", + "destinationTags": { + "SiPixelLorentzAngle_byPCL_multirun_v0_prompt": {} + }, + "inputTag": "SiPixelLA_pcl", + "since": null, + "userText": "Multirun Upload for SiPixelLorentzAngle" +} diff --git a/CondFormats/Common/test/SiPixelLorentzAngleRcd_prep.json b/CondFormats/Common/test/SiPixelLorentzAngleRcd_prep.json new file mode 100644 index 0000000000000..85caef817b82d --- /dev/null +++ b/CondFormats/Common/test/SiPixelLorentzAngleRcd_prep.json @@ -0,0 +1,9 @@ +{ + "destinationDatabase": "oracle://cms_orcoff_prep/CMS_CONDITIONS", + "destinationTags": { + "SiPixelLorentzAngle_byPCL_v0_prompt": {} + }, + "inputTag": "SiPixelLA_pcl", + "since": null, + "userText": "Tier0 PCL Upload for SiPixelLA (prep)" +} diff --git a/CondFormats/Common/test/SiPixelLorentzAngleRcd_prod.json b/CondFormats/Common/test/SiPixelLorentzAngleRcd_prod.json new file mode 100644 index 0000000000000..b444a98d0bd5b --- /dev/null +++ b/CondFormats/Common/test/SiPixelLorentzAngleRcd_prod.json @@ -0,0 +1,9 @@ +{ + "destinationDatabase": "oracle://cms_orcon_prod/CMS_CONDITIONS", + "destinationTags": { + "SiPixelLorentzAngle_byPCL_v0_prompt": {} + }, + "inputTag": "SiPixelLA_pcl", + "since": null, + "userText": "Tier0 PCL Upload for SiPixelLorentzAngle" +} diff --git a/CondFormats/PCLConfig/plugins/AlignPCLThresholdsWriter.cc b/CondFormats/PCLConfig/plugins/AlignPCLThresholdsWriter.cc index eb0089aec3d30..62655fad84a9f 100644 --- a/CondFormats/PCLConfig/plugins/AlignPCLThresholdsWriter.cc +++ b/CondFormats/PCLConfig/plugins/AlignPCLThresholdsWriter.cc @@ -179,7 +179,7 @@ void AlignPCLThresholdsWriter::analyze(const edm::Event& iEvent, const edm::Even if (poolDbService.isAvailable()) { cond::Time_t valid_time = poolDbService->currentTime(); // this writes the payload to begin in current run defined in cfg - poolDbService->writeOne(myThresholds, valid_time, m_record); + poolDbService->writeOneIOV(*myThresholds, valid_time, m_record); } } diff --git a/CondFormats/PPSObjects/interface/PPSAssociationCuts.h b/CondFormats/PPSObjects/interface/PPSAssociationCuts.h index 12bbcd6d01538..486fe22eff03d 100644 --- a/CondFormats/PPSObjects/interface/PPSAssociationCuts.h +++ b/CondFormats/PPSObjects/interface/PPSAssociationCuts.h @@ -12,6 +12,7 @@ struct TF1; #include "CondFormats/Serialization/interface/Serializable.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/ParameterSet/interface/ParameterSetDescription.h" +#include "FWCore/Utilities/interface/Exception.h" #include #include @@ -36,6 +37,9 @@ class PPSAssociationCuts { double getTiTrMin() const { return ti_tr_min_; } double getTiTrMax() const { return ti_tr_max_; } + // build TF1 representations of the mean and threshold functions + void buildFunctions(); + // returns whether the specified cut is applied bool isApplied(Quantities quantity) const; @@ -66,7 +70,13 @@ class PPSAssociationCuts { ~PPSAssociationCuts() {} - const CutsPerArm &getAssociationCuts(const int sector) const { return association_cuts_.at(sector); } + // checks if the data have a valid structure + bool isValid() const; + + // builds run-time data members, useful e.g. after loading data from DB + void initialize(); + + const CutsPerArm &getAssociationCuts(const int sector) const { return association_cuts_.find(sector)->second; } static edm::ParameterSetDescription getDefaultParameters(); diff --git a/CondFormats/PPSObjects/src/PPSAssociationCuts.cc b/CondFormats/PPSObjects/src/PPSAssociationCuts.cc index ca04123c98c06..f486947af6aae 100644 --- a/CondFormats/PPSObjects/src/PPSAssociationCuts.cc +++ b/CondFormats/PPSObjects/src/PPSAssociationCuts.cc @@ -23,9 +23,6 @@ PPSAssociationCuts::CutsPerArm::CutsPerArm(const edm::ParameterSet &iConfig, int std::string threshold = association_cuts.getParameter(names[i] + "_cut_threshold"); s_thresholds_.push_back(threshold); - - f_means_.push_back(std::make_shared("f", mean.c_str())); - f_thresholds_.push_back(std::make_shared("f", threshold.c_str())); } ti_tr_min_ = association_cuts.getParameter("ti_tr_min"); @@ -34,18 +31,35 @@ PPSAssociationCuts::CutsPerArm::CutsPerArm(const edm::ParameterSet &iConfig, int //---------------------------------------------------------------------------------------------------- +void PPSAssociationCuts::CutsPerArm::buildFunctions() { + f_means_.clear(); + for (const auto &s : s_means_) + f_means_.push_back(std::make_shared("f", s.c_str())); + + f_thresholds_.clear(); + for (const auto &s : s_thresholds_) + f_thresholds_.push_back(std::make_shared("f", s.c_str())); +} + +//---------------------------------------------------------------------------------------------------- + bool PPSAssociationCuts::CutsPerArm::isApplied(Quantities quantity) const { - return (!s_thresholds_.at(quantity).empty()) && (!s_means_.at(quantity).empty()); + return (!s_thresholds_[quantity].empty()) && (!s_means_[quantity].empty()); } //---------------------------------------------------------------------------------------------------- bool PPSAssociationCuts::CutsPerArm::isSatisfied( Quantities quantity, double x_near, double y_near, double xangle, double q_NF_diff) const { + // if cut not applied, then condition considered as satisfied if (!isApplied(quantity)) return true; - const double mean = evaluateExpression(f_means_.at(quantity), x_near, y_near, xangle); - const double threshold = evaluateExpression(f_thresholds_.at(quantity), x_near, y_near, xangle); + + // evaluate mean and threshold + const double mean = evaluateExpression(f_means_[quantity], x_near, y_near, xangle); + const double threshold = evaluateExpression(f_thresholds_[quantity], x_near, y_near, xangle); + + // make comparison return fabs(q_NF_diff - mean) < threshold; } @@ -67,6 +81,8 @@ PPSAssociationCuts::PPSAssociationCuts(const edm::ParameterSet &iConfig) { unsigned int i = 0; for (const int §or : {45, 56}) association_cuts_[i++] = CutsPerArm(iConfig, sector); + + initialize(); } //---------------------------------------------------------------------------------------------------- @@ -94,6 +110,31 @@ edm::ParameterSetDescription PPSAssociationCuts::getDefaultParameters() { //---------------------------------------------------------------------------------------------------- +bool PPSAssociationCuts::isValid() const { + // valid if association_cuts_ have two entries, with keys 0 and 1 + if (association_cuts_.size() != 2) + return false; + + if (association_cuts_.find(0) == association_cuts_.end()) + return false; + if (association_cuts_.find(1) == association_cuts_.end()) + return false; + + return true; +} + +//---------------------------------------------------------------------------------------------------- + +void PPSAssociationCuts::initialize() { + if (!isValid()) + throw cms::Exception("PPS") << "Invalid structure of PPSAssociationCuts."; + + for (auto &p : association_cuts_) + p.second.buildFunctions(); +} + +//---------------------------------------------------------------------------------------------------- + std::ostream &operator<<(std::ostream &os, const PPSAssociationCuts::CutsPerArm &cutsPerArm) { os << "CutsPerArm {" << std::endl; diff --git a/CondFormats/PhysicsToolsObjects/test/SiStripDeDx2DBuilder.cc b/CondFormats/PhysicsToolsObjects/test/SiStripDeDx2DBuilder.cc index 4a66e17d3f369..240c9fc6f71cb 100644 --- a/CondFormats/PhysicsToolsObjects/test/SiStripDeDx2DBuilder.cc +++ b/CondFormats/PhysicsToolsObjects/test/SiStripDeDx2DBuilder.cc @@ -39,7 +39,7 @@ void SiStripDeDx2DBuilder::analyze(const edm::Event& evt, const edm::EventSetup& << "... creating dummy PhysicsToolsObjects::Calibration::HistogramD2D Data for Run " << run << "\n " << std::endl; // PhysicsToolsObjects::Calibration::HistogramD2D* obj = new PhysicsTools::Calibration::HistogramD2D(300, 0., 3., 1000,0.,1000.); - PhysicsTools::Calibration::VHistogramD2D* obj = new PhysicsTools::Calibration::VHistogramD2D(); + PhysicsTools::Calibration::VHistogramD2D obj; for (int ih = 0; ih < 3; ih++) { PhysicsTools::Calibration::HistogramD2D myhist(300, 0., 3., 1000, 0., 1000.); @@ -49,8 +49,8 @@ void SiStripDeDx2DBuilder::analyze(const edm::Event& evt, const edm::EventSetup& } } - (obj->vHist).push_back(myhist); - (obj->vValues).push_back(ih); + (obj.vHist).push_back(myhist); + (obj.vValues).push_back(ih); } // SiStripDetInfoFileReader reader(fp_.fullPath()); @@ -72,7 +72,7 @@ void SiStripDeDx2DBuilder::analyze(const edm::Event& evt, const edm::EventSetup& // } // PhysicsToolsObjects::Calibration::HistogramD2D::Range range(theSiStripVector.begin(),theSiStripVector.end()); - // if ( ! obj->put(it->first,range) ) + // if ( ! obj.put(it->first,range) ) // edm::LogError("PhysicsToolsObjects::Calibration::HistogramD2DBuilder")<<"[PhysicsToolsObjects::Calibration::HistogramD2DBuilder::analyze] detid already exists"<isNewTagRequest("SiStripDeDxProton_2D_Rcd")) { - mydbservice->createNewIOV( - obj, mydbservice->beginOfTime(), mydbservice->endOfTime(), "SiStripDeDxProton_2D_Rcd"); + mydbservice->createOneIOV( + obj, mydbservice->beginOfTime(), "SiStripDeDxProton_2D_Rcd"); } else { - mydbservice->appendSinceTime( + mydbservice->appendOneIOV( obj, mydbservice->currentTime(), "SiStripDeDxProton_2D_Rcd"); } } else { diff --git a/CondFormats/PhysicsToolsObjects/test/SiStripDeDx2DReader.cc b/CondFormats/PhysicsToolsObjects/test/SiStripDeDx2DReader.cc index 3d7869bd5c391..8df768c27aa9a 100644 --- a/CondFormats/PhysicsToolsObjects/test/SiStripDeDx2DReader.cc +++ b/CondFormats/PhysicsToolsObjects/test/SiStripDeDx2DReader.cc @@ -6,7 +6,7 @@ // user include files #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/ESHandle.h" @@ -20,7 +20,7 @@ #include #include -class SiStripDeDx2DReader : public edm::EDAnalyzer { +class SiStripDeDx2DReader : public edm::one::EDAnalyzer<> { public: explicit SiStripDeDx2DReader(const edm::ParameterSet&); ~SiStripDeDx2DReader(); @@ -28,17 +28,15 @@ class SiStripDeDx2DReader : public edm::EDAnalyzer { void analyze(const edm::Event&, const edm::EventSetup&); private: - // uint32_t printdebug_; + const edm::ESGetToken SiStripDeDx2DToken_; }; -SiStripDeDx2DReader::SiStripDeDx2DReader(const edm::ParameterSet& iConfig) {} -//: printdebug_(iConfig.getUntrackedParameter("printDebug",1)){} +SiStripDeDx2DReader::SiStripDeDx2DReader(const edm::ParameterSet& iConfig) : SiStripDeDx2DToken_(esConsumes()) {} -SiStripDeDx2DReader::~SiStripDeDx2DReader() {} +SiStripDeDx2DReader::~SiStripDeDx2DReader() = default; void SiStripDeDx2DReader::analyze(const edm::Event& e, const edm::EventSetup& iSetup) { - edm::ESHandle SiStripDeDx2D_; - iSetup.get().get(SiStripDeDx2D_); + edm::ESHandle SiStripDeDx2D_ = iSetup.getHandle(SiStripDeDx2DToken_); edm::LogInfo("SiStripDeDx2DReader") << "[SiStripDeDx2DReader::analyze] End Reading SiStripDeDxProton_2D" << std::endl; for (int ihisto = 0; ihisto < 3; ihisto++) { @@ -54,24 +52,6 @@ void SiStripDeDx2DReader::analyze(const edm::Event& e, const edm::EventSetup& iS std::cout << "Value = " << (SiStripDeDx2D_->vValues)[ihisto] << std::endl; } - - // std::vector detid; - // SiStripDeDx2D_->getDetIds(detid); - // edm::LogInfo("Number of detids ") << detid.size() << std::endl; - - // if (printdebug_) - // for (size_t id=0;idgetRange(detid[id]); - - // int apv=0; - // for(int it=0;itgetDeDx2D(it,range) << " \t" - // << std::endl; - // } - // } } #include "FWCore/PluginManager/interface/ModuleDef.h" diff --git a/CondFormats/PhysicsToolsObjects/test/SiStripDeDx3DBuilder.cc b/CondFormats/PhysicsToolsObjects/test/SiStripDeDx3DBuilder.cc index af44a27027488..ad91798fad1c2 100644 --- a/CondFormats/PhysicsToolsObjects/test/SiStripDeDx3DBuilder.cc +++ b/CondFormats/PhysicsToolsObjects/test/SiStripDeDx3DBuilder.cc @@ -39,14 +39,13 @@ void SiStripDeDx3DBuilder::analyze(const edm::Event& evt, const edm::EventSetup& << "... creating dummy PhysicsToolsObjects::Calibration::HistogramD3D Data for Run " << run << "\n " << std::endl; // PhysicsToolsObjects::Calibration::HistogramD2D* obj = new PhysicsTools::Calibration::HistogramD2D(300, 0., 3., 1000,0.,1000.); - PhysicsTools::Calibration::HistogramD3D* obj = - new PhysicsTools::Calibration::HistogramD3D(5, 0, 5, 100, 0., 3., 100, 0., 1000.); + PhysicsTools::Calibration::HistogramD3D obj(5, 0, 5, 100, 0., 3., 100, 0., 1000.); for (int ix = 0; ix < 5; ix++) { for (int iy = 0; iy < 100; iy++) { for (int iz = 0; iz < 100; iz++) { // edm::LogInfo("SiStripDeDx3DBuilder") << "X = " << ix << " Y = " << iy << " Z = " << iz << std::endl; - obj->setBinContent(ix, iy, iz, ix + 2 * iy + 3 * iz); + obj.setBinContent(ix, iy, iz, ix + 2 * iy + 3 * iz); } } } @@ -57,10 +56,10 @@ void SiStripDeDx3DBuilder::analyze(const edm::Event& evt, const edm::EventSetup& if (mydbservice.isAvailable()) { if (mydbservice->isNewTagRequest("SiStripDeDxProton_3D_Rcd")) { - mydbservice->createNewIOV( - obj, mydbservice->beginOfTime(), mydbservice->endOfTime(), "SiStripDeDxProton_3D_Rcd"); + mydbservice->createOneIOV( + obj, mydbservice->beginOfTime(), "SiStripDeDxProton_3D_Rcd"); } else { - mydbservice->appendSinceTime( + mydbservice->appendOneIOV( obj, mydbservice->currentTime(), "SiStripDeDxProton_3D_Rcd"); } } else { diff --git a/CondFormats/PhysicsToolsObjects/test/SiStripDeDx3DReader.cc b/CondFormats/PhysicsToolsObjects/test/SiStripDeDx3DReader.cc index ec334eb0576a1..8dce147563e7f 100644 --- a/CondFormats/PhysicsToolsObjects/test/SiStripDeDx3DReader.cc +++ b/CondFormats/PhysicsToolsObjects/test/SiStripDeDx3DReader.cc @@ -6,7 +6,7 @@ // user include files #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/ESHandle.h" @@ -20,7 +20,7 @@ #include #include -class SiStripDeDx3DReader : public edm::EDAnalyzer { +class SiStripDeDx3DReader : public edm::one::EDAnalyzer<> { public: explicit SiStripDeDx3DReader(const edm::ParameterSet&); ~SiStripDeDx3DReader(); @@ -28,17 +28,17 @@ class SiStripDeDx3DReader : public edm::EDAnalyzer { void analyze(const edm::Event&, const edm::EventSetup&); private: + const edm::ESGetToken SiStripDeDx3DToken_; // uint32_t printdebug_; }; -SiStripDeDx3DReader::SiStripDeDx3DReader(const edm::ParameterSet& iConfig) {} +SiStripDeDx3DReader::SiStripDeDx3DReader(const edm::ParameterSet& iConfig) : SiStripDeDx3DToken_(esConsumes()) {} //: printdebug_(iConfig.getUntrackedParameter("printDebug",1)){} -SiStripDeDx3DReader::~SiStripDeDx3DReader() {} +SiStripDeDx3DReader::~SiStripDeDx3DReader() = default; void SiStripDeDx3DReader::analyze(const edm::Event& e, const edm::EventSetup& iSetup) { - edm::ESHandle SiStripDeDx3D_; - iSetup.get().get(SiStripDeDx3D_); + edm::ESHandle SiStripDeDx3D_ = iSetup.getHandle(SiStripDeDx3DToken_); edm::LogInfo("SiStripDeDx3DReader") << "[SiStripDeDx3DReader::analyze] End Reading SiStripDeDxProton_3D" << std::endl; for (int ix = 0; ix < 5; ix++) { diff --git a/CondFormats/PhysicsToolsObjects/test/SiStripDeDxMipBuilder.cc b/CondFormats/PhysicsToolsObjects/test/SiStripDeDxMipBuilder.cc index 034feffd9bc85..632d4da6058d9 100644 --- a/CondFormats/PhysicsToolsObjects/test/SiStripDeDxMipBuilder.cc +++ b/CondFormats/PhysicsToolsObjects/test/SiStripDeDxMipBuilder.cc @@ -16,12 +16,11 @@ void SiStripDeDxMipBuilder::analyze(const edm::Event& evt, const edm::EventSetup << "... creating dummy PhysicsToolsObjects::Calibration::HistogramD2D Data for Run " << run << "\n " << std::endl; // PhysicsToolsObjects::Calibration::HistogramD2D* obj = new PhysicsTools::Calibration::HistogramD2D(300, 0., 3., 1000,0.,1000.); - PhysicsTools::Calibration::HistogramD2D* obj = - new PhysicsTools::Calibration::HistogramD2D(300, 0., 3., 1000, 0., 1000.); + PhysicsTools::Calibration::HistogramD2D obj(300, 0., 3., 1000, 0., 1000.); for (int ix = 0; ix < 300; ix++) { for (int iy = 0; iy < 1000; iy++) { - obj->setBinContent(ix, iy, iy / 999.); + obj.setBinContent(ix, iy, iy / 999.); } } @@ -44,7 +43,7 @@ void SiStripDeDxMipBuilder::analyze(const edm::Event& evt, const edm::EventSetup // } // PhysicsToolsObjects::Calibration::HistogramD2D::Range range(theSiStripVector.begin(),theSiStripVector.end()); - // if ( ! obj->put(it->first,range) ) + // if ( ! obj.put(it->first,range) ) // edm::LogError("PhysicsToolsObjects::Calibration::HistogramD2DBuilder")<<"[PhysicsToolsObjects::Calibration::HistogramD2DBuilder::analyze] detid already exists"<isNewTagRequest("SiStripDeDxMipRcd")) { - mydbservice->createNewIOV( - obj, mydbservice->beginOfTime(), mydbservice->endOfTime(), "SiStripDeDxMipRcd"); + mydbservice->createOneIOV( + obj, mydbservice->beginOfTime(), "SiStripDeDxMipRcd"); } else { - mydbservice->appendSinceTime( + mydbservice->appendOneIOV( obj, mydbservice->currentTime(), "SiStripDeDxMipRcd"); } } else { diff --git a/CondFormats/PhysicsToolsObjects/test/SiStripDeDxMipReader.cc b/CondFormats/PhysicsToolsObjects/test/SiStripDeDxMipReader.cc index c2c757427a52c..d99781e3cb8e7 100644 --- a/CondFormats/PhysicsToolsObjects/test/SiStripDeDxMipReader.cc +++ b/CondFormats/PhysicsToolsObjects/test/SiStripDeDxMipReader.cc @@ -1,22 +1,39 @@ -#include "CondFormats/PhysicsToolsObjects/interface/Histogram2D.h" -#include "CondFormats/DataRecord/interface/SiStripDeDxMipRcd.h" - -#include "CondFormats/PhysicsToolsObjects/test/SiStripDeDxMipReader.h" - +// system includes #include #include #include +// user include files +#include "CondFormats/PhysicsToolsObjects/interface/Histogram2D.h" +#include "CondFormats/DataRecord/interface/SiStripDeDxMipRcd.h" +#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/ESHandle.h" +#include "FWCore/ServiceRegistry/interface/Service.h" +#include "FWCore/MessageLogger/interface/MessageLogger.h" +#include "FWCore/ParameterSet/interface/ParameterSet.h" + +class SiStripDeDxMipReader : public edm::one::EDAnalyzer<> { +public: + explicit SiStripDeDxMipReader(const edm::ParameterSet&); + ~SiStripDeDxMipReader(); + + void analyze(const edm::Event&, const edm::EventSetup&); + +private: + const edm::ESGetToken SiStripDeDxMipToken_; +}; + using namespace cms; -SiStripDeDxMipReader::SiStripDeDxMipReader(const edm::ParameterSet& iConfig) {} -//: printdebug_(iConfig.getUntrackedParameter("printDebug",1)){} +SiStripDeDxMipReader::SiStripDeDxMipReader(const edm::ParameterSet& iConfig) : SiStripDeDxMipToken_(esConsumes()) {} -SiStripDeDxMipReader::~SiStripDeDxMipReader() {} +SiStripDeDxMipReader::~SiStripDeDxMipReader() = default; void SiStripDeDxMipReader::analyze(const edm::Event& e, const edm::EventSetup& iSetup) { - edm::ESHandle SiStripDeDxMip_; - iSetup.get().get(SiStripDeDxMip_); + edm::ESHandle SiStripDeDxMip_ = iSetup.getHandle(SiStripDeDxMipToken_); edm::LogInfo("SiStripDeDxMipReader") << "[SiStripDeDxMipReader::analyze] End Reading SiStripDeDxMip" << std::endl; std::cout << SiStripDeDxMip_->numberOfBinsX() << " " << SiStripDeDxMip_->numberOfBinsY() << std::endl; for (int ix = 0; ix < 300; ix++) { @@ -24,24 +41,6 @@ void SiStripDeDxMipReader::analyze(const edm::Event& e, const edm::EventSetup& i std::cout << SiStripDeDxMip_->binContent(ix, iy) << " " << SiStripDeDxMip_->value(ix / 100., iy) << std::endl; } } - - // std::vector detid; - // SiStripDeDxMip_->getDetIds(detid); - // edm::LogInfo("Number of detids ") << detid.size() << std::endl; - - // if (printdebug_) - // for (size_t id=0;idgetRange(detid[id]); - - // int apv=0; - // for(int it=0;itgetDeDxMip(it,range) << " \t" - // << std::endl; - // } - // } } #include "FWCore/PluginManager/interface/ModuleDef.h" diff --git a/CondFormats/PhysicsToolsObjects/test/SiStripDeDxMipReader.h b/CondFormats/PhysicsToolsObjects/test/SiStripDeDxMipReader.h deleted file mode 100644 index cb5143b310302..0000000000000 --- a/CondFormats/PhysicsToolsObjects/test/SiStripDeDxMipReader.h +++ /dev/null @@ -1,27 +0,0 @@ -#ifndef SiStripDeDxMipReader_H -#define SiStripDeDxMipReader_H - -// system include files -//#include - -// user include files -#include "FWCore/Framework/interface/Frameworkfwd.h" -#include "FWCore/Framework/interface/EDAnalyzer.h" -#include "FWCore/Framework/interface/Event.h" -#include "FWCore/Framework/interface/EventSetup.h" -#include "FWCore/Framework/interface/ESHandle.h" -#include "FWCore/ServiceRegistry/interface/Service.h" -#include "FWCore/MessageLogger/interface/MessageLogger.h" -#include "FWCore/ParameterSet/interface/ParameterSet.h" - -class SiStripDeDxMipReader : public edm::EDAnalyzer { -public: - explicit SiStripDeDxMipReader(const edm::ParameterSet&); - ~SiStripDeDxMipReader(); - - void analyze(const edm::Event&, const edm::EventSetup&); - -private: - // uint32_t printdebug_; -}; -#endif diff --git a/CondFormats/SiPixelObjects/interface/SiPixelGainCalibrationForHLT.h b/CondFormats/SiPixelObjects/interface/SiPixelGainCalibrationForHLT.h index 8ae84ba6fcb37..b7e0a8ee87235 100644 --- a/CondFormats/SiPixelObjects/interface/SiPixelGainCalibrationForHLT.h +++ b/CondFormats/SiPixelObjects/interface/SiPixelGainCalibrationForHLT.h @@ -107,8 +107,8 @@ class SiPixelGainCalibrationForHLT { private: float encodeGain(const float& gain); float encodePed(const float& ped); - float decodeGain(unsigned int gain) const { return gain * gainPrecision + minGain_; } - float decodePed(unsigned int ped) const { return ped * pedPrecision + minPed_; } + float decodeGain(unsigned int gain) const { return float(gain) * gainPrecision + minGain_; } + float decodePed(unsigned int ped) const { return float(ped) * pedPrecision + minPed_; } std::vector v_pedestals; //@@@ blob streaming doesn't work with uint16_t and with classes std::vector indexes; diff --git a/CondFormats/SiPixelObjects/interface/SiPixelGainForHLTonGPU.h b/CondFormats/SiPixelObjects/interface/SiPixelGainForHLTonGPU.h index aa5a127927b90..79581776dc1f9 100644 --- a/CondFormats/SiPixelObjects/interface/SiPixelGainForHLTonGPU.h +++ b/CondFormats/SiPixelObjects/interface/SiPixelGainForHLTonGPU.h @@ -56,8 +56,8 @@ class SiPixelGainForHLTonGPU { return std::make_pair(decodePed(s.ped & 0xFF), decodeGain(s.gain & 0xFF)); } - constexpr float decodeGain(unsigned int gain) const { return gain * gainPrecision_ + minGain_; } - constexpr float decodePed(unsigned int ped) const { return ped * pedPrecision_ + minPed_; } + constexpr float decodeGain(unsigned int gain) const { return float(gain) * gainPrecision_ + minGain_; } + constexpr float decodePed(unsigned int ped) const { return float(ped) * pedPrecision_ + minPed_; } DecodingStructure* v_pedestals_; std::pair rangeAndCols_[gpuClustering::maxNumModules]; diff --git a/CondFormats/SiPixelObjects/test/FastSiPixelFEDChannelContainerFromQuality.cc b/CondFormats/SiPixelObjects/test/FastSiPixelFEDChannelContainerFromQuality.cc index 42b54677f424b..2e29e68fde135 100644 --- a/CondFormats/SiPixelObjects/test/FastSiPixelFEDChannelContainerFromQuality.cc +++ b/CondFormats/SiPixelObjects/test/FastSiPixelFEDChannelContainerFromQuality.cc @@ -24,8 +24,6 @@ #include "CondFormats/SiPixelObjects/interface/SiPixelFedCablingMap.h" #include "CondFormats/SiPixelObjects/interface/SiPixelFedCablingTree.h" #include "CondFormats/SiPixelObjects/interface/SiPixelQuality.h" -#include "FWCore/Framework/interface/EDAnalyzer.h" -#include "FWCore/Framework/interface/ESHandle.h" #include "FWCore/Framework/interface/ESWatcher.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/Frameworkfwd.h" @@ -420,10 +418,10 @@ void FastSiPixelFEDChannelContainerFromQuality::endJob() { cond::Time_t valid_time = poolDbService->currentTime(); // this writes the payload to begin in current run defined in cfg if (!isMC_) { - poolDbService->writeOne(myQualities, valid_time, m_record); + poolDbService->writeOneIOV(*myQualities, valid_time, m_record); } else { // for MC IOV since=1 - poolDbService->writeOne(myQualities, 1, m_record); + poolDbService->writeOneIOV(*myQualities, 1, m_record); } } } diff --git a/CondFormats/SiPixelObjects/test/SiPixelBadFEDChannelSimulationSanityChecker.cc b/CondFormats/SiPixelObjects/test/SiPixelBadFEDChannelSimulationSanityChecker.cc index 557b26fe0bc2a..ce36a6b0988a7 100644 --- a/CondFormats/SiPixelObjects/test/SiPixelBadFEDChannelSimulationSanityChecker.cc +++ b/CondFormats/SiPixelObjects/test/SiPixelBadFEDChannelSimulationSanityChecker.cc @@ -26,11 +26,15 @@ class SiPixelBadFEDChannelSimulationSanityChecker : public edm::one::EDAnalyzer< virtual void analyze(const edm::Event& e, const edm::EventSetup& c) override; // ----------member data --------------------------- + const edm::ESGetToken siPixelBadFEDChToken_; + const edm::ESGetToken siPixelQPToken_; const bool printdebug_; }; SiPixelBadFEDChannelSimulationSanityChecker::SiPixelBadFEDChannelSimulationSanityChecker(edm::ParameterSet const& p) - : printdebug_(p.getUntrackedParameter("printDebug", true)) { + : siPixelBadFEDChToken_(esConsumes()), + siPixelQPToken_(esConsumes()), + printdebug_(p.getUntrackedParameter("printDebug", true)) { edm::LogInfo("SiPixelBadFEDChannelSimulationSanityChecker") << "SiPixelBadFEDChannelSimulationSanityChecker" << std::endl; } @@ -55,9 +59,7 @@ void SiPixelBadFEDChannelSimulationSanityChecker::analyze(const edm::Event& e, c } //this part gets the handle of the event source and the record (i.e. the Database) - edm::ESHandle qualityCollectionHandle; - context.get().get(qualityCollectionHandle); - const SiPixelFEDChannelContainer* quality_map = qualityCollectionHandle.product(); + const SiPixelFEDChannelContainer* quality_map = &context.getData(siPixelBadFEDChToken_); edm::eventsetup::EventSetupRecordKey recordKey2( edm::eventsetup::EventSetupRecordKey::TypeTag::findType("SiPixelStatusScenarioProbabilityRcd>")); @@ -69,9 +71,7 @@ void SiPixelBadFEDChannelSimulationSanityChecker::analyze(const edm::Event& e, c } //this part gets the handle of the event source and the record (i.e. the Database) - edm::ESHandle scenarioProbabilityHandle; - context.get().get(scenarioProbabilityHandle); - const SiPixelQualityProbabilities* myProbabilities = scenarioProbabilityHandle.product(); + const SiPixelQualityProbabilities* myProbabilities = &context.getData(siPixelQPToken_); SiPixelFEDChannelContainer::SiPixelBadFEDChannelsScenarioMap m_qualities = quality_map->getScenarioMap(); SiPixelQualityProbabilities::probabilityMap m_probabilities = myProbabilities->getProbability_Map(); diff --git a/CondFormats/SiPixelObjects/test/SiPixelFEDChannelContainerFromQualityConverter.cc b/CondFormats/SiPixelObjects/test/SiPixelFEDChannelContainerFromQualityConverter.cc index c2e1335f1305d..dee1a2897e48b 100644 --- a/CondFormats/SiPixelObjects/test/SiPixelFEDChannelContainerFromQualityConverter.cc +++ b/CondFormats/SiPixelObjects/test/SiPixelFEDChannelContainerFromQualityConverter.cc @@ -53,6 +53,9 @@ class SiPixelFEDChannelContainerFromQualityConverter : public edm::one::EDAnalyz virtual void endJob() override; // ----------member data --------------------------- + const edm::ESGetToken siPixelQualityToken_; + const edm::ESGetToken siPixelCablingToken_; + const std::string m_record; const bool printdebug_; const bool isMC_; @@ -68,7 +71,9 @@ class SiPixelFEDChannelContainerFromQualityConverter : public edm::one::EDAnalyz // SiPixelFEDChannelContainerFromQualityConverter::SiPixelFEDChannelContainerFromQualityConverter( const edm::ParameterSet& iConfig) - : m_record(iConfig.getParameter("record")), + : siPixelQualityToken_(esConsumes()), + siPixelCablingToken_(esConsumes()), + m_record(iConfig.getParameter("record")), printdebug_(iConfig.getUntrackedParameter("printDebug", false)), isMC_(iConfig.getUntrackedParameter("isMC", true)), removeEmptyPayloads_(iConfig.getUntrackedParameter("removeEmptyPayloads", false)) { @@ -95,11 +100,8 @@ void SiPixelFEDChannelContainerFromQualityConverter::analyze(const edm::Event& i if (hasQualityIOV) { //Retrieve the strip quality from conditions - edm::ESHandle siPixelQuality_; - iSetup.get().get(siPixelQuality_); - - edm::ESHandle cablingMapHandle; - iSetup.get().get(cablingMapHandle); + edm::ESHandle siPixelQuality_ = iSetup.getHandle(siPixelQualityToken_); + edm::ESHandle cablingMapHandle = iSetup.getHandle(siPixelCablingToken_); std::string scenario = std::to_string(RunNumber_) + "_" + std::to_string(LuminosityBlockNumber_); @@ -226,10 +228,10 @@ void SiPixelFEDChannelContainerFromQualityConverter::endJob() { cond::Time_t valid_time = poolDbService->currentTime(); // this writes the payload to begin in current run defined in cfg if (!isMC_) { - poolDbService->writeOne(myQualities, valid_time, m_record); + poolDbService->writeOneIOV(*myQualities, valid_time, m_record); } else { // for MC IOV since=1 - poolDbService->writeOne(myQualities, 1, m_record); + poolDbService->writeOneIOV(*myQualities, 1, m_record); } } } diff --git a/CondFormats/SiPixelObjects/test/SiPixelFEDChannelContainerTestReader.cc b/CondFormats/SiPixelObjects/test/SiPixelFEDChannelContainerTestReader.cc index 6a551c8654f0a..d411593877021 100644 --- a/CondFormats/SiPixelObjects/test/SiPixelFEDChannelContainerTestReader.cc +++ b/CondFormats/SiPixelObjects/test/SiPixelFEDChannelContainerTestReader.cc @@ -24,12 +24,14 @@ class SiPixelFEDChannelContainerTestReader : public edm::one::EDAnalyzer<> { virtual void analyze(const edm::Event& e, const edm::EventSetup& c) override; // ----------member data --------------------------- + const edm::ESGetToken siPixelBadFEDChToken_; const bool printdebug_; const std::string formatedOutput_; }; SiPixelFEDChannelContainerTestReader::SiPixelFEDChannelContainerTestReader(edm::ParameterSet const& p) - : printdebug_(p.getUntrackedParameter("printDebug", true)), + : siPixelBadFEDChToken_(esConsumes()), + printdebug_(p.getUntrackedParameter("printDebug", true)), formatedOutput_(p.getUntrackedParameter("outputFile", "")) { edm::LogInfo("SiPixelFEDChannelContainerTestReader") << "SiPixelFEDChannelContainerTestReader" << std::endl; } @@ -54,11 +56,8 @@ void SiPixelFEDChannelContainerTestReader::analyze(const edm::Event& e, const ed } //this part gets the handle of the event source and the record (i.e. the Database) - edm::ESHandle qualityCollectionHandle; - edm::LogInfo("SiPixelFEDChannelContainerTestReader") << "got eshandle" << std::endl; - - context.get().get(qualityCollectionHandle); - edm::LogInfo("SiPixelFEDChannelContainerTestReader") << "got context" << std::endl; + edm::ESHandle qualityCollectionHandle = context.getHandle(siPixelBadFEDChToken_); + edm::LogInfo("SiPixelFEDChannelContainerTestReader") << "got eshandle from context" << std::endl; const SiPixelFEDChannelContainer* quality_map = qualityCollectionHandle.product(); edm::LogInfo("SiPixelFEDChannelContainerTestReader") << "got SiPixelFEDChannelContainer* " << std::endl; diff --git a/CondFormats/SiPixelObjects/test/SiPixelFEDChannelContainerWriteFromASCII.cc b/CondFormats/SiPixelObjects/test/SiPixelFEDChannelContainerWriteFromASCII.cc index 21faa33345328..85fd16e73d8c1 100644 --- a/CondFormats/SiPixelObjects/test/SiPixelFEDChannelContainerWriteFromASCII.cc +++ b/CondFormats/SiPixelObjects/test/SiPixelFEDChannelContainerWriteFromASCII.cc @@ -153,7 +153,7 @@ void SiPixelFEDChannelContainerWriteFromASCII::endJob() { if (poolDbService.isAvailable()) { cond::Time_t valid_time = poolDbService->currentTime(); // this writes the payload to begin in current run defined in cfg - poolDbService->writeOne(myQualities, valid_time, m_record); + poolDbService->writeOneIOV(*myQualities, valid_time, m_record); } } diff --git a/CondFormats/SiPixelObjects/test/SiPixelFedCablingMapAnalyzer.cc b/CondFormats/SiPixelObjects/test/SiPixelFedCablingMapAnalyzer.cc index 37f807f47b81d..902038d8c0940 100644 --- a/CondFormats/SiPixelObjects/test/SiPixelFedCablingMapAnalyzer.cc +++ b/CondFormats/SiPixelObjects/test/SiPixelFedCablingMapAnalyzer.cc @@ -1,6 +1,6 @@ //#include -#include "FWCore/Framework/interface/EDAnalyzer.h" +#include "FWCore/Framework/interface/one/EDAnalyzer.h" #include "FWCore/Framework/interface/EventSetup.h" #include "FWCore/Framework/interface/ESHandle.h" @@ -17,27 +17,27 @@ using namespace edm; using namespace sipixelobjects; // class declaration -class SiPixelFedCablingMapAnalyzer : public edm::EDAnalyzer { +class SiPixelFedCablingMapAnalyzer : public edm::one::EDAnalyzer<> { public: - explicit SiPixelFedCablingMapAnalyzer(const edm::ParameterSet&) {} + explicit SiPixelFedCablingMapAnalyzer(const edm::ParameterSet&) : fedCablingToken_(esConsumes()) {} ~SiPixelFedCablingMapAnalyzer(); virtual void analyze(const edm::Event&, const edm::EventSetup&); private: + edm::ESGetToken fedCablingToken_; }; -SiPixelFedCablingMapAnalyzer::~SiPixelFedCablingMapAnalyzer() {} +SiPixelFedCablingMapAnalyzer::~SiPixelFedCablingMapAnalyzer() = default; void SiPixelFedCablingMapAnalyzer::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) { - std::cout << "====== SiPixelFedCablingMapAnalyzer" << std::endl; + LogPrint("SiPixelFedCablingMapAnalyzer") << "====== SiPixelFedCablingMapAnalyzer" << std::endl; - edm::ESHandle map; - iSetup.get().get(map); + const SiPixelFedCablingMap* map = &iSetup.getData(fedCablingToken_); LogInfo(" got map, version: ") << map->version(); auto tree = map->cablingTree(); - LogInfo("PRINT MAP:") << tree->print(100); - LogInfo("PRINT MAP, end:"); + LogInfo("SiPixelFedCablingMapAnalyzer") << "PRINT MAP:" << tree->print(100); + LogInfo("SiPixelFedCablingMapAnalyzer") << "PRINT MAP, end:"; } //define this as a plug-in diff --git a/CondFormats/SiPixelObjects/test/SiPixelQualityProbabilitiesTestReader.cc b/CondFormats/SiPixelObjects/test/SiPixelQualityProbabilitiesTestReader.cc index 08af6781f5a59..ba229d0736b60 100644 --- a/CondFormats/SiPixelObjects/test/SiPixelQualityProbabilitiesTestReader.cc +++ b/CondFormats/SiPixelObjects/test/SiPixelQualityProbabilitiesTestReader.cc @@ -22,12 +22,14 @@ class SiPixelQualityProbabilitiesTestReader : public edm::one::EDAnalyzer<> { virtual void analyze(const edm::Event& e, const edm::EventSetup& c) override; // ----------member data --------------------------- + const edm::ESGetToken siPixelQPToken_; const bool printdebug_; const std::string formatedOutput_; }; SiPixelQualityProbabilitiesTestReader::SiPixelQualityProbabilitiesTestReader(edm::ParameterSet const& p) - : printdebug_(p.getUntrackedParameter("printDebug", true)), + : siPixelQPToken_(esConsumes()), + printdebug_(p.getUntrackedParameter("printDebug", true)), formatedOutput_(p.getUntrackedParameter("outputFile", "")) { edm::LogInfo("SiPixelQualityProbabilitiesTestReader") << "SiPixelQualityProbabilitiesTestReader" << std::endl; } @@ -52,11 +54,8 @@ void SiPixelQualityProbabilitiesTestReader::analyze(const edm::Event& e, const e } //this part gets the handle of the event source and the record (i.e. the Database) - edm::ESHandle scenarioProbabilityHandle; - edm::LogInfo("SiPixelQualityProbabilitiesTestReader") << "got eshandle" << std::endl; - - context.get().get(scenarioProbabilityHandle); - edm::LogInfo("SiPixelQualityProbabilitiesTestReader") << "got context" << std::endl; + edm::ESHandle scenarioProbabilityHandle = context.getHandle(siPixelQPToken_); + edm::LogInfo("SiPixelQualityProbabilitiesTestReader") << "got eshandle from context" << std::endl; const SiPixelQualityProbabilities* myProbabilities = scenarioProbabilityHandle.product(); edm::LogInfo("SiPixelQualityProbabilitiesTestReader") << "got SiPixelQualityProbabilities* " << std::endl; diff --git a/CondFormats/SiPixelObjects/test/SiPixelQualityProbabilitiesTestWriter.cc b/CondFormats/SiPixelObjects/test/SiPixelQualityProbabilitiesTestWriter.cc index d11081195f883..a658b8c2296f5 100644 --- a/CondFormats/SiPixelObjects/test/SiPixelQualityProbabilitiesTestWriter.cc +++ b/CondFormats/SiPixelObjects/test/SiPixelQualityProbabilitiesTestWriter.cc @@ -136,7 +136,7 @@ void SiPixelQualityProbabilitiesTestWriter::endJob() { if (poolDbService.isAvailable()) { cond::Time_t valid_time = poolDbService->currentTime(); // this writes the payload to begin in current run defined in cfg - poolDbService->writeOne(myProbabilities, valid_time, m_record); + poolDbService->writeOneIOV(*myProbabilities, valid_time, m_record); } } diff --git a/CondFormats/SiPixelObjects/test/SiPixelQualityProbabilitiesWriteFromASCII.cc b/CondFormats/SiPixelObjects/test/SiPixelQualityProbabilitiesWriteFromASCII.cc index ee50ac5ab35e2..408ce03785691 100644 --- a/CondFormats/SiPixelObjects/test/SiPixelQualityProbabilitiesWriteFromASCII.cc +++ b/CondFormats/SiPixelObjects/test/SiPixelQualityProbabilitiesWriteFromASCII.cc @@ -127,7 +127,7 @@ void SiPixelQualityProbabilitiesWriteFromASCII::endJob() { if (poolDbService.isAvailable()) { cond::Time_t valid_time = poolDbService->currentTime(); // this writes the payload to begin in current run defined in cfg - poolDbService->writeOne(myProbabilities, valid_time, m_record); + poolDbService->writeOneIOV(*myProbabilities, valid_time, m_record); } } diff --git a/CondFormats/SiPixelObjects/test/SiPixelTestSummary.cc b/CondFormats/SiPixelObjects/test/SiPixelTestSummary.cc index 710d7815c82be..f22a8052fcbba 100644 --- a/CondFormats/SiPixelObjects/test/SiPixelTestSummary.cc +++ b/CondFormats/SiPixelObjects/test/SiPixelTestSummary.cc @@ -2,7 +2,7 @@ #include -#include "FWCore/Framework/interface/EDAnalyzer.h" +#include "FWCore/Framework/interface/one/EDAnalyzer.h" #include "FWCore/Framework/interface/EventSetup.h" #include "FWCore/Framework/interface/ESHandle.h" @@ -20,17 +20,18 @@ using std::string; using namespace std; // ---------------------------------------------------------------------- -class SiPixelTestSummary : public edm::EDAnalyzer { +class SiPixelTestSummary : public edm::one::EDAnalyzer<> { public: - explicit SiPixelTestSummary(const edm::ParameterSet&) {} + explicit SiPixelTestSummary(const edm::ParameterSet&) : geomToken_(esConsumes()) {} ~SiPixelTestSummary(); virtual void analyze(const edm::Event&, const edm::EventSetup&); private: + edm::ESGetToken geomToken_; }; // ---------------------------------------------------------------------- -SiPixelTestSummary::~SiPixelTestSummary() {} +SiPixelTestSummary::~SiPixelTestSummary() = default; // ---------------------------------------------------------------------- void SiPixelTestSummary::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) { @@ -38,8 +39,7 @@ void SiPixelTestSummary::analyze(const edm::Event& iEvent, const edm::EventSetup SiPixelDetSummary a(1); - edm::ESHandle pDD; - iSetup.get().get(pDD); + const TrackerGeometry* pDD = &iSetup.getData(geomToken_); cout << "**********************************************************************" << endl; cout << " *** Geometry node for TrackerGeom is " << &(*pDD) << std::endl; diff --git a/CondTools/BTau/plugins/BTagCalibrationDbCreator.cc b/CondTools/BTau/plugins/BTagCalibrationDbCreator.cc index 3d61b70de13e1..db78618adf47c 100644 --- a/CondTools/BTau/plugins/BTagCalibrationDbCreator.cc +++ b/CondTools/BTau/plugins/BTagCalibrationDbCreator.cc @@ -3,7 +3,7 @@ #include #include #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" @@ -11,7 +11,7 @@ #include "CondCore/DBOutputService/interface/PoolDBOutputService.h" #include "CondFormats/BTauObjects/interface/BTagCalibration.h" -class BTagCalibrationDbCreator : public edm::EDAnalyzer { +class BTagCalibrationDbCreator : public edm::one::EDAnalyzer<> { public: BTagCalibrationDbCreator(const edm::ParameterSet&); void beginJob() override; @@ -29,7 +29,7 @@ BTagCalibrationDbCreator::BTagCalibrationDbCreator(const edm::ParameterSet& p) tagger_(p.getUntrackedParameter("tagger")) {} void BTagCalibrationDbCreator::beginJob() { - auto calib = new BTagCalibration(tagger_, csvFile_); + auto calib = new BTagCalibration(tagger_, csvFile_, true); edm::Service s; if (s.isAvailable()) { if (s->isNewTagRequest(tagger_)) { diff --git a/CondTools/BTau/test/testBTagCalibrationReader.cpp b/CondTools/BTau/test/testBTagCalibrationReader.cpp index 4547874c2da03..2877c3e537c75 100644 --- a/CondTools/BTau/test/testBTagCalibrationReader.cpp +++ b/CondTools/BTau/test/testBTagCalibrationReader.cpp @@ -28,7 +28,7 @@ int main() { "1, test, down, 1, -2, 2, 50, 500, 0, 999, \"1.9*x\" \n"); stringstream csv1Stream(csv1); BTagCalibration bc1("csv"); - bc1.readCSV(csv1Stream); + bc1.readCSV(csv1Stream, true); // test pt-dependent function BTagCalibrationReader bcr1(BTagEntry::OP_LOOSE); diff --git a/CondTools/BeamSpot/plugins/BeamSpotOnlineRecordsWriter.cc b/CondTools/BeamSpot/plugins/BeamSpotOnlineRecordsWriter.cc index fc1ce7ae22792..21ef983d8b767 100644 --- a/CondTools/BeamSpot/plugins/BeamSpotOnlineRecordsWriter.cc +++ b/CondTools/BeamSpot/plugins/BeamSpotOnlineRecordsWriter.cc @@ -21,6 +21,7 @@ #include #include #include +#include // user include files #include "FWCore/Framework/interface/Frameworkfwd.h" @@ -108,10 +109,11 @@ void BeamSpotOnlineRecordsWriter::endJob() { double cov[7][7]; int type, lastAnalyzedLumi, firstAnalyzedLumi, lastAnalyzedRun, lastAnalyzedFill; std::string tag; + std::time_t lumiRangeBeginTime, lumiRangeEndTime; fasciiFile >> tag >> lastAnalyzedRun; - fasciiFile >> tag >> tag >> tag >> tag >> tag; // BeginTimeOfFit parsing (not used in payload) - fasciiFile >> tag >> tag >> tag >> tag >> tag; // EndTimeOfFit parsing (not used in payload) + fasciiFile >> tag >> tag >> tag >> tag >> lumiRangeBeginTime; // BeginTimeOfFit parsing (not used in payload) + fasciiFile >> tag >> tag >> tag >> tag >> lumiRangeEndTime; // EndTimeOfFit parsing (not used in payload) fasciiFile >> tag >> firstAnalyzedLumi; fasciiFile >> tag >> lastAnalyzedLumi; fasciiFile >> tag >> type; @@ -136,11 +138,20 @@ void BeamSpotOnlineRecordsWriter::endJob() { lastAnalyzedFill = -999; + // Verify that the parsing was correct by checking the BS positions + if (std::fabs(x) > 1000. || std::fabs(x) < 1.e-20 || std::fabs(y) > 1000. || std::fabs(y) < 1.e-20 || + std::fabs(z) > 1000. || std::fabs(z) < 1.e-20) { + throw edm::Exception(edm::errors::Unknown) + << " !!! Error in parsing input file, parsed BS (x,y,z): (" << x << "," << y << "," << z << ") !!!"; + } + edm::LogPrint("BeamSpotOnlineRecordsWriter") << "---- Parsed these parameters from input txt file ----"; edm::LogPrint("BeamSpotOnlineRecordsWriter") << " lastAnalyzedRun : " << lastAnalyzedRun; edm::LogPrint("BeamSpotOnlineRecordsWriter") << " lastAnalyzedFill : " << lastAnalyzedFill; edm::LogPrint("BeamSpotOnlineRecordsWriter") << " firstAnalyzedLumi : " << firstAnalyzedLumi; edm::LogPrint("BeamSpotOnlineRecordsWriter") << " lastAnalyzedLumi : " << lastAnalyzedLumi; + edm::LogPrint("BeamSpotOnlineRecordsWriter") << " lumiRangeBeginTime: " << lumiRangeBeginTime; + edm::LogPrint("BeamSpotOnlineRecordsWriter") << " lumiRangeEndTime : " << lumiRangeEndTime; edm::LogPrint("BeamSpotOnlineRecordsWriter") << " type : " << type; edm::LogPrint("BeamSpotOnlineRecordsWriter") << " x : " << x; edm::LogPrint("BeamSpotOnlineRecordsWriter") << " y : " << y; @@ -181,6 +192,8 @@ void BeamSpotOnlineRecordsWriter::endJob() { abeam->SetLastAnalyzedLumi(lastAnalyzedLumi); abeam->SetLastAnalyzedRun(lastAnalyzedRun); abeam->SetLastAnalyzedFill(lastAnalyzedFill); + abeam->SetStartTimeStamp(lumiRangeBeginTime); + abeam->SetEndTimeStamp(lumiRangeEndTime); abeam->SetType(type); abeam->SetPosition(x, y, z); abeam->SetSigmaZ(sigmaZ); @@ -198,6 +211,11 @@ void BeamSpotOnlineRecordsWriter::endJob() { } } + // Set the creation time of the payload to the current time + auto creationTime = + std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); + abeam->SetCreationTime(creationTime); + edm::LogPrint("BeamSpotOnlineRecordsWriter") << " Writing results to DB..."; edm::Service poolDbService; @@ -207,17 +225,16 @@ void BeamSpotOnlineRecordsWriter::endJob() { edm::LogPrint("BeamSpotOnlineRecordsWriter") << "new tag requested"; if (fuseNewSince) { edm::LogPrint("BeamSpotOnlineRecordsWriter") << "Using a new Since: " << fnewSince; - poolDbService->createNewIOV(abeam.get(), fnewSince, poolDbService->endOfTime(), fLabel); + poolDbService->createOneIOV(*abeam, fnewSince, fLabel); } else - poolDbService->createNewIOV( - abeam.get(), poolDbService->beginOfTime(), poolDbService->endOfTime(), fLabel); + poolDbService->createOneIOV(*abeam, poolDbService->beginOfTime(), fLabel); } else { edm::LogPrint("BeamSpotOnlineRecordsWriter") << "no new tag requested"; if (fuseNewSince) { edm::LogPrint("BeamSpotOnlineRecordsWriter") << "Using a new Since: " << fnewSince; - poolDbService->appendSinceTime(abeam.get(), fnewSince, fLabel); + poolDbService->appendOneIOV(*abeam, fnewSince, fLabel); } else - poolDbService->appendSinceTime(abeam.get(), poolDbService->currentTime(), fLabel); + poolDbService->appendOneIOV(*abeam, poolDbService->currentTime(), fLabel); } } edm::LogPrint("BeamSpotOnlineRecordsWriter") << "[BeamSpotOnlineRecordsWriter] endJob done \n"; diff --git a/CondTools/BeamSpot/test/BeamSpotOnlineRecordsReader_cfg.py b/CondTools/BeamSpot/test/BeamSpotOnlineRecordsReader_cfg.py index d549181331302..85dfa50a14aa9 100644 --- a/CondTools/BeamSpot/test/BeamSpotOnlineRecordsReader_cfg.py +++ b/CondTools/BeamSpot/test/BeamSpotOnlineRecordsReader_cfg.py @@ -78,7 +78,7 @@ tag_name = options.inputTag from CondCore.CondDB.CondDB_cfi import * -CondDBBeamSpotOnlineLegacy = CondDB.clone(connect = cms.string("sqlite_file:test.db")) # customize with input db file +CondDBBeamSpotOnlineLegacy = CondDB.clone(connect = cms.string("sqlite_file:test_%s.db" % tag_name)) # customize with input db file process.PoolDBESSource = cms.ESSource("PoolDBESSource", CondDBBeamSpotOnlineLegacy, DumpStat=cms.untracked.bool(True), diff --git a/CondTools/BeamSpot/test/BeamSpotOnlineRecordsWriter_cfg.py b/CondTools/BeamSpot/test/BeamSpotOnlineRecordsWriter_cfg.py index 08fd2be1d6f2a..0c3a528aae176 100644 --- a/CondTools/BeamSpot/test/BeamSpotOnlineRecordsWriter_cfg.py +++ b/CondTools/BeamSpot/test/BeamSpotOnlineRecordsWriter_cfg.py @@ -51,7 +51,7 @@ ################################# # Produce a SQLITE FILE ################################# -CondDBBeamSpotObjects = CondDB.clone(connect = cms.string('sqlite_file:test.db')) # choose an output name +CondDBBeamSpotObjects = CondDB.clone(connect = cms.string('sqlite_file:test_%s.db' % tag_name)) # choose an output name process.PoolDBOutputService = cms.Service("PoolDBOutputService", CondDBBeamSpotObjects, timetype = cms.untracked.string('lumiid'), #('lumiid'), #('runnumber') diff --git a/CondTools/BeamSpot/test/testReadWriteOnlineBSFromDB.sh b/CondTools/BeamSpot/test/testReadWriteOnlineBSFromDB.sh index e30956b591f4e..0ae82bd5977e3 100755 --- a/CondTools/BeamSpot/test/testReadWriteOnlineBSFromDB.sh +++ b/CondTools/BeamSpot/test/testReadWriteOnlineBSFromDB.sh @@ -4,26 +4,30 @@ function die { echo $1: status $2 ; exit $2; } echo "TESTING BeamSpotOnline From DB Read / Write codes ..." -## clean the input db file -if test -f "test.db"; then - rm -fr test.db +## clean the input db files +if test -f "test_BSHLT_tag.db"; then + rm -fr test_BSHLT_tag.db +fi + +if test -f "test_BSLegacy_tag.db"; then + rm -fr test_BSLegacy_tag.db fi ## copy the input file cp -pr $CMSSW_BASE/src/CondTools/BeamSpot/data/BeamFitResults_Run306171.txt . # test write -echo "TESTING Writing BeamSpotOnlineLegacyObjectsRcd DB object ...\n\n" +printf "TESTING Writing BeamSpotOnlineLegacyObjectsRcd DB object ...\n\n" cmsRun ${LOCAL_TEST_DIR}/BeamSpotOnlineRecordsWriter_cfg.py unitTest=True inputRecord=BeamSpotOnlineLegacyObjectsRcd || die "Failure writing payload for BeamSpotOnlineLegacyObjectsRcd" $? -echo "TESTING Writing BeamSpotOnlineHLTObjectsRcd DB object ...\n\n" +printf "TESTING Writing BeamSpotOnlineHLTObjectsRcd DB object ...\n\n" cmsRun ${LOCAL_TEST_DIR}/BeamSpotOnlineRecordsWriter_cfg.py unitTest=True inputRecord=BeamSpotOnlineHLTObjectsRcd || die "Failure writing payload for BeamSpotOnlineHLTObjectsRcd" $? # test read -echo "TESTING Reading BeamSpotOnlineLegacyObjectsRcd DB object ...\n\n" +printf "TESTING Reading BeamSpotOnlineLegacyObjectsRcd DB object ...\n\n" cmsRun ${LOCAL_TEST_DIR}/BeamSpotOnlineRecordsReader_cfg.py unitTest=True inputRecord=BeamSpotOnlineLegacyObjectsRcd || die "Failure reading payload for BeamSpotOnlineLegacyObjectsRcd" $? -echo "TESTING Reading BeamSpotOnlineHLTObjectsRcd DB object ...\n\n" +printf "TESTING Reading BeamSpotOnlineHLTObjectsRcd DB object ...\n\n" cmsRun ${LOCAL_TEST_DIR}/BeamSpotOnlineRecordsReader_cfg.py unitTest=True inputRecord=BeamSpotOnlineHLTObjectsRcd || die "Failure reading payload for BeamSpotOnlineHLTObjectsRcd" $? echo "TESTING reading BeamSpotObjectRcd DB object ...\n\n" diff --git a/CondTools/CTPPS/plugins/PPSTimingCalibrationWriter.cc b/CondTools/CTPPS/plugins/PPSTimingCalibrationWriter.cc index e288a828a5594..23fecd626a25a 100644 --- a/CondTools/CTPPS/plugins/PPSTimingCalibrationWriter.cc +++ b/CondTools/CTPPS/plugins/PPSTimingCalibrationWriter.cc @@ -43,7 +43,7 @@ void PPSTimingCalibrationWriter::analyze(const edm::Event& iEvent, const edm::Ev // store the calibration into a DB object edm::Service poolDbService; if (poolDbService.isAvailable()) - poolDbService->writeOne(hTimingCalib.product(), poolDbService->currentTime(), "PPSTimingCalibrationRcd"); + poolDbService->writeOneIOV(*hTimingCalib.product(), poolDbService->currentTime(), "PPSTimingCalibrationRcd"); else throw cms::Exception("PPSTimingCalibrationWriter") << "PoolDBService required."; } diff --git a/CondTools/CTPPS/plugins/RetrieveCTPPSRPAlignmentCorrectionsData.cc b/CondTools/CTPPS/plugins/RetrieveCTPPSRPAlignmentCorrectionsData.cc new file mode 100644 index 0000000000000..d039391e5a9f5 --- /dev/null +++ b/CondTools/CTPPS/plugins/RetrieveCTPPSRPAlignmentCorrectionsData.cc @@ -0,0 +1,43 @@ +/**************************************************************************** +* Author: +* Mateusz Kocot (mateuszkocot99@gmail.com) +****************************************************************************/ + +#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/ESHandle.h" +#include "FWCore/Framework/interface/MakerMacros.h" + +#include "FWCore/MessageLogger/interface/MessageLogger.h" +#include "FWCore/ParameterSet/interface/ParameterSet.h" +#include "FWCore/ServiceRegistry/interface/Service.h" + +#include "CondFormats/PPSObjects/interface/CTPPSRPAlignmentCorrectionsData.h" +#include "CondFormats/DataRecord/interface/CTPPSRPAlignmentCorrectionsDataRcd.h" + +#include + +class RetrieveCTPPSRPAlignmentCorrectionsData : public edm::one::EDAnalyzer<> { +public: + explicit RetrieveCTPPSRPAlignmentCorrectionsData(const edm::ParameterSet &); + +private: + void analyze(const edm::Event &, const edm::EventSetup &) override; + + edm::ESGetToken esToken_; +}; + +RetrieveCTPPSRPAlignmentCorrectionsData::RetrieveCTPPSRPAlignmentCorrectionsData(const edm::ParameterSet &iConfig) + : esToken_(esConsumes()) {} + +void RetrieveCTPPSRPAlignmentCorrectionsData::analyze(const edm::Event &iEvent, const edm::EventSetup &iSetup) { + // get the data + const auto &ctppsRPAlignmentCorrectionsData = iSetup.getData(esToken_); + + edm::LogInfo("PPS") << ctppsRPAlignmentCorrectionsData; +} + +//define this as a plug-in +DEFINE_FWK_MODULE(RetrieveCTPPSRPAlignmentCorrectionsData); diff --git a/CondTools/CTPPS/plugins/WriteCTPPSBeamParameters.cc b/CondTools/CTPPS/plugins/WriteCTPPSBeamParameters.cc index e1420cec14328..5dec57bc9af9c 100644 --- a/CondTools/CTPPS/plugins/WriteCTPPSBeamParameters.cc +++ b/CondTools/CTPPS/plugins/WriteCTPPSBeamParameters.cc @@ -67,7 +67,7 @@ void WriteCTPPSBeamParameters::analyze(const edm::Event& iEvent, const edm::Even // Write to database or sqlite file edm::Service poolDbService; if (poolDbService.isAvailable()) - poolDbService->writeOne(p, ilumi, "CTPPSBeamParametersRcd"); + poolDbService->writeOneIOV(*p, ilumi, "CTPPSBeamParametersRcd"); // poolDbService->writeOne( p, poolDbService->currentTime(), "CTPPSBeamParametersRcd" ); else throw std::runtime_error("PoolDBService required."); diff --git a/CondTools/CTPPS/plugins/WritePPSAlignmentConfig.cc b/CondTools/CTPPS/plugins/WritePPSAlignmentConfig.cc index 84437bd4e3728..9ac076de64a31 100644 --- a/CondTools/CTPPS/plugins/WritePPSAlignmentConfig.cc +++ b/CondTools/CTPPS/plugins/WritePPSAlignmentConfig.cc @@ -41,7 +41,7 @@ void WritePPSAlignmentConfig::analyze(const edm::Event &iEvent, const edm::Event // store the data in a DB object edm::Service poolDbService; if (poolDbService.isAvailable()) { - poolDbService->writeOne(&ppsAlignmentConfig, poolDbService->currentTime(), "PPSAlignmentConfigRcd"); + poolDbService->writeOneIOV(ppsAlignmentConfig, poolDbService->currentTime(), "PPSAlignmentConfigRcd"); } else { throw cms::Exception("WritePPSAlignmentConfig") << "PoolDBService required."; } diff --git a/CondTools/CTPPS/plugins/WritePPSAlignmentConfiguration.cc b/CondTools/CTPPS/plugins/WritePPSAlignmentConfiguration.cc index 387ec812d0bb6..e421583141902 100644 --- a/CondTools/CTPPS/plugins/WritePPSAlignmentConfiguration.cc +++ b/CondTools/CTPPS/plugins/WritePPSAlignmentConfiguration.cc @@ -41,7 +41,7 @@ void WritePPSAlignmentConfiguration::analyze(const edm::Event &iEvent, const edm // store the data in a DB object edm::Service poolDbService; if (poolDbService.isAvailable()) { - poolDbService->writeOne(&ppsAlignmentConfiguration, poolDbService->currentTime(), "PPSAlignmentConfigurationRcd"); + poolDbService->writeOneIOV(ppsAlignmentConfiguration, poolDbService->currentTime(), "PPSAlignmentConfigurationRcd"); } else { throw cms::Exception("WritePPSAlignmentConfiguration") << "PoolDBService required."; } diff --git a/CondTools/CTPPS/plugins/WritePPSAssociationCuts.cc b/CondTools/CTPPS/plugins/WritePPSAssociationCuts.cc index 97f0eb3d4bbe7..6d2dbe84b2409 100644 --- a/CondTools/CTPPS/plugins/WritePPSAssociationCuts.cc +++ b/CondTools/CTPPS/plugins/WritePPSAssociationCuts.cc @@ -41,7 +41,7 @@ void WritePPSAssociationCuts::analyze(const edm::Event &iEvent, const edm::Event // store the data in a DB object edm::Service poolDbService; if (poolDbService.isAvailable()) { - poolDbService->writeOne(&ppsAssociationCuts, poolDbService->currentTime(), "PPSAssociationCutsRcd"); + poolDbService->writeOneIOV(&ppsAssociationCuts, poolDbService->currentTime(), "PPSAssociationCutsRcd"); } else { throw cms::Exception("WritePPSAssociationCuts") << "PoolDBService required."; } diff --git a/CondTools/CTPPS/src/CTPPSRPAlignmentInfoAnalyzer.cc b/CondTools/CTPPS/src/CTPPSRPAlignmentInfoAnalyzer.cc index 58d1ccfd10533..42e2523224a40 100644 --- a/CondTools/CTPPS/src/CTPPSRPAlignmentInfoAnalyzer.cc +++ b/CondTools/CTPPS/src/CTPPSRPAlignmentInfoAnalyzer.cc @@ -85,7 +85,7 @@ void CTPPSRPAlignmentInfoAnalyzer::analyze(const edm::Event& iEvent, const edm:: const CTPPSRPAlignmentCorrectionsData* pCTPPSRPAlignmentCorrectionsData = alignments.product(); edm::Service poolDbService; if (poolDbService.isAvailable()) { - poolDbService->writeOne(pCTPPSRPAlignmentCorrectionsData, iov_, record_); + poolDbService->writeOneIOV(*pCTPPSRPAlignmentCorrectionsData, iov_, record_); } } diff --git a/CondTools/CTPPS/src/WriteCTPPSPixelAnalysisMask.cc b/CondTools/CTPPS/src/WriteCTPPSPixelAnalysisMask.cc index f8578b87620d6..3e89386c7a79a 100644 --- a/CondTools/CTPPS/src/WriteCTPPSPixelAnalysisMask.cc +++ b/CondTools/CTPPS/src/WriteCTPPSPixelAnalysisMask.cc @@ -73,7 +73,7 @@ void WriteCTPPSPixelAnalysisMask::analyze(const edm::Event &, edm::EventSetup co const CTPPSPixelAnalysisMask *pCTPPSPixelAnalysisMask = hAnalysisMask.product(); // Analysis Mask edm::Service poolDbService; if (poolDbService.isAvailable()) { - poolDbService->writeOne(pCTPPSPixelAnalysisMask, analysismaskiov_, /*m_record*/ record_); + poolDbService->writeOneIOV(*pCTPPSPixelAnalysisMask, analysismaskiov_, /*m_record*/ record_); } } diff --git a/CondTools/CTPPS/src/WriteCTPPSPixelDAQMapping.cc b/CondTools/CTPPS/src/WriteCTPPSPixelDAQMapping.cc index 7ea3187aac00c..2302605c4082d 100644 --- a/CondTools/CTPPS/src/WriteCTPPSPixelDAQMapping.cc +++ b/CondTools/CTPPS/src/WriteCTPPSPixelDAQMapping.cc @@ -72,7 +72,7 @@ void WriteCTPPSPixelDAQMapping::analyze(const edm::Event &, edm::EventSetup cons const CTPPSPixelDAQMapping *pCTPPSPixelDAQMapping = hMapping.product(); // DAQ Mapping edm::Service poolDbService; if (poolDbService.isAvailable()) { - poolDbService->writeOne(pCTPPSPixelDAQMapping, daqmappingiov_, /*m_record*/ record_); + poolDbService->writeOneIOV(*pCTPPSPixelDAQMapping, daqmappingiov_, /*m_record*/ record_); } } diff --git a/CondTools/CTPPS/test/BuildFile.xml b/CondTools/CTPPS/test/BuildFile.xml new file mode 100644 index 0000000000000..2e95cb4d6b8fe --- /dev/null +++ b/CondTools/CTPPS/test/BuildFile.xml @@ -0,0 +1 @@ + diff --git a/CondTools/CTPPS/test/test_CondToolsCTPPS.sh b/CondTools/CTPPS/test/test_CondToolsCTPPS.sh new file mode 100755 index 0000000000000..f7d93515a1a67 --- /dev/null +++ b/CondTools/CTPPS/test/test_CondToolsCTPPS.sh @@ -0,0 +1,5 @@ + #!/bin/bash -ex +TEST_DIR=$CMSSW_BASE/src/CondTools/CTPPS/test +echo "test dir: $TEST_DIR" + +cmsRun ${TEST_DIR}/write_PPSAssociationCuts_cfg.py diff --git a/CondTools/DT/test/dbgeom_dump.py b/CondTools/DT/test/dbgeom_dump.py index 628a2c68f87a1..c99fbd6c151f3 100644 --- a/CondTools/DT/test/dbgeom_dump.py +++ b/CondTools/DT/test/dbgeom_dump.py @@ -24,7 +24,7 @@ ) ) -process.muonGeometryConstants.fromDD4Hep = True +process.muonGeometryConstants.fromDD4hep = True process.DTGeometryESModule.applyAlignment = cms.bool(False) process.DTGeometryESModule.fromDDD = cms.bool(True) process.DTGeometryESModule.fromDD4hep = cms.bool(False) diff --git a/CondTools/Ecal/plugins/EcalMustacheSCParametersMaker.cc b/CondTools/Ecal/plugins/EcalMustacheSCParametersMaker.cc index fee8c7e863877..3346adcb54232 100644 --- a/CondTools/Ecal/plugins/EcalMustacheSCParametersMaker.cc +++ b/CondTools/Ecal/plugins/EcalMustacheSCParametersMaker.cc @@ -54,7 +54,7 @@ void EcalMustacheSCParametersMaker::analyze(const edm::Event& iEvent, const edm: edm::Service poolDbService; if (poolDbService.isAvailable()) { - poolDbService->writeOne(esParamsHandle_.product(), poolDbService->currentTime(), "EcalMustacheSCParametersRcd"); + poolDbService->writeOneIOV(*esParamsHandle_.product(), poolDbService->currentTime(), "EcalMustacheSCParametersRcd"); } else { throw cms::Exception("PoolDBService") << "No PoolDBService available."; } diff --git a/CondTools/Ecal/plugins/EcalSCDynamicDPhiParametersMaker.cc b/CondTools/Ecal/plugins/EcalSCDynamicDPhiParametersMaker.cc index e5e6fb0521196..96d3feecdbe21 100644 --- a/CondTools/Ecal/plugins/EcalSCDynamicDPhiParametersMaker.cc +++ b/CondTools/Ecal/plugins/EcalSCDynamicDPhiParametersMaker.cc @@ -54,7 +54,8 @@ void EcalSCDynamicDPhiParametersMaker::analyze(const edm::Event& iEvent, const e edm::Service poolDbService; if (poolDbService.isAvailable()) { - poolDbService->writeOne(esParamsHandle_.product(), poolDbService->currentTime(), "EcalSCDynamicDPhiParametersRcd"); + poolDbService->writeOneIOV( + *esParamsHandle_.product(), poolDbService->currentTime(), "EcalSCDynamicDPhiParametersRcd"); } else { throw cms::Exception("PoolDBService") << "No PoolDBService available."; } diff --git a/CondTools/Geometry/plugins/CSCRecoIdealDBLoader.cc b/CondTools/Geometry/plugins/CSCRecoIdealDBLoader.cc index 885ca3858378a..13d58f7fe997a 100644 --- a/CondTools/Geometry/plugins/CSCRecoIdealDBLoader.cc +++ b/CondTools/Geometry/plugins/CSCRecoIdealDBLoader.cc @@ -27,14 +27,14 @@ class CSCRecoIdealDBLoader : public edm::one::EDAnalyzer { void endRun(edm::Run const& iEvent, edm::EventSetup const&) override {} private: - bool fromDD4Hep_; + bool fromDD4hep_; edm::ESGetToken dd4HepCompactViewToken_; edm::ESGetToken compactViewToken_; edm::ESGetToken muonGeomConstantsToken_; }; CSCRecoIdealDBLoader::CSCRecoIdealDBLoader(const edm::ParameterSet& iC) { - fromDD4Hep_ = iC.getUntrackedParameter("fromDD4Hep", false); + fromDD4hep_ = iC.getUntrackedParameter("fromDD4hep", false); dd4HepCompactViewToken_ = esConsumes(); compactViewToken_ = esConsumes(); muonGeomConstantsToken_ = esConsumes(); @@ -54,7 +54,7 @@ void CSCRecoIdealDBLoader::beginRun(const edm::Run&, edm::EventSetup const& es) auto pMNDC = es.getHandle(muonGeomConstantsToken_); CSCGeometryParsFromDD cscgp; - if (fromDD4Hep_) { + if (fromDD4hep_) { auto pDD = es.getTransientHandle(dd4HepCompactViewToken_); const cms::DDCompactView& cpv = *pDD; cscgp.build(&cpv, *pMNDC, *rig, *rdp); diff --git a/CondTools/Geometry/plugins/DTRecoIdealDBLoader.cc b/CondTools/Geometry/plugins/DTRecoIdealDBLoader.cc index c8f9dc2795fce..59ef334b2334f 100644 --- a/CondTools/Geometry/plugins/DTRecoIdealDBLoader.cc +++ b/CondTools/Geometry/plugins/DTRecoIdealDBLoader.cc @@ -28,14 +28,14 @@ class DTRecoIdealDBLoader : public edm::one::EDAnalyzer { void endRun(edm::Run const& iEvent, edm::EventSetup const&) override {} private: - bool fromDD4Hep_; + bool fromDD4hep_; edm::ESGetToken dd4HepCompactViewToken_; edm::ESGetToken compactViewToken_; edm::ESGetToken muonGeomConstantsToken_; }; DTRecoIdealDBLoader::DTRecoIdealDBLoader(const edm::ParameterSet& iC) { - fromDD4Hep_ = iC.getUntrackedParameter("fromDD4Hep", false); + fromDD4hep_ = iC.getUntrackedParameter("fromDD4hep", false); dd4HepCompactViewToken_ = esConsumes(); compactViewToken_ = esConsumes(); muonGeomConstantsToken_ = esConsumes(); @@ -52,7 +52,7 @@ void DTRecoIdealDBLoader::beginRun(const edm::Run&, edm::EventSetup const& es) { auto pMNDC = es.getHandle(muonGeomConstantsToken_); DTGeometryParsFromDD dtgp; - if (fromDD4Hep_) { + if (fromDD4hep_) { auto pDD = es.getTransientHandle(dd4HepCompactViewToken_); const cms::DDCompactView& cpv = *pDD; dtgp.build(&cpv, *pMNDC, *rig); diff --git a/CondTools/Geometry/plugins/GEMRecoIdealDBLoader.cc b/CondTools/Geometry/plugins/GEMRecoIdealDBLoader.cc index 7787aa61d5e33..94b202b17defe 100644 --- a/CondTools/Geometry/plugins/GEMRecoIdealDBLoader.cc +++ b/CondTools/Geometry/plugins/GEMRecoIdealDBLoader.cc @@ -29,14 +29,14 @@ class GEMRecoIdealDBLoader : public edm::one::EDAnalyzer { void endRun(edm::Run const& iEvent, edm::EventSetup const&) override {} private: - bool fromDD4Hep_; + bool fromDD4hep_; edm::ESGetToken dd4HepCompactViewToken_; edm::ESGetToken compactViewToken_; edm::ESGetToken muonGeomConstantsToken_; }; GEMRecoIdealDBLoader::GEMRecoIdealDBLoader(const edm::ParameterSet& iC) { - fromDD4Hep_ = iC.getUntrackedParameter("fromDD4Hep", false); // set true for DD4HEP + fromDD4hep_ = iC.getUntrackedParameter("fromDD4hep", false); // set true for DD4HEP dd4HepCompactViewToken_ = esConsumes(); compactViewToken_ = esConsumes(); muonGeomConstantsToken_ = esConsumes(); @@ -57,7 +57,7 @@ void GEMRecoIdealDBLoader::beginRun(const edm::Run&, edm::EventSetup const& es) GEMGeometryParsFromDD rpcpd; RecoIdealGeometry* rig = new RecoIdealGeometry; - if (fromDD4Hep_) { + if (fromDD4hep_) { edm::LogVerbatim("GEMRecoIdealDBLoader") << "(0) GEMRecoIdealDBLoader - DD4HEP "; auto pDD = es.getTransientHandle(dd4HepCompactViewToken_); const cms::DDCompactView& cpv = *pDD; diff --git a/CondTools/Geometry/plugins/HcalParametersDBBuilder.cc b/CondTools/Geometry/plugins/HcalParametersDBBuilder.cc index 1a21df2ad7a8f..2f9daab65aa5c 100644 --- a/CondTools/Geometry/plugins/HcalParametersDBBuilder.cc +++ b/CondTools/Geometry/plugins/HcalParametersDBBuilder.cc @@ -25,16 +25,16 @@ class HcalParametersDBBuilder : public edm::one::EDAnalyzer void endRun(edm::Run const& iEvent, edm::EventSetup const&) override {} private: - bool fromDD4Hep_; + bool fromDD4hep_; edm::ESGetToken dd4HepCompactViewToken_; edm::ESGetToken compactViewToken_; }; HcalParametersDBBuilder::HcalParametersDBBuilder(const edm::ParameterSet& ps) - : fromDD4Hep_(ps.getParameter("fromDD4Hep")) { + : fromDD4hep_(ps.getParameter("fromDD4hep")) { #ifdef EDM_ML_DEBUG edm::LogVerbatim("HCalGeom") << "HcalParametersDBBuilder::HcalParametersDBBuilder called with dd4hep: " - << fromDD4Hep_; + << fromDD4hep_; #endif dd4HepCompactViewToken_ = esConsumes(); compactViewToken_ = esConsumes(); @@ -42,7 +42,7 @@ HcalParametersDBBuilder::HcalParametersDBBuilder(const edm::ParameterSet& ps) void HcalParametersDBBuilder::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { edm::ParameterSetDescription desc; - desc.add("fromDD4Hep", false); + desc.add("fromDD4hep", false); descriptions.add("HcalParametersWriter", desc); } @@ -56,7 +56,7 @@ void HcalParametersDBBuilder::beginRun(const edm::Run&, edm::EventSetup const& e HcalParametersFromDD builder; - if (fromDD4Hep_) { + if (fromDD4hep_) { #ifdef EDM_ML_DEBUG edm::LogVerbatim("HCalGeom") << "HcalParametersDBBuilder::Try to access cms::DDCompactView"; #endif diff --git a/CondTools/Geometry/plugins/ME0RecoIdealDBLoader.cc b/CondTools/Geometry/plugins/ME0RecoIdealDBLoader.cc index 84e71da6d2888..b1573895d1afe 100644 --- a/CondTools/Geometry/plugins/ME0RecoIdealDBLoader.cc +++ b/CondTools/Geometry/plugins/ME0RecoIdealDBLoader.cc @@ -27,14 +27,14 @@ class ME0RecoIdealDBLoader : public edm::one::EDAnalyzer { void endRun(edm::Run const& iEvent, edm::EventSetup const&) override {} private: - bool fromDD4Hep_; + bool fromDD4hep_; edm::ESGetToken dd4HepCompactViewToken_; edm::ESGetToken compactViewToken_; edm::ESGetToken muonGeomConstantsToken_; }; ME0RecoIdealDBLoader::ME0RecoIdealDBLoader(const edm::ParameterSet& iC) { - fromDD4Hep_ = iC.getUntrackedParameter("fromDD4Hep", false); // set true for DD4HEP + fromDD4hep_ = iC.getUntrackedParameter("fromDD4hep", false); // set true for DD4HEP dd4HepCompactViewToken_ = esConsumes(); compactViewToken_ = esConsumes(); muonGeomConstantsToken_ = esConsumes(); @@ -53,7 +53,7 @@ void ME0RecoIdealDBLoader::beginRun(const edm::Run&, edm::EventSetup const& es) auto pMNDC = es.getHandle(muonGeomConstantsToken_); ME0GeometryParsFromDD me0pd; RecoIdealGeometry* rig = new RecoIdealGeometry; - if (fromDD4Hep_) { + if (fromDD4hep_) { edm::LogVerbatim("ME0RecoIdealDBLoader") << "(0) ME0RecoIdealDBLoader - DD4HEP "; auto pDD = es.getTransientHandle(dd4HepCompactViewToken_); const cms::DDCompactView& cpv = *pDD; diff --git a/CondTools/Geometry/plugins/PHGCalParametersDBBuilder.cc b/CondTools/Geometry/plugins/PHGCalParametersDBBuilder.cc index 5468c050f6d70..f25221f3b4795 100644 --- a/CondTools/Geometry/plugins/PHGCalParametersDBBuilder.cc +++ b/CondTools/Geometry/plugins/PHGCalParametersDBBuilder.cc @@ -30,7 +30,7 @@ class PHGCalParametersDBBuilder : public edm::one::EDAnalyzer dd4HepCompactViewToken_; edm::ESGetToken compactViewToken_; }; @@ -41,13 +41,13 @@ PHGCalParametersDBBuilder::PHGCalParametersDBBuilder(const edm::ParameterSet& iC namew_ = iC.getParameter("nameW"); namec_ = iC.getParameter("nameC"); namet_ = iC.getParameter("nameT"); - fromDD4Hep_ = iC.getParameter("fromDD4Hep"); + fromDD4hep_ = iC.getParameter("fromDD4hep"); dd4HepCompactViewToken_ = esConsumes(); compactViewToken_ = esConsumes(); #ifdef EDM_ML_DEBUG edm::LogVerbatim("HGCalGeom") << "HGCalParametersESModule for " << name_ << ":" << name2_ << ":" << namew_ << ":" - << namec_ << ":" << namet_ << " and fromDD4Hep flag " << fromDD4Hep_; + << namec_ << ":" << namet_ << " and fromDD4hep flag " << fromDD4hep_; #endif } @@ -58,7 +58,7 @@ void PHGCalParametersDBBuilder::fillDescriptions(edm::ConfigurationDescriptions& desc.add("nameW", "HGCalEEWafer"); desc.add("nameC", "HGCalEECell"); desc.add("nameT", "HGCal"); - desc.add("fromDD4Hep", false); + desc.add("fromDD4hep", false); descriptions.add("HGCalEEParametersWriter", desc); } @@ -72,7 +72,7 @@ void PHGCalParametersDBBuilder::beginRun(const edm::Run&, edm::EventSetup const& HGCalParameters* ptp = new HGCalParameters(name_); HGCalParametersFromDD builder; - if (fromDD4Hep_) { + if (fromDD4hep_) { #ifdef EDM_ML_DEBUG edm::LogVerbatim("HGCalGeom") << "PHGCalParametersDBBuilder::Try to access cm::DDCompactView"; #endif diff --git a/CondTools/Geometry/plugins/RPCRecoIdealDBLoader.cc b/CondTools/Geometry/plugins/RPCRecoIdealDBLoader.cc index 69332ef488c9e..82c596be75210 100644 --- a/CondTools/Geometry/plugins/RPCRecoIdealDBLoader.cc +++ b/CondTools/Geometry/plugins/RPCRecoIdealDBLoader.cc @@ -27,14 +27,14 @@ class RPCRecoIdealDBLoader : public edm::one::EDAnalyzer { void endRun(edm::Run const& iEvent, edm::EventSetup const&) override {} private: - bool fromDD4Hep_; + bool fromDD4hep_; edm::ESGetToken dd4HepCompactViewToken_; edm::ESGetToken compactViewToken_; edm::ESGetToken muonGeomConstantsToken_; }; RPCRecoIdealDBLoader::RPCRecoIdealDBLoader(const edm::ParameterSet& iC) { - fromDD4Hep_ = iC.getUntrackedParameter("fromDD4Hep", false); + fromDD4hep_ = iC.getUntrackedParameter("fromDD4hep", false); dd4HepCompactViewToken_ = esConsumes(); compactViewToken_ = esConsumes(); muonGeomConstantsToken_ = esConsumes(); @@ -51,7 +51,7 @@ void RPCRecoIdealDBLoader::beginRun(const edm::Run&, edm::EventSetup const& es) auto pMNDC = es.getHandle(muonGeomConstantsToken_); RPCGeometryParsFromDD rpcpd; - if (fromDD4Hep_) { + if (fromDD4hep_) { auto pDD = es.getTransientHandle(dd4HepCompactViewToken_); const cms::DDCompactView& cpv = *pDD; rpcpd.build(&cpv, *pMNDC, *rig); diff --git a/CondTools/Geometry/python/HGCalParametersWriter_cff.py b/CondTools/Geometry/python/HGCalParametersWriter_cff.py index f64d58a53350e..59d8e06902d62 100644 --- a/CondTools/Geometry/python/HGCalParametersWriter_cff.py +++ b/CondTools/Geometry/python/HGCalParametersWriter_cff.py @@ -5,7 +5,7 @@ from Configuration.ProcessModifiers.dd4hep_cff import dd4hep dd4hep.toModify(HGCalEEParametersWriter, - fromDD4Hep = cms.bool(True) + fromDD4hep = cms.bool(True) ) HGCalHESiParametersWriter = HGCalEEParametersWriter.clone( diff --git a/CondTools/Geometry/python/HcalParametersWriter_cff.py b/CondTools/Geometry/python/HcalParametersWriter_cff.py index 86daa0ce54349..e6a4ed4faa5a0 100644 --- a/CondTools/Geometry/python/HcalParametersWriter_cff.py +++ b/CondTools/Geometry/python/HcalParametersWriter_cff.py @@ -5,5 +5,5 @@ from Configuration.ProcessModifiers.dd4hep_cff import dd4hep dd4hep.toModify(HcalParametersWriter, - fromDD4Hep = cms.bool(True) + fromDD4hep = cms.bool(True) ) diff --git a/CondTools/Geometry/test/calogeometry2026writer.py b/CondTools/Geometry/test/calogeometry2026writer.py index bc71576f92cba..5ccd23807fa1f 100644 --- a/CondTools/Geometry/test/calogeometry2026writer.py +++ b/CondTools/Geometry/test/calogeometry2026writer.py @@ -18,7 +18,7 @@ EcalP = cms.untracked.bool(False), HGCal = cms.untracked.bool(True)) -process.HcalParametersWriter.fromDD4Hep = cms.bool(False) +process.HcalParametersWriter.fromDD4hep = cms.bool(False) process.CondDB.timetype = cms.untracked.string('runnumber') process.CondDB.connect = cms.string('sqlite_file:myfile.db') process.PoolDBOutputService = cms.Service("PoolDBOutputService", diff --git a/CondTools/Geometry/test/calogeometrywriter.py b/CondTools/Geometry/test/calogeometrywriter.py index 52e67ba997e21..565de0b0458d9 100644 --- a/CondTools/Geometry/test/calogeometrywriter.py +++ b/CondTools/Geometry/test/calogeometrywriter.py @@ -14,7 +14,7 @@ process.CaloGeometryWriter = cms.EDAnalyzer("PCaloGeometryBuilder") -process.HcalParametersWriter.fromDD4Hep = cms.bool(False) +process.HcalParametersWriter.fromDD4hep = cms.bool(False) process.CondDB.timetype = cms.untracked.string('runnumber') process.CondDB.connect = cms.string('sqlite_file:myfile.db') process.PoolDBOutputService = cms.Service("PoolDBOutputService", diff --git a/CondTools/Geometry/test/cscgeometrywriter.py b/CondTools/Geometry/test/cscgeometrywriter.py index f601c334fce66..272a55057a2bd 100644 --- a/CondTools/Geometry/test/cscgeometrywriter.py +++ b/CondTools/Geometry/test/cscgeometrywriter.py @@ -15,7 +15,7 @@ ) process.CSCGeometryWriter = cms.EDAnalyzer("CSCRecoIdealDBLoader", - fromDD4Hep = cms.bool(False)) + fromDD4hep = cms.bool(False)) process.CondDB.timetype = cms.untracked.string('runnumber') process.CondDB.connect = cms.string('sqlite_file:myfile.db') diff --git a/CondTools/Geometry/test/dtgeometrywriter.py b/CondTools/Geometry/test/dtgeometrywriter.py index fb96947e7e2f9..f279a728ec607 100644 --- a/CondTools/Geometry/test/dtgeometrywriter.py +++ b/CondTools/Geometry/test/dtgeometrywriter.py @@ -23,7 +23,7 @@ ) process.DTGeometryWriter = cms.EDAnalyzer("DTRecoIdealDBLoader", - fromDD4Hep = cms.untracked.bool(False)) + fromDD4hep = cms.untracked.bool(False)) process.CondDB.timetype = cms.untracked.string('runnumber') process.CondDB.connect = cms.string('sqlite_file:myfile.db') diff --git a/CondTools/Geometry/test/rpcgeometrywriter.py b/CondTools/Geometry/test/rpcgeometrywriter.py index 639b1696a45ff..7bb9b7c1a6cb6 100644 --- a/CondTools/Geometry/test/rpcgeometrywriter.py +++ b/CondTools/Geometry/test/rpcgeometrywriter.py @@ -23,7 +23,7 @@ ) process.RPCGeometryWriter = cms.EDAnalyzer("RPCRecoIdealDBLoader", - fromDD4Hep = cms.untracked.bool(False)) + fromDD4hep = cms.untracked.bool(False)) process.CondDB.timetype = cms.untracked.string('runnumber') process.CondDB.connect = cms.string('sqlite_file:myfile.db') diff --git a/CondTools/Geometry/test/writehelpers/createExtended2021DD4hepPayloads.sh b/CondTools/Geometry/test/writehelpers/createExtended2021DD4hepPayloads.sh index 18a02b05a2da5..4a97d08294e99 100755 --- a/CondTools/Geometry/test/writehelpers/createExtended2021DD4hepPayloads.sh +++ b/CondTools/Geometry/test/writehelpers/createExtended2021DD4hepPayloads.sh @@ -15,9 +15,7 @@ compgen -G "*.txt" > /dev/null && sed -i {s/TagXX/${mytag}/g} *.txt sed -i {s/TagXX/${mytag}/g} splitExtended2021Database.sh # First read in the little XML files and create the -# large XML file for the Phase1_R30F12_HCal Ideal scenario. -# Input cff Output file -# GeometryExtended2021_cff geSingleBigFile.xml +# big XML file for the Extended2021DD4hep scenario. cmsRun geometryExtended2021DD4hep_xmlwriter.py # Now convert the content of the large XML file into @@ -31,63 +29,60 @@ cmsRun geometryExtended2021DD4hep_writer.py # Input the many XML files referenced by the cff file and # output a single big XML file. # This is repeated several times below. The sed commands -# serve to give the following sequence of input and output +# serve to give the correct sequence of input and output # files -# -# Input cff Output file -# GeometryIdeal_cff giSingleBigFile.xml -# -# sed -i '{s/Extended2021/Extended2021ZeroMaterial/g}' geometryExtended2021DD4hep_xmlwriter.py -# sed -i '{s/\/ge/\/gez/g}' geometryExtended2021DD4hep_xmlwriter.py -# cmsRun geometryExtended2021DD4hep_xmlwriter.py - -# sed -i '{s/Extended2021ZeroMaterial/Extended2021FlatMinus05Percent/g}' geometryExtended2021DD4hep_xmlwriter.py -# sed -i '{s/\/gez/\/geFM05/g}' geometryExtended2021DD4hep_xmlwriter.py -# cmsRun geometryExtended2021DD4hep_xmlwriter.py - -# sed -i '{s/Extended2021FlatMinus05Percent/Extended2021FlatMinus10Percent/g}' geometryExtended2021DD4hep_xmlwriter.py -# sed -i '{s/\/geFM05/\/geFM10/g}' geometryExtended2021DD4hep_xmlwriter.py -# cmsRun geometryExtended2021DD4hep_xmlwriter.py - -# sed -i '{s/Extended2021FlatMinus10Percent/Extended2021FlatPlus05Percent/g}' geometryExtended2021DD4hep_xmlwriter.py -# sed -i '{s/\/geFM10/\/geFP05/g}' geometryExtended2021DD4hep_xmlwriter.py -# cmsRun geometryExtended2021DD4hep_xmlwriter.py - -# sed -i '{s/Extended2021FlatPlus05Percent/Extended2021FlatPlus10Percent/g}' geometryExtended2021DD4hep_xmlwriter.py -# sed -i '{s/\/geFP05/\/geFP10/g}' geometryExtended2021DD4hep_xmlwriter.py -# cmsRun geometryExtended2021DD4hep_xmlwriter.py + +sed -i '{s/ExtendedGeometry2021/ExtendedGeometry2021ZeroMaterial/g}' geometryExtended2021DD4hep_xmlwriter.py +sed -i '{s/\/ge/\/gez/g}' geometryExtended2021DD4hep_xmlwriter.py +cmsRun geometryExtended2021DD4hep_xmlwriter.py + +sed -i '{s/ExtendedGeometry2021ZeroMaterial/ExtendedGeometry2021FlatMinus05Percent/g}' geometryExtended2021DD4hep_xmlwriter.py +sed -i '{s/\/gez/\/geFM05/g}' geometryExtended2021DD4hep_xmlwriter.py +cmsRun geometryExtended2021DD4hep_xmlwriter.py + +sed -i '{s/ExtendedGeometry2021FlatMinus05Percent/ExtendedGeometry2021FlatMinus10Percent/g}' geometryExtended2021DD4hep_xmlwriter.py +sed -i '{s/\/geFM05/\/geFM10/g}' geometryExtended2021DD4hep_xmlwriter.py +cmsRun geometryExtended2021DD4hep_xmlwriter.py + +sed -i '{s/ExtendedGeometry2021FlatMinus10Percent/ExtendedGeometry2021FlatPlus05Percent/g}' geometryExtended2021DD4hep_xmlwriter.py +sed -i '{s/\/geFM10/\/geFP05/g}' geometryExtended2021DD4hep_xmlwriter.py +cmsRun geometryExtended2021DD4hep_xmlwriter.py + +sed -i '{s/ExtendedGeometry2021FlatPlus05Percent/ExtendedGeometry2021FlatPlus10Percent/g}' geometryExtended2021DD4hep_xmlwriter.py +sed -i '{s/\/geFP05/\/geFP10/g}' geometryExtended2021DD4hep_xmlwriter.py +cmsRun geometryExtended2021DD4hep_xmlwriter.py # Read the one big XML file and output a record to the # database with the an identifying tag # This is repeated several times below. The sed commands -# serve to give the following sequence of input file and output +# serve to give the correct sequence of input file and output # tag -# +# To start: # Input file Output tag # gezSingleBigFile.xml XMLFILE_Geometry_${mytag}_Extended2021ZeroMaterial_mc -# -# sed -i '{s/Extended/Extended2021ZeroMaterial/g}' xmlgeometrywriter.py -# sed -i '{s/\/ge/\/gez/g}' xmlgeometrywriter.py -# cmsRun xmlgeometrywriter.py -# sed -i '{s/Extended2021ZeroMaterial/Extended2021FlatMinus05Percent/g}' xmlgeometrywriter.py -# sed -i '{s/\/gez/\/geFM05/g}' xmlgeometrywriter.py -# cmsRun xmlgeometrywriter.py +sed -i '{s/Extended/Extended2021ZeroMaterial/g}' xmlgeometrywriter.py +sed -i '{s/\/ge/\/gez/g}' xmlgeometrywriter.py +cmsRun xmlgeometrywriter.py + +sed -i '{s/Extended2021ZeroMaterial/Extended2021FlatMinus05Percent/g}' xmlgeometrywriter.py +sed -i '{s/\/gez/\/geFM05/g}' xmlgeometrywriter.py +cmsRun xmlgeometrywriter.py -# sed -i '{s/Extended2021FlatMinus05Percent/Extended2021FlatMinus10Percent/g}' xmlgeometrywriter.py -# sed -i '{s/\/geFM05/\/geFM10/g}' xmlgeometrywriter.py -# cmsRun xmlgeometrywriter.py +sed -i '{s/Extended2021FlatMinus05Percent/Extended2021FlatMinus10Percent/g}' xmlgeometrywriter.py +sed -i '{s/\/geFM05/\/geFM10/g}' xmlgeometrywriter.py +cmsRun xmlgeometrywriter.py -# sed -i '{s/Extended2021FlatMinus10Percent/Extended2021FlatPlus05Percent/g}' xmlgeometrywriter.py -# sed -i '{s/\/geFM10/\/geFP05/g}' xmlgeometrywriter.py -# cmsRun xmlgeometrywriter.py +sed -i '{s/Extended2021FlatMinus10Percent/Extended2021FlatPlus05Percent/g}' xmlgeometrywriter.py +sed -i '{s/\/geFM10/\/geFP05/g}' xmlgeometrywriter.py +cmsRun xmlgeometrywriter.py -# sed -i '{s/Extended2021FlatPlus05Percent/Extended2021FlatPlus10Percent/g}' xmlgeometrywriter.py -# sed -i '{s/\/geFP05/\/geFP10/g}' xmlgeometrywriter.py -# cmsRun xmlgeometrywriter.py +sed -i '{s/Extended2021FlatPlus05Percent/Extended2021FlatPlus10Percent/g}' xmlgeometrywriter.py +sed -i '{s/\/geFP05/\/geFP10/g}' xmlgeometrywriter.py +cmsRun xmlgeometrywriter.py # All the database objects were written into one database # (myfile.db) in the steps above. Extract the different # pieces into separate database files. These are the payloads -# that get uploaded to the dropbox. There is one for each tag +# that get uploaded to the DB. There is one for each tag ./splitExtended2021Database.sh diff --git a/CondTools/Geometry/test/writehelpers/geometryExtended2021DD4hep_writer.py b/CondTools/Geometry/test/writehelpers/geometryExtended2021DD4hep_writer.py index 554423ee90704..9d4e15da9d629 100644 --- a/CondTools/Geometry/test/writehelpers/geometryExtended2021DD4hep_writer.py +++ b/CondTools/Geometry/test/writehelpers/geometryExtended2021DD4hep_writer.py @@ -40,15 +40,15 @@ process.TrackerGeometryWriter = cms.EDAnalyzer("PGeometricDetBuilder",fromDD4hep=cms.bool(True)) process.TrackerParametersWriter = cms.EDAnalyzer("PTrackerParametersDBBuilder",fromDD4hep=cms.bool(True)) -process.CaloGeometryWriter = cms.EDAnalyzer("PCaloGeometryBuilder",fromDD4Hep = cms.untracked.bool(True)) +process.CaloGeometryWriter = cms.EDAnalyzer("PCaloGeometryBuilder",fromDD4hep = cms.untracked.bool(True)) -process.CSCGeometryWriter = cms.EDAnalyzer("CSCRecoIdealDBLoader",fromDD4Hep = cms.untracked.bool(True)) +process.CSCGeometryWriter = cms.EDAnalyzer("CSCRecoIdealDBLoader",fromDD4hep = cms.untracked.bool(True)) -process.DTGeometryWriter = cms.EDAnalyzer("DTRecoIdealDBLoader",fromDD4Hep = cms.untracked.bool(True)) +process.DTGeometryWriter = cms.EDAnalyzer("DTRecoIdealDBLoader",fromDD4hep = cms.untracked.bool(True)) -process.RPCGeometryWriter = cms.EDAnalyzer("RPCRecoIdealDBLoader",fromDD4Hep = cms.untracked.bool(True)) +process.RPCGeometryWriter = cms.EDAnalyzer("RPCRecoIdealDBLoader",fromDD4hep = cms.untracked.bool(True)) -process.GEMGeometryWriter = cms.EDAnalyzer("GEMRecoIdealDBLoader",fromDD4Hep = cms.untracked.bool(True)) +process.GEMGeometryWriter = cms.EDAnalyzer("GEMRecoIdealDBLoader",fromDD4hep = cms.untracked.bool(True)) process.CondDB.timetype = cms.untracked.string('runnumber') process.CondDB.connect = cms.string('sqlite_file:myfile.db') diff --git a/CondTools/Geometry/test/writehelpers/geometryExtended2021_writer.py b/CondTools/Geometry/test/writehelpers/geometryExtended2021_writer.py index b1b29f2b3e191..8baf29ce5d289 100644 --- a/CondTools/Geometry/test/writehelpers/geometryExtended2021_writer.py +++ b/CondTools/Geometry/test/writehelpers/geometryExtended2021_writer.py @@ -36,11 +36,11 @@ process.CaloGeometryWriter = cms.EDAnalyzer("PCaloGeometryBuilder") -process.CSCGeometryWriter = cms.EDAnalyzer("CSCRecoIdealDBLoader",fromDD4Hep = cms.untracked.bool(False)) +process.CSCGeometryWriter = cms.EDAnalyzer("CSCRecoIdealDBLoader",fromDD4hep = cms.untracked.bool(False)) -process.DTGeometryWriter = cms.EDAnalyzer("DTRecoIdealDBLoader",fromDD4Hep = cms.untracked.bool(False)) +process.DTGeometryWriter = cms.EDAnalyzer("DTRecoIdealDBLoader",fromDD4hep = cms.untracked.bool(False)) -process.RPCGeometryWriter = cms.EDAnalyzer("RPCRecoIdealDBLoader",fromDD4Hep = cms.untracked.bool(False)) +process.RPCGeometryWriter = cms.EDAnalyzer("RPCRecoIdealDBLoader",fromDD4hep = cms.untracked.bool(False)) process.GEMGeometryWriter = cms.EDAnalyzer("GEMRecoIdealDBLoader") diff --git a/CondTools/Geometry/test/writehelpers/geometryExtended2026_writer.py b/CondTools/Geometry/test/writehelpers/geometryExtended2026_writer.py index aec94dc15bc42..9573fa710fa19 100644 --- a/CondTools/Geometry/test/writehelpers/geometryExtended2026_writer.py +++ b/CondTools/Geometry/test/writehelpers/geometryExtended2026_writer.py @@ -37,11 +37,11 @@ EcalP = cms.untracked.bool(False), HGCal = cms.untracked.bool(False)) -process.CSCGeometryWriter = cms.EDAnalyzer("CSCRecoIdealDBLoader",fromDD4Hep = cms.untracked.bool(False)) +process.CSCGeometryWriter = cms.EDAnalyzer("CSCRecoIdealDBLoader",fromDD4hep = cms.untracked.bool(False)) -process.DTGeometryWriter = cms.EDAnalyzer("DTRecoIdealDBLoader",fromDD4Hep = cms.untracked.bool(False)) +process.DTGeometryWriter = cms.EDAnalyzer("DTRecoIdealDBLoader",fromDD4hep = cms.untracked.bool(False)) -process.RPCGeometryWriter = cms.EDAnalyzer("RPCRecoIdealDBLoader",fromDD4Hep = cms.untracked.bool(False)) +process.RPCGeometryWriter = cms.EDAnalyzer("RPCRecoIdealDBLoader",fromDD4hep = cms.untracked.bool(False)) process.GEMGeometryWriter = cms.EDAnalyzer("GEMRecoIdealDBLoader") diff --git a/CondTools/Geometry/test/writehelpers/splitExtended2021Database.sh b/CondTools/Geometry/test/writehelpers/splitExtended2021Database.sh index 747889deb2a37..860185a5dacdf 100755 --- a/CondTools/Geometry/test/writehelpers/splitExtended2021Database.sh +++ b/CondTools/Geometry/test/writehelpers/splitExtended2021Database.sh @@ -1,6 +1,11 @@ #!/bin/sh conddb --yes --db myfile.db copy XMLFILE_Geometry_TagXX_Extended2021_mc --destdb GeometryFileExtended2021.db +conddb --yes --db myfile.db copy XMLFILE_Geometry_TagXX_Extended2021ZeroMaterial_mc --destdb GeometryFileExtended2021ZeroMaterial.db +conddb --yes --db myfile.db copy XMLFILE_Geometry_TagXX_Extended2021FlatMinus05Percent_mc --destdb GeometryFileExtended2021FlatMinus05Percent.db +conddb --yes --db myfile.db copy XMLFILE_Geometry_TagXX_Extended2021FlatMinus10Percent_mc --destdb GeometryFileExtended2021FlatMinus10Percent.db +conddb --yes --db myfile.db copy XMLFILE_Geometry_TagXX_Extended2021FlatPlus05Percent_mc --destdb GeometryFileExtended2021FlatPlus05Percent.db +conddb --yes --db myfile.db copy XMLFILE_Geometry_TagXX_Extended2021FlatPlus10Percent_mc --destdb GeometryFileExtended2021FlatPlus10Percent.db conddb --yes --db myfile.db copy TKRECO_Geometry_TagXX --destdb TKRECO_Geometry.db conddb --yes --db myfile.db copy TKParameters_Geometry_TagXX --destdb TKParameters_Geometry.db conddb --yes --db myfile.db copy EBRECO_Geometry_TagXX --destdb EBRECO_Geometry.db @@ -10,7 +15,6 @@ conddb --yes --db myfile.db copy HCALRECO_Geometry_TagXX --destdb conddb --yes --db myfile.db copy HCALParameters_Geometry_TagXX --destdb HCALParameters_Geometry.db conddb --yes --db myfile.db copy CTRECO_Geometry_TagXX --destdb CTRECO_Geometry.db conddb --yes --db myfile.db copy ZDCRECO_Geometry_TagXX --destdb ZDCRECO_Geometry.db -conddb --yes --db myfile.db copy CASTORRECO_Geometry_TagXX --destdb CASTORRECO_Geometry.db conddb --yes --db myfile.db copy CSCRECO_Geometry_TagXX --destdb CSCRECO_Geometry.db conddb --yes --db myfile.db copy CSCRECODIGI_Geometry_TagXX --destdb CSCRECODIGI_Geometry.db conddb --yes --db myfile.db copy DTRECO_Geometry_TagXX --destdb DTRECO_Geometry.db diff --git a/CondTools/Hcal/interface/BoostIODBReader.h b/CondTools/Hcal/interface/BoostIODBReader.h index 95fc36c19357e..2c9d24448c2f9 100644 --- a/CondTools/Hcal/interface/BoostIODBReader.h +++ b/CondTools/Hcal/interface/BoostIODBReader.h @@ -26,7 +26,7 @@ #include "CondFormats/Serialization/interface/eos/portable_oarchive.hpp" #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" @@ -39,7 +39,7 @@ // class declaration // template -class BoostIODBReader : public edm::EDAnalyzer { +class BoostIODBReader : public edm::one::EDAnalyzer<> { public: typedef DataType data_type; typedef RecordType record_type; diff --git a/CondTools/Hcal/interface/BoostIODBWriter.h b/CondTools/Hcal/interface/BoostIODBWriter.h index df4ab0d4c2d98..e3669ac3deb4a 100644 --- a/CondTools/Hcal/interface/BoostIODBWriter.h +++ b/CondTools/Hcal/interface/BoostIODBWriter.h @@ -27,7 +27,7 @@ #include "CondFormats/Serialization/interface/eos/portable_iarchive.hpp" #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/Utilities/interface/Exception.h" @@ -41,7 +41,7 @@ // class declaration // template -class BoostIODBWriter : public edm::EDAnalyzer { +class BoostIODBWriter : public edm::one::EDAnalyzer<> { public: typedef DataType data_type; @@ -71,7 +71,7 @@ void BoostIODBWriter::analyze(const edm::Event& iEvent, const edm::Eve edm::Service poolDbService; if (poolDbService.isAvailable()) - poolDbService->writeOne(datum.release(), poolDbService->currentTime(), record_); + poolDbService->writeOneIOV(*datum, poolDbService->currentTime(), record_); else throw cms::Exception("ConfigurationError") << "PoolDBOutputService is not available, " << "please configure it properly" << std::endl; diff --git a/CondTools/Hcal/interface/HcalAutoPedestalValidator.h b/CondTools/Hcal/interface/HcalAutoPedestalValidator.h index a90a0f725d15b..6098d63d3f777 100644 --- a/CondTools/Hcal/interface/HcalAutoPedestalValidator.h +++ b/CondTools/Hcal/interface/HcalAutoPedestalValidator.h @@ -12,7 +12,7 @@ #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/MakerMacros.h" @@ -37,7 +37,7 @@ #include "CalibCalorimetry/HcalAlgos/interface/HcalDbASCIIIO.h" #include "Geometry/HcalTowerAlgo/interface/HcalGeometry.h" -class HcalAutoPedestalValidator : public edm::EDAnalyzer { +class HcalAutoPedestalValidator : public edm::one::EDAnalyzer<> { public: HcalAutoPedestalValidator(edm::ParameterSet const& ps); diff --git a/CondTools/Hcal/interface/HcalGainsCheck.h b/CondTools/Hcal/interface/HcalGainsCheck.h index 6a39c30475d95..5a2e9e029d83e 100644 --- a/CondTools/Hcal/interface/HcalGainsCheck.h +++ b/CondTools/Hcal/interface/HcalGainsCheck.h @@ -14,7 +14,7 @@ #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/MakerMacros.h" @@ -43,7 +43,7 @@ #include "TH1.h" #include "TH2.h" -class HcalGainsCheck : public edm::EDAnalyzer { +class HcalGainsCheck : public edm::one::EDAnalyzer<> { public: HcalGainsCheck(edm::ParameterSet const& ps); diff --git a/CondTools/Hcal/interface/HcalPedestalWidthsCheck.h b/CondTools/Hcal/interface/HcalPedestalWidthsCheck.h index d96c775bb88fe..a9a80c4e190b8 100644 --- a/CondTools/Hcal/interface/HcalPedestalWidthsCheck.h +++ b/CondTools/Hcal/interface/HcalPedestalWidthsCheck.h @@ -14,7 +14,7 @@ #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/MakerMacros.h" @@ -39,7 +39,7 @@ #include "CalibCalorimetry/HcalAlgos/interface/HcalDbASCIIIO.h" #include "Geometry/HcalTowerAlgo/interface/HcalGeometry.h" -class HcalPedestalWidthsCheck : public edm::EDAnalyzer { +class HcalPedestalWidthsCheck : public edm::one::EDAnalyzer<> { public: HcalPedestalWidthsCheck(edm::ParameterSet const& ps); diff --git a/CondTools/Hcal/interface/HcalPedestalsCheck.h b/CondTools/Hcal/interface/HcalPedestalsCheck.h index 3112ee24c211f..173b1b5f39b43 100644 --- a/CondTools/Hcal/interface/HcalPedestalsCheck.h +++ b/CondTools/Hcal/interface/HcalPedestalsCheck.h @@ -14,7 +14,7 @@ #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/MakerMacros.h" @@ -39,7 +39,7 @@ #include "CalibCalorimetry/HcalAlgos/interface/HcalDbASCIIIO.h" #include "Geometry/HcalTowerAlgo/interface/HcalGeometry.h" -class HcalPedestalsCheck : public edm::EDAnalyzer { +class HcalPedestalsCheck : public edm::one::EDAnalyzer<> { public: HcalPedestalsCheck(edm::ParameterSet const& ps); diff --git a/CondTools/Hcal/interface/HcalQIEDataCheck.h b/CondTools/Hcal/interface/HcalQIEDataCheck.h index 3ea71c0b1b3ae..b2e0ed06b9aab 100644 --- a/CondTools/Hcal/interface/HcalQIEDataCheck.h +++ b/CondTools/Hcal/interface/HcalQIEDataCheck.h @@ -13,7 +13,7 @@ #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/MakerMacros.h" @@ -34,7 +34,7 @@ #include "CalibCalorimetry/HcalAlgos/interface/HcalDbASCIIIO.h" #include "Geometry/HcalTowerAlgo/interface/HcalGeometry.h" -class HcalQIEDataCheck : public edm::EDAnalyzer { +class HcalQIEDataCheck : public edm::one::EDAnalyzer<> { public: HcalQIEDataCheck(edm::ParameterSet const& ps); diff --git a/CondTools/Hcal/plugins/BufferedBoostIODBWriter.cc b/CondTools/Hcal/plugins/BufferedBoostIODBWriter.cc index fbd468ef78586..cbda375679554 100644 --- a/CondTools/Hcal/plugins/BufferedBoostIODBWriter.cc +++ b/CondTools/Hcal/plugins/BufferedBoostIODBWriter.cc @@ -7,7 +7,7 @@ #include #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" @@ -20,7 +20,7 @@ // // class declaration // -class BufferedBoostIODBWriter : public edm::EDAnalyzer { +class BufferedBoostIODBWriter : public edm::one::EDAnalyzer<> { public: explicit BufferedBoostIODBWriter(const edm::ParameterSet&); ~BufferedBoostIODBWriter() override {} @@ -63,7 +63,7 @@ void BufferedBoostIODBWriter::analyze(const edm::Event& iEvent, const edm::Event edm::Service poolDbService; if (poolDbService.isAvailable()) - poolDbService->writeOne(fcp.release(), poolDbService->currentTime(), record); + poolDbService->writeOneIOV(*fcp, poolDbService->currentTime(), record); else throw cms::Exception("ConfigurationError") << "PoolDBOutputService is not available, " << "please configure it properly" << std::endl; diff --git a/CondTools/Hcal/plugins/HcalDumpConditions.cc b/CondTools/Hcal/plugins/HcalDumpConditions.cc index 4061182459d49..a1e783cb9f3c1 100644 --- a/CondTools/Hcal/plugins/HcalDumpConditions.cc +++ b/CondTools/Hcal/plugins/HcalDumpConditions.cc @@ -16,7 +16,7 @@ September 21, 2009 Added HcalLutMetadata - Gena Kukartsev #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/MakerMacros.h" @@ -35,7 +35,7 @@ September 21, 2009 Added HcalLutMetadata - Gena Kukartsev #include "CondFormats/HcalObjects/interface/AllObjects.h" namespace edmtest { - class HcalDumpConditions : public edm::EDAnalyzer { + class HcalDumpConditions : public edm::one::EDAnalyzer<> { public: explicit HcalDumpConditions(edm::ParameterSet const& p) { front = p.getUntrackedParameter("outFilePrefix", "Dump"); diff --git a/CondTools/Hcal/test/HcalConditionsTest.cc b/CondTools/Hcal/test/HcalConditionsTest.cc index 32fab2ee0e87a..ebb7430515534 100644 --- a/CondTools/Hcal/test/HcalConditionsTest.cc +++ b/CondTools/Hcal/test/HcalConditionsTest.cc @@ -14,7 +14,7 @@ R.Ofierzynski - 2.Oct. 2007 #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/MakerMacros.h" @@ -41,7 +41,7 @@ R.Ofierzynski - 2.Oct. 2007 #include "FWCore/Framework/interface/IOVSyncValue.h" namespace edmtest { - class HcalConditionsTest : public edm::EDAnalyzer { + class HcalConditionsTest : public edm::one::EDAnalyzer<> { public: explicit HcalConditionsTest(edm::ParameterSet const& p) { front = p.getUntrackedParameter("outFilePrefix", "Dump"); diff --git a/CondTools/L1Trigger/src/Interval.icc b/CondTools/L1Trigger/src/Interval.icc deleted file mode 100644 index 6f44e0d9c3c0f..0000000000000 --- a/CondTools/L1Trigger/src/Interval.icc +++ /dev/null @@ -1,36 +0,0 @@ -/* vim: set filetype=cpp: */ - -/* - * Interval Manager implementation - */ - -template -const l1t::Interval & l1t::IntervalManager::find (const TimeType & time) const -{ - typename IntervalMap::const_iterator it = intervalMap.upper_bound (time); - - // check if requested time is not too low. - if (it == intervalMap.begin ()) - return Interval::invalid (); - - // upper_bound will return value that is greather then time. So we go back and found good interval - it --; - - // finally make sure that this is correct interval. It could be that we got end () because we time - // is bigger then we have in map - if (it->second.start () <= time && it->second.end () >= time) - return it->second; - - return Interval::invalid (); -} - -/* - * Interval implementation - */ -template -l1t::Interval & l1t::Interval::invalid () -{ - static Interval invalid = Interval (TimeType (), TimeType ()); - invalid.isInvalid= true; - return invalid; -} diff --git a/CondTools/RunInfo/interface/BTransitionAnalyzer.h b/CondTools/RunInfo/interface/BTransitionAnalyzer.h index fb0d058840ebb..d077bbcb646ab 100644 --- a/CondTools/RunInfo/interface/BTransitionAnalyzer.h +++ b/CondTools/RunInfo/interface/BTransitionAnalyzer.h @@ -59,7 +59,7 @@ namespace cond { edm::LogInfo("BTransitionAnalyzer") << "Exporting payload corresponding to the calibrations for magnetic field " << (bFieldLabel == bOnLabel ? "ON" : "OFF") << " starting from run number: " << run.run() << std::endl; - mydbservice->writeOne(payloadHandle.product(), run.run(), demangledName(typeid(R))); + mydbservice->writeOneIOV(*payloadHandle.product(), run.run(), demangledName(typeid(R))); } else { edm::LogInfo("BTransitionAnalyzer") << "The payload corresponding to the calibrations for magnetic field " << (bFieldLabel == bOnLabel ? "ON" : "OFF") << " is still valid for run " diff --git a/CondTools/SiPhase2Tracker/plugins/DTCCablingMapProducer.cc b/CondTools/SiPhase2Tracker/plugins/DTCCablingMapProducer.cc index 098a56b1dcf67..c8f7ab691aa31 100644 --- a/CondTools/SiPhase2Tracker/plugins/DTCCablingMapProducer.cc +++ b/CondTools/SiPhase2Tracker/plugins/DTCCablingMapProducer.cc @@ -269,7 +269,7 @@ void DTCCablingMapProducer::endJob() { edm::Service poolDbService; if (poolDbService.isAvailable()) { - poolDbService->writeOne(pCablingMap_.release(), iovBeginTime_, record_); + poolDbService->writeOneIOV(*pCablingMap_, iovBeginTime_, record_); } else { throw cms::Exception("PoolDBServiceNotFound") << "A running PoolDBService instance is required."; } diff --git a/CondTools/SiPhase2Tracker/plugins/DTCCablingMapTestProducer.cc b/CondTools/SiPhase2Tracker/plugins/DTCCablingMapTestProducer.cc index add76f683e8c8..1c39547f10190 100644 --- a/CondTools/SiPhase2Tracker/plugins/DTCCablingMapTestProducer.cc +++ b/CondTools/SiPhase2Tracker/plugins/DTCCablingMapTestProducer.cc @@ -78,7 +78,7 @@ void DTCCablingMapTestProducer::beginJob() { edm::Service poolDbService; if (poolDbService.isAvailable()) - poolDbService->writeOne(pCablingMap_.release(), iovBeginTime_, recordName_); + poolDbService->writeOneIOV(*pCablingMap_, iovBeginTime_, recordName_); else throw std::runtime_error("PoolDBService required."); } diff --git a/CondTools/SiPhase2Tracker/plugins/SiPhase2OuterTrackerLorentzAngleReader.cc b/CondTools/SiPhase2Tracker/plugins/SiPhase2OuterTrackerLorentzAngleReader.cc new file mode 100644 index 0000000000000..2a2fde75b6994 --- /dev/null +++ b/CondTools/SiPhase2Tracker/plugins/SiPhase2OuterTrackerLorentzAngleReader.cc @@ -0,0 +1,64 @@ +// user include files +#include "FWCore/Framework/interface/MakerMacros.h" +#include "FWCore/Framework/interface/Frameworkfwd.h" +#include "FWCore/Framework/interface/global/EDAnalyzer.h" +#include "FWCore/Framework/interface/Event.h" +#include "FWCore/Framework/interface/EventSetup.h" +#include "FWCore/ServiceRegistry/interface/Service.h" +#include "FWCore/MessageLogger/interface/MessageLogger.h" +#include "FWCore/ParameterSet/interface/ParameterSet.h" +#include "CondFormats/DataRecord/interface/SiPhase2OuterTrackerLorentzAngleRcd.h" +#include "CondFormats/SiPhase2TrackerObjects/interface/SiPhase2OuterTrackerLorentzAngle.h" + +// +// +// class decleration +// +class SiPhase2OuterTrackerLorentzAngleReader : public edm::global::EDAnalyzer<> { +public: + explicit SiPhase2OuterTrackerLorentzAngleReader(const edm::ParameterSet&); + ~SiPhase2OuterTrackerLorentzAngleReader() override = default; + void analyze(edm::StreamID, edm::Event const&, edm::EventSetup const&) const override; + + static void fillDescriptions(edm::ConfigurationDescriptions& descriptions); + +private: + const uint32_t printdebug_; + const std::string label_; + const edm::ESGetToken laToken_; +}; + +SiPhase2OuterTrackerLorentzAngleReader::SiPhase2OuterTrackerLorentzAngleReader(const edm::ParameterSet& iConfig) + : printdebug_(iConfig.getUntrackedParameter("printDebug", 5)), + label_(iConfig.getUntrackedParameter("label", "")), + laToken_(esConsumes(edm::ESInputTag{"", label_})) {} + +void SiPhase2OuterTrackerLorentzAngleReader::analyze(edm::StreamID, + edm::Event const& iEvent, + edm::EventSetup const& iSetup) const { + const auto& lorentzAngles = iSetup.getData(laToken_); + edm::LogInfo("SiPhase2OuterTrackerLorentzAngleReader") + << "[SiPhase2OuterTrackerLorentzAngleReader::analyze] End Reading SiPhase2OuterTrackerLorentzAngle with label " + << label_ << std::endl; + + const auto& detid_la = lorentzAngles.getLorentzAngles(); + std::unordered_map::const_iterator it; + size_t count = 0; + for (it = detid_la.begin(); it != detid_la.end() && count < printdebug_; it++) { + edm::LogInfo("SiPhase2OuterTrackerLorentzAngleReader") << "detid " << it->first << " \t" + << " Lorentz angle " << it->second; + count++; + } +} + +// ------------ method fills 'descriptions' with the allowed parameters for the module ------------ +void SiPhase2OuterTrackerLorentzAngleReader::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { + edm::ParameterSetDescription desc; + desc.setComment("Module to read SiPhase2OuterTrackerLorentzAngle Payloads"); + desc.addUntracked("printDebug", 5)->setComment("maximum amount of print-outs"); + desc.addUntracked("label", "")->setComment("label from which to read the payload"); + descriptions.addWithDefaultLabel(desc); +} + +//define this as a plug-in +DEFINE_FWK_MODULE(SiPhase2OuterTrackerLorentzAngleReader); diff --git a/CondTools/SiPhase2Tracker/plugins/SiPhase2OuterTrackerLorentzAngleWriter.cc b/CondTools/SiPhase2Tracker/plugins/SiPhase2OuterTrackerLorentzAngleWriter.cc index 489e9d6653cad..251793f91fd0e 100644 --- a/CondTools/SiPhase2Tracker/plugins/SiPhase2OuterTrackerLorentzAngleWriter.cc +++ b/CondTools/SiPhase2Tracker/plugins/SiPhase2OuterTrackerLorentzAngleWriter.cc @@ -51,9 +51,7 @@ class SiPhase2OuterTrackerLorentzAngleWriter : public edm::one::EDAnalyzer<> { static void fillDescriptions(edm::ConfigurationDescriptions& descriptions); private: - void beginJob() override; void analyze(const edm::Event&, const edm::EventSetup&) override; - void endJob() override; // ----------member data --------------------------- const edm::ESGetToken topoToken_; @@ -131,27 +129,21 @@ void SiPhase2OuterTrackerLorentzAngleWriter::analyze(const edm::Event& iEvent, c edm::LogInfo("SiPhase2OuterTrackerLorentzAngleWriter") << " There are " << detsLAtoDB.size() << " OT Lorentz Angle values assigned" << std::endl; - // SiStripLorentzAngle object - + // SiPhase2OuterTrackerLorentzAngle object auto lorentzAngle = std::make_unique(); lorentzAngle->putLorentzAngles(detsLAtoDB); edm::LogInfo("SiPhase2OuterTrackerLorentzAngleWriter") << "currentTime " << mydbservice->currentTime() << std::endl; - mydbservice->writeOne(lorentzAngle.get(), mydbservice->currentTime(), m_record); + mydbservice->writeOneIOV(*lorentzAngle, mydbservice->currentTime(), m_record); } -// ------------ method called once each job just before starting event loop ------------ -void SiPhase2OuterTrackerLorentzAngleWriter::beginJob() {} - -// ------------ method called once each job just after ending the event loop ------------ -void SiPhase2OuterTrackerLorentzAngleWriter::endJob() {} - // ------------ method fills 'descriptions' with the allowed parameters for the module ------------ void SiPhase2OuterTrackerLorentzAngleWriter::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { edm::ParameterSetDescription desc; - desc.add("record", "SiPhase2OuterTrackerLorentzAngleRcd"); - desc.add("tag", "SiPhase2OuterTrackerLorentzAngle"); - desc.add("value", 0.07); - descriptions.addDefault(desc); + desc.setComment("Module to write SiPhase2OuterTrackerLorentzAngle Payloads"); + desc.add("record", "SiPhase2OuterTrackerLorentzAngleRcd")->setComment("record to write"); + desc.add("tag", "SiPhase2OuterTrackerLorentzAngle")->setComment("tag to write"); + desc.add("value", 0.07)->setComment("value to be put in the payload"); + descriptions.addWithDefaultLabel(desc); } //define this as a plug-in diff --git a/CondTools/SiPhase2Tracker/test/BuildFile.xml b/CondTools/SiPhase2Tracker/test/BuildFile.xml new file mode 100644 index 0000000000000..4f550c96b297f --- /dev/null +++ b/CondTools/SiPhase2Tracker/test/BuildFile.xml @@ -0,0 +1 @@ + diff --git a/CondTools/SiPhase2Tracker/test/DTCCablingMapProducer_write.py b/CondTools/SiPhase2Tracker/test/DTCCablingMapProducer_write.py index a839346c27ebf..adfa131aa0d52 100644 --- a/CondTools/SiPhase2Tracker/test/DTCCablingMapProducer_write.py +++ b/CondTools/SiPhase2Tracker/test/DTCCablingMapProducer_write.py @@ -33,7 +33,7 @@ #dummy_fill_mode = cms.string("DUMMY_FILL_DISABLED"), #dummy_fill_mode = cms.string("DUMMY_FILL_ELINK_ID"), modulesToDTCCablingCSVFileNames = cms.vstring( - "CondTools/SiPhase2Tracker/TrackerDetToDTCELinkCablingMap__OT614_200_IT404_layer2_10G__T6__OTOnly.csv" + "CondTools/SiPhase2Tracker/data/TrackerModuleToDTCCablingMap__OT616_200_IT613__T14__OTOnly.csv" ), dummy_fill_mode = cms.string("DUMMY_FILL_ELINK_ID_AND_GBT_ID"), csvFormat_ncolumns = cms.uint32( 2), diff --git a/CondTools/SiPhase2Tracker/test/SiPhase2OuterTrackerLorentzAngleReader_cfg.py b/CondTools/SiPhase2Tracker/test/SiPhase2OuterTrackerLorentzAngleReader_cfg.py new file mode 100644 index 0000000000000..e4e99b328671e --- /dev/null +++ b/CondTools/SiPhase2Tracker/test/SiPhase2OuterTrackerLorentzAngleReader_cfg.py @@ -0,0 +1,78 @@ +#! /usr/bin/env cmsRun +# Author: Marco Musich (October 2021) +import FWCore.ParameterSet.Config as cms +process = cms.Process("TEST") + +################################################################### +# Messages +################################################################### +process.load('FWCore.MessageService.MessageLogger_cfi') +process.MessageLogger.cerr.enable = False +process.MessageLogger.SiPhase2OuterTrackerLorentzAngleReader=dict() +process.MessageLogger.SiPhase2OuterTrackerLorentzAngle=dict() +process.MessageLogger.cout = cms.untracked.PSet( + enable = cms.untracked.bool(True), + enableStatistics = cms.untracked.bool(True), + threshold = cms.untracked.string("INFO"), + default = cms.untracked.PSet(limit = cms.untracked.int32(0)), + FwkReport = cms.untracked.PSet(limit = cms.untracked.int32(-1), + reportEvery = cms.untracked.int32(1000) + ), + SiPhase2OuterTrackerLorentzAngleReader = cms.untracked.PSet( limit = cms.untracked.int32(-1)), + SiPhase2OuterTrackerLorentzAngle = cms.untracked.PSet( limit = cms.untracked.int32(-1)), +) + +################################################################### +# A data source must always be defined. +# We don't need it, so here's a dummy one. +################################################################### +process.source = cms.Source("EmptyIOVSource", + timetype = cms.string('runnumber'), + firstValue = cms.uint64(1), + lastValue = cms.uint64(1), + interval = cms.uint64(1) +) + +################################################################### +# Input data +################################################################### +tag = 'SiPhase2OuterTrackerLorentzAngle_T15' +suffix = 'v0' +inFile = tag+'_'+suffix+'.db' +inDB = 'sqlite_file:'+inFile + +process.load("CondCore.CondDB.CondDB_cfi") +# input database (in this case the local sqlite file) +process.CondDB.connect = inDB + +process.PoolDBESSource = cms.ESSource("PoolDBESSource", + process.CondDB, + DumpStat=cms.untracked.bool(True), + toGet = cms.VPSet(cms.PSet(record = cms.string("SiPhase2OuterTrackerLorentzAngleRcd"), + tag = cms.string(tag)) + ) + ) + +################################################################### +# check the ES data getter +################################################################### +process.get = cms.EDAnalyzer("EventSetupRecordDataGetter", + toGet = cms.VPSet(cms.PSet( + record = cms.string(' SiPhase2OuterTrackerLorentzAngleRcd'), + data = cms.vstring('SiPhase2OuterTrackerLorentzAngle') + )), + verbose = cms.untracked.bool(True) +) + +################################################################### +# Payload reader +################################################################### +import CondTools.SiPhase2Tracker.siPhase2OuterTrackerLorentzAngleReader_cfi as _mod +process.LAPayloadReader = _mod.siPhase2OuterTrackerLorentzAngleReader.clone(printDebug = 10, + label = "") + +################################################################### +# Path +################################################################### +process.p = cms.Path(process.LAPayloadReader) + diff --git a/CondTools/SiPhase2Tracker/test/test_CondToolsSiPhase2Tracker.sh b/CondTools/SiPhase2Tracker/test/test_CondToolsSiPhase2Tracker.sh new file mode 100755 index 0000000000000..780f52ec81d99 --- /dev/null +++ b/CondTools/SiPhase2Tracker/test/test_CondToolsSiPhase2Tracker.sh @@ -0,0 +1,20 @@ + #!/bin/bash -ex +TEST_DIR=$CMSSW_BASE/src/CondTools/SiPhase2Tracker/test +echo "test dir: $TEST_DIR" + +printf "testing writing Phase2 Lorentz Angle \n\n" +## need to be in order (don't read before writing) +cmsRun ${TEST_DIR}/SiPhase2OuterTrackerLorentzAngleWriter_cfg.py +cmsRun ${TEST_DIR}/SiPhase2OuterTrackerLorentzAngleReader_cfg.py + +printf "testing writing Phase2 Tracker Cabling Map (test) \n\n" +## need to be in order (don't read before writing) +cmsRun ${TEST_DIR}/DTCCablingMapTestProducer_write.py +cmsRun ${TEST_DIR}/DTCCablingMapTestProducer_retrieve.py +cmsRun ${TEST_DIR}/DTCCablingMapTestProducer_dump.py + +printf "testing writing Phase2 Tracker Cabling Map \n\n" +## need to be in order (don't read before writing) +cmsRun ${TEST_DIR}/DTCCablingMapProducer_write.py +cmsRun ${TEST_DIR}/DTCCablingMapProducer_retrieve.py +cmsRun ${TEST_DIR}/DTCCablingMapProducer_dump.py diff --git a/CondTools/SiPixel/plugins/BuildFile.xml b/CondTools/SiPixel/plugins/BuildFile.xml index e77dddc76cc94..fcf25955b81d3 100644 --- a/CondTools/SiPixel/plugins/BuildFile.xml +++ b/CondTools/SiPixel/plugins/BuildFile.xml @@ -2,11 +2,13 @@ + + + - diff --git a/CondTools/SiPixel/plugins/SiPixel2DTemplateDBObjectUploader.cc b/CondTools/SiPixel/plugins/SiPixel2DTemplateDBObjectUploader.cc index 5dfc275fdbc01..a90e3588ae701 100644 --- a/CondTools/SiPixel/plugins/SiPixel2DTemplateDBObjectUploader.cc +++ b/CondTools/SiPixel/plugins/SiPixel2DTemplateDBObjectUploader.cc @@ -76,19 +76,19 @@ void SiPixel2DTemplateDBObjectUploader::beginJob() {} void SiPixel2DTemplateDBObjectUploader::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) { //--- Make the POOL-ORA object to store the database object - SiPixel2DTemplateDBObject* obj = new SiPixel2DTemplateDBObject; + SiPixel2DTemplateDBObject obj; // Local variables const char* tempfile; int m; // Set the number of templates to be passed to the dbobject - obj->setNumOfTempl(theTemplateCalibrations.size()); + obj.setNumOfTempl(theTemplateCalibrations.size()); // Set the version of the template dbobject - this is an external parameter - obj->setVersion(theVersion); + obj.setVersion(theVersion); // Open the template file(s) - for (m = 0; m < obj->numOfTempl(); ++m) { + for (m = 0; m < obj.numOfTempl(); ++m) { edm::FileInPath file(theTemplateCalibrations[m].c_str()); tempfile = (file.fullPath()).c_str(); std::ifstream in_file(tempfile, std::ios::in); @@ -116,15 +116,15 @@ void SiPixel2DTemplateDBObjectUploader::analyze(const edm::Event& iEvent, const temp.c[1] = title_char[j + 1]; temp.c[2] = title_char[j + 2]; temp.c[3] = title_char[j + 3]; - obj->push_back(temp.f); - obj->setMaxIndex(obj->maxIndex() + 1); + obj.push_back(temp.f); + obj.setMaxIndex(obj.maxIndex() + 1); } // Fill the dbobject in_file >> tempstore; while (!in_file.eof()) { - obj->setMaxIndex(obj->maxIndex() + 1); - obj->push_back(tempstore); + obj.setMaxIndex(obj.maxIndex() + 1); + obj.push_back(tempstore); in_file >> tempstore; } @@ -195,7 +195,7 @@ void SiPixel2DTemplateDBObjectUploader::analyze(const edm::Event& iEvent, const thisID = (short)theBarrelTemplateIds[iter]; } - if (thisID == 10000 || (!(*obj).putTemplateID(detid.rawId(), thisID))) + if (thisID == 10000 || (!obj.putTemplateID(detid.rawId(), thisID))) edm::LogPrint("SiPixel2DTemplateDBObjectUploader") << " Could not fill barrel layer " << layer << ", module " << module << "\n"; edm::LogPrint("SiPixel2DTemplateDBObjectUploader") @@ -240,7 +240,7 @@ void SiPixel2DTemplateDBObjectUploader::analyze(const edm::Event& iEvent, const thisID = (short)theEndcapTemplateIds[iter]; } - if (thisID == 10000 || (!(*obj).putTemplateID(detid.rawId(), thisID))) + if (thisID == 10000 || (!obj.putTemplateID(detid.rawId(), thisID))) edm::LogPrint("SiPixel2DTemplateDBObjectUploader") << " Could not fill endcap det unit" << side << ", disk " << disk << ", blade " << blade << ", and panel " << panel << ".\n"; @@ -253,7 +253,7 @@ void SiPixel2DTemplateDBObjectUploader::analyze(const edm::Event& iEvent, const //Print out the assignment of this detID short mapnum; - mapnum = (*obj).getTemplateID(detid.rawId()); + mapnum = obj.getTemplateID(detid.rawId()); edm::LogPrint("SiPixel2DTemplateDBObjectUploader") << "The DetID: " << detid.rawId() << " is mapped to the template: " << mapnum << "\n"; } @@ -264,9 +264,9 @@ void SiPixel2DTemplateDBObjectUploader::analyze(const edm::Event& iEvent, const if (!poolDbService.isAvailable()) // Die if not available throw cms::Exception("NotAvailable") << "PoolDBOutputService not available"; if (poolDbService->isNewTagRequest("SiPixel2DTemplateDBObjectRcd")) - poolDbService->writeOne(obj, poolDbService->beginOfTime(), "SiPixel2DTemplateDBObjectRcd"); + poolDbService->writeOneIOV(obj, poolDbService->beginOfTime(), "SiPixel2DTemplateDBObjectRcd"); else - poolDbService->writeOne(obj, poolDbService->currentTime(), "SiPixel2DTemplateDBObjectRcd"); + poolDbService->writeOneIOV(obj, poolDbService->currentTime(), "SiPixel2DTemplateDBObjectRcd"); } void SiPixel2DTemplateDBObjectUploader::endJob() {} diff --git a/CondTools/SiPixel/plugins/SiPixelGenErrorDBObjectUploader.cc b/CondTools/SiPixel/plugins/SiPixelGenErrorDBObjectUploader.cc index 94b99b05a0f54..0ed5eb2fc2332 100644 --- a/CondTools/SiPixel/plugins/SiPixelGenErrorDBObjectUploader.cc +++ b/CondTools/SiPixel/plugins/SiPixelGenErrorDBObjectUploader.cc @@ -75,20 +75,20 @@ void SiPixelGenErrorDBObjectUploader::beginJob() {} void SiPixelGenErrorDBObjectUploader::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) { //--- Make the POOL-ORA object to store the database object - SiPixelGenErrorDBObject* obj = new SiPixelGenErrorDBObject; + SiPixelGenErrorDBObject obj; // Local variables const char* tempfile; int m; // Set the number of GenErrors to be passed to the dbobject - obj->setNumOfTempl(theGenErrorCalibrations.size()); + obj.setNumOfTempl(theGenErrorCalibrations.size()); // Set the version of the GenError dbobject - this is an external parameter - obj->setVersion(theVersion); + obj.setVersion(theVersion); // Open the GenError file(s) - for (m = 0; m < obj->numOfTempl(); ++m) { + for (m = 0; m < obj.numOfTempl(); ++m) { edm::FileInPath file(theGenErrorCalibrations[m].c_str()); tempfile = (file.fullPath()).c_str(); std::ifstream in_file(tempfile, std::ios::in); @@ -117,8 +117,8 @@ void SiPixelGenErrorDBObjectUploader::analyze(const edm::Event& iEvent, const ed temp.c[1] = title_char[j + 1]; temp.c[2] = title_char[j + 2]; temp.c[3] = title_char[j + 3]; - obj->push_back(temp.f); - obj->setMaxIndex(obj->maxIndex() + 1); + obj.push_back(temp.f); + obj.setMaxIndex(obj.maxIndex() + 1); } // Check if the magnetic field is the same as in the header of the input files @@ -137,8 +137,8 @@ void SiPixelGenErrorDBObjectUploader::analyze(const edm::Event& iEvent, const ed // Fill the dbobject in_file >> tempstore; while (!in_file.eof()) { - obj->setMaxIndex(obj->maxIndex() + 1); - obj->push_back(tempstore); + obj.setMaxIndex(obj.maxIndex() + 1); + obj.push_back(tempstore); in_file >> tempstore; } @@ -210,7 +210,7 @@ void SiPixelGenErrorDBObjectUploader::analyze(const edm::Event& iEvent, const ed thisID = (short)theBarrelGenErrIds[iter]; } - if (thisID == 10000 || (!(*obj).putGenErrorID(detid.rawId(), thisID))) + if (thisID == 10000 || (!obj.putGenErrorID(detid.rawId(), thisID))) edm::LogPrint("SiPixelGenErrorDBObjectUploader") << " Could not fill barrel layer " << layer << ", module " << module << "\n"; edm::LogPrint("SiPixelGenErrorDBObjectUploader") @@ -254,7 +254,7 @@ void SiPixelGenErrorDBObjectUploader::analyze(const edm::Event& iEvent, const ed thisID = (short)theEndcapGenErrIds[iter]; } - if (thisID == 10000 || (!(*obj).putGenErrorID(detid.rawId(), thisID))) + if (thisID == 10000 || (!obj.putGenErrorID(detid.rawId(), thisID))) edm::LogPrint("SiPixelGenErrorDBObjectUploader") << " Could not fill endcap det unit" << side << ", disk " << disk << ", blade " << blade << ", panel " << panel << ".\n"; @@ -266,7 +266,7 @@ void SiPixelGenErrorDBObjectUploader::analyze(const edm::Event& iEvent, const ed //Print out the assignment of this DetID short mapnum; - mapnum = (*obj).getGenErrorID(detid.rawId()); + mapnum = obj.getGenErrorID(detid.rawId()); edm::LogPrint("SiPixelGenErrorDBObjectUploader") << "The DetID: " << detid.rawId() << " is mapped to the template: " << mapnum << "\n"; } @@ -277,9 +277,9 @@ void SiPixelGenErrorDBObjectUploader::analyze(const edm::Event& iEvent, const ed if (!poolDbService.isAvailable()) // Die if not available throw cms::Exception("NotAvailable") << "PoolDBOutputService not available"; if (poolDbService->isNewTagRequest("SiPixelGenErrorDBObjectRcd")) - poolDbService->writeOne(obj, poolDbService->beginOfTime(), "SiPixelGenErrorDBObjectRcd"); + poolDbService->writeOneIOV(obj, poolDbService->beginOfTime(), "SiPixelGenErrorDBObjectRcd"); else - poolDbService->writeOne(obj, poolDbService->currentTime(), "SiPixelGenErrorDBObjectRcd"); + poolDbService->writeOneIOV(obj, poolDbService->currentTime(), "SiPixelGenErrorDBObjectRcd"); } void SiPixelGenErrorDBObjectUploader::endJob() {} diff --git a/CondTools/SiPixel/test/createTestDBObjects.sh b/CondTools/SiPixel/test/createTestDBObjects.sh index 493a270040520..f20acad1b8f13 100755 --- a/CondTools/SiPixel/test/createTestDBObjects.sh +++ b/CondTools/SiPixel/test/createTestDBObjects.sh @@ -2,56 +2,56 @@ function die { echo $1: status $2 ; exit $2; } -echo "TESTING Pixel CPE DB codes ..." +echo -e "TESTING Pixel CPE DB codes ..." -echo "TESTING Pixel 1D Template DB code ..." +echo -e "TESTING Pixel 1D Template DB code ..." cmsRun ${LOCAL_TEST_DIR}/SiPixelTemplateDBObjectUploader_cfg.py MagField=0.0 Fullname=SiPixelTemplateDBObject_phase1_0T_mc_BoR3_v1_bugfix Map=${LOCAL_TEST_DIR}/../data/phaseI_mapping.csv TemplateFilePath=CalibTracker/SiPixelESProducers/data/SiPixelTemplateDBObject_0T_phase1_BoR3_v1 || die "Failure running SiPixelTemplateDBObjectUploader_cfg.py" $? -echo "TESTING Pixel 1D GenErr DB code ..." +echo -e "TESTING Pixel 1D GenErr DB code ..." cmsRun ${LOCAL_TEST_DIR}/SiPixelGenErrorDBObjectUploader_cfg.py MagField=0.0 Fullname=SiPixelGenErrorDBObject_phase1_0T_mc_BoR3_v1_bugfix Map=${LOCAL_TEST_DIR}/../data/phaseI_mapping.csv GenErrFilePath=CalibTracker/SiPixelESProducers/data/SiPixelTemplateDBObject_0T_phase1_BoR3_v1 || die "Failure running SiPixelGenErrorDBObjectUploader_cfg.py" $? -echo "TESTING Pixel 1D Template DB code for Phase-2 ..." +echo -e "TESTING Pixel 1D Template DB code for Phase-2 ..." cmsRun ${LOCAL_TEST_DIR}/SiPixelTemplateDBObjectUploader_Phase2_cfg.py MagField=3.8 Version=7 Append=mc_25x100 Map=${LOCAL_TEST_DIR}/../data/phase2_T15_mapping.csv geometry=T15 TemplateFilePath=CalibTracker/SiPixelESProducers/data/Phase2_25by100_templates_2020October || die "Failure running SiPixelTemplateDBObjectUploader_Phase2_cfg.py" $? -echo "TESTING Pixel 1D GenErr DB code for Phase-2 ..." +echo -e "TESTING Pixel 1D GenErr DB code for Phase-2 ..." cmsRun ${LOCAL_TEST_DIR}/SiPixelGenErrorDBObjectUploader_Phase2_cfg.py MagField=3.8 Version=7 Append=mc_25x100 Map=${LOCAL_TEST_DIR}/../data/phase2_T15_mapping.csv geometry=T15 GenErrFilePath=CalibTracker/SiPixelESProducers/data/Phase2_25by100_templates_2020October || die "Failure running SiPixelGenErrorDBObjectUploader_Phase2_cfg.py" $? -echo "TESTING Pixel 2D Template DB code for Phase-2 ..." +echo -e "TESTING Pixel 2D Template DB code for Phase-2 ..." cmsRun ${LOCAL_TEST_DIR}/SiPixel2DTemplateDBObjectUploader_Phase2_cfg.py MagField=3.8 Version=7 Append=mc_25x100 Map=${LOCAL_TEST_DIR}/../data/phase2_T15_mapping.csv TemplateFilePath=CalibTracker/SiPixelESProducers/data/Phase2_25by100_templates_2020October denominator=True || die "Failure running SiPixel2DTemplateDBObjectUploader_Phase2_cfg.py" $? -echo "TESTING SiPixelVCal DB codes ... \n\n" +echo -e "TESTING SiPixelVCal DB codes ... \n\n" -echo "TESTING Writing SiPixelVCal DB object ...\n\n" +echo -e "TESTING Writing SiPixelVCal DB object ...\n\n" cmsRun ${LOCAL_TEST_DIR}/SiPixelVCalDB_cfg.py || die "Failure running SiPixelVCalDB_cfg.py" $? -echo "TESTING Reading SiPixelVCal DB object ...\n\n" +echo -e "TESTING Reading SiPixelVCal DB object ...\n\n" cmsRun ${LOCAL_TEST_DIR}/SiPixelVCalReader_cfg.py || die "Failure running SiPixelVCalReader_cfg.py" $? -echo "TESTING SiPixelLorentzAngle DB codes ... \n\n" +echo -e "TESTING SiPixelLorentzAngle DB codes ... \n\n" -echo "TESTING Writing SiPixelLorentzAngle DB object ...\n\n" +echo -e "TESTING Writing SiPixelLorentzAngle DB object ...\n\n" cmsRun ${LOCAL_TEST_DIR}/SiPixelLorentzAngleDB_cfg.py || die "Failure running SiPixelLorentzAngleDB_cfg.py" $? -echo "TESTING Reading SiPixelLorentzAngle DB object ...\n\n" +echo -e "TESTING Reading SiPixelLorentzAngle DB object ...\n\n" cmsRun ${LOCAL_TEST_DIR}/SiPixelLorentzAngleReader_cfg.py || die "Failure running SiPixelLorentzAngleReader_cfg.py" $? -echo "TESTING SiPixelDynamicInefficiency DB codes ... \n\n" +echo -e "TESTING SiPixelDynamicInefficiency DB codes ... \n\n" -echo "TESTING Writing SiPixelDynamicInefficiency DB object ...\n\n" +echo -e "TESTING Writing SiPixelDynamicInefficiency DB object ...\n\n" cmsRun ${LOCAL_TEST_DIR}/SiPixelDynamicInefficiencyDB_cfg.py || die "Failure running SiPixelDynamicInefficiencyDB_cfg.py" $? -echo "TESTING Reading SiPixelDynamicInefficiency DB object ...\n\n" +echo -e "TESTING Reading SiPixelDynamicInefficiency DB object ...\n\n" cmsRun ${LOCAL_TEST_DIR}/SiPixelDynamicInefficiencyReader_cfg.py || die "Failure running SiPixelDynamicInefficiencyReader_cfg.py" $? -echo "TESTING SiPixelGain Scaling DB codes ... \n\n" +echo -e "TESTING SiPixelGain Scaling DB codes ... \n\n" -echo "TESTING Writing Scaled SiPixel Gain DB Object ...\n\n" +echo -e "TESTING Writing Scaled SiPixel Gain DB Object ...\n\n" cmsRun ${LOCAL_TEST_DIR}/SiPixelGainCalibScaler_cfg.py firstRun=278869 maxEvents=12000 || die "Failure running SiPixelGainCalibScaler_cfg.py" $? -echo "TESTING SiPixelQuality DB codes ... \n\n" +echo -e "TESTING SiPixelQuality DB codes ... \n\n" -echo "TESTING Writing SiPixelQuality DB object ...\n\n" +echo -e "TESTING Writing SiPixelQuality DB object ...\n\n" cmsRun ${LOCAL_TEST_DIR}/SiPixelBadModuleByHandBuilder_cfg.py || die "Failure running SiPixelBadModuleByHandBuilder_cfg.py" $? -echo "TESTING Reading SiPixelQuality DB object ...\n\n" +echo -e "TESTING Reading SiPixelQuality DB object ...\n\n" cmsRun ${LOCAL_TEST_DIR}/SiPixelBadModuleReader_cfg.py || die "Failure running SiPixelBadModuleReader_cfg.py" $? diff --git a/CondTools/SiStrip/plugins/SiStripApvGainBuilder.cc b/CondTools/SiStrip/plugins/SiStripApvGainBuilder.cc index c82f1789cf398..4cef3d99a8f24 100644 --- a/CondTools/SiStrip/plugins/SiStripApvGainBuilder.cc +++ b/CondTools/SiStrip/plugins/SiStripApvGainBuilder.cc @@ -14,7 +14,7 @@ void SiStripApvGainBuilder::analyze(const edm::Event& evt, const edm::EventSetup edm::LogInfo("SiStripApvGainBuilder") << "... creating dummy SiStripApvGain Data for Run " << run << "\n " << std::endl; - SiStripApvGain* obj = new SiStripApvGain(); + SiStripApvGain obj; int count = -1; for (const auto& it : SiStripDetInfoFileReader::read(fp_.fullPath()).getAllData()) { @@ -30,7 +30,7 @@ void SiStripApvGainBuilder::analyze(const edm::Event& evt, const edm::EventSetup } SiStripApvGain::Range range(theSiStripVector.begin(), theSiStripVector.end()); - if (!obj->put(it.first, range)) + if (!obj.put(it.first, range)) edm::LogError("SiStripApvGainBuilder") << "[SiStripApvGainBuilder::analyze] detid already exists" << std::endl; } @@ -39,10 +39,9 @@ void SiStripApvGainBuilder::analyze(const edm::Event& evt, const edm::EventSetup if (mydbservice.isAvailable()) { if (mydbservice->isNewTagRequest("SiStripApvGainRcd")) { - mydbservice->createNewIOV( - obj, mydbservice->beginOfTime(), mydbservice->endOfTime(), "SiStripApvGainRcd"); + mydbservice->createOneIOV(obj, mydbservice->beginOfTime(), "SiStripApvGainRcd"); } else { - mydbservice->appendSinceTime(obj, mydbservice->currentTime(), "SiStripApvGainRcd"); + mydbservice->appendOneIOV(obj, mydbservice->currentTime(), "SiStripApvGainRcd"); } } else { edm::LogError("SiStripApvGainBuilder") << "Service is unavailable" << std::endl; diff --git a/CondTools/SiStrip/plugins/SiStripApvGainRescaler.cc b/CondTools/SiStrip/plugins/SiStripApvGainRescaler.cc index a624d035ca80b..56dc16f3d3bd7 100644 --- a/CondTools/SiStrip/plugins/SiStripApvGainRescaler.cc +++ b/CondTools/SiStrip/plugins/SiStripApvGainRescaler.cc @@ -128,7 +128,7 @@ void SiStripApvGainRescaler::analyze(const edm::Event& iEvent, const edm::EventS edm::Service poolDbService; if (poolDbService.isAvailable()) - poolDbService->writeOne(theAPVGains.get(), poolDbService->currentTime(), m_Record); + poolDbService->writeOneIOV(*theAPVGains, poolDbService->currentTime(), m_Record); else throw std::runtime_error("PoolDBService required."); } diff --git a/CondTools/SiStrip/plugins/SiStripChannelGainFromDBMiscalibrator.cc b/CondTools/SiStrip/plugins/SiStripChannelGainFromDBMiscalibrator.cc index 6135a243adc52..0ea0498b4a6c4 100644 --- a/CondTools/SiStrip/plugins/SiStripChannelGainFromDBMiscalibrator.cc +++ b/CondTools/SiStrip/plugins/SiStripChannelGainFromDBMiscalibrator.cc @@ -239,7 +239,7 @@ void SiStripChannelGainFromDBMiscalibrator::analyze(const edm::Event& iEvent, co edm::Service poolDbService; if (poolDbService.isAvailable()) - poolDbService->writeOne(theAPVGains.get(), poolDbService->currentTime(), m_Record); + poolDbService->writeOneIOV(*theAPVGains, poolDbService->currentTime(), m_Record); else throw std::runtime_error("PoolDBService required."); } diff --git a/CondTools/SiStrip/plugins/SiStripDetVOffFakeBuilder.cc b/CondTools/SiStrip/plugins/SiStripDetVOffFakeBuilder.cc index b1e35a3ba7f3f..3ff5471fa1d90 100644 --- a/CondTools/SiStrip/plugins/SiStripDetVOffFakeBuilder.cc +++ b/CondTools/SiStrip/plugins/SiStripDetVOffFakeBuilder.cc @@ -51,7 +51,7 @@ void SiStripDetVOffFakeBuilder::analyze(const edm::Event& evt, const edm::EventS edm::LogInfo("SiStripDetVOffFakeBuilder") << "... creating dummy SiStripDetVOff Data for Run " << run << "\n " << std::endl; - SiStripDetVOff* SiStripDetVOff_ = new SiStripDetVOff(); + SiStripDetVOff SiStripDetVOff_; // std::vector TheDetIdHVVector; @@ -61,19 +61,19 @@ void SiStripDetVOffFakeBuilder::analyze(const edm::Event& evt, const edm::EventS int lv = rand() % 20; if (hv <= 2) { edm::LogInfo("SiStripDetVOffFakeBuilder") << "detid: " << *it << " HV\t OFF" << std::endl; - SiStripDetVOff_->put(*it, 1, -1); + SiStripDetVOff_.put(*it, 1, -1); // TheDetIdHVVector.push_back(*it); } if (lv <= 2) { edm::LogInfo("SiStripDetVOffFakeBuilder") << "detid: " << *it << " LV\t OFF" << std::endl; - SiStripDetVOff_->put(*it, -1, 1); + SiStripDetVOff_.put(*it, -1, 1); // TheDetIdHVVector.push_back(*it); } if (lv <= 2 || hv <= 2) edm::LogInfo("SiStripDetVOffFakeBuilder") << "detid: " << *it << " V\t OFF" << std::endl; } - // SiStripDetVOff_->put(TheDetIdHVVector); + // SiStripDetVOff_.put(TheDetIdHVVector); //End now write DetVOff data in DB edm::Service mydbservice; @@ -81,10 +81,9 @@ void SiStripDetVOffFakeBuilder::analyze(const edm::Event& evt, const edm::EventS if (mydbservice.isAvailable()) { try { if (mydbservice->isNewTagRequest("SiStripDetVOffRcd")) { - mydbservice->createNewIOV( - SiStripDetVOff_, mydbservice->beginOfTime(), mydbservice->endOfTime(), "SiStripDetVOffRcd"); + mydbservice->createOneIOV(SiStripDetVOff_, mydbservice->beginOfTime(), "SiStripDetVOffRcd"); } else { - mydbservice->appendSinceTime(SiStripDetVOff_, mydbservice->currentTime(), "SiStripDetVOffRcd"); + mydbservice->appendOneIOV(SiStripDetVOff_, mydbservice->currentTime(), "SiStripDetVOffRcd"); } } catch (const cond::Exception& er) { edm::LogError("SiStripDetVOffFakeBuilder") << er.what() << std::endl; diff --git a/CondTools/SiStrip/plugins/SiStripFedCablingBuilder.cc b/CondTools/SiStrip/plugins/SiStripFedCablingBuilder.cc index 1d1a3f83c2505..4bfa0df8de243 100644 --- a/CondTools/SiStrip/plugins/SiStripFedCablingBuilder.cc +++ b/CondTools/SiStrip/plugins/SiStripFedCablingBuilder.cc @@ -91,17 +91,16 @@ void SiStripFedCablingBuilder::beginRun(const edm::Run& run, const edm::EventSet edm::LogVerbatim("SiStripFedCablingBuilder") << "[SiStripFedCablingBuilder::" << __func__ << "]" << " Copying FED cabling..."; - SiStripFedCabling* obj = new SiStripFedCabling(*(fed.product())); + SiStripFedCabling obj(*(fed.product())); //End now write sistripnoises data in DB edm::Service mydbservice; if (mydbservice.isAvailable()) { if (mydbservice->isNewTagRequest("SiStripFedCablingRcd")) { - mydbservice->createNewIOV( - obj, mydbservice->beginOfTime(), mydbservice->endOfTime(), "SiStripFedCablingRcd"); + mydbservice->createOneIOV(obj, mydbservice->beginOfTime(), "SiStripFedCablingRcd"); } else { - mydbservice->appendSinceTime(obj, mydbservice->currentTime(), "SiStripFedCablingRcd"); + mydbservice->appendOneIOV(obj, mydbservice->currentTime(), "SiStripFedCablingRcd"); } } else { edm::LogError("SiStripFedCablingBuilder") << "Service is unavailable" << std::endl; diff --git a/CondTools/SiStrip/plugins/SiStripNoisesBuilder.cc b/CondTools/SiStrip/plugins/SiStripNoisesBuilder.cc index d1bd0f6a6b9d1..de511793bb741 100644 --- a/CondTools/SiStrip/plugins/SiStripNoisesBuilder.cc +++ b/CondTools/SiStrip/plugins/SiStripNoisesBuilder.cc @@ -13,7 +13,7 @@ void SiStripNoisesBuilder::analyze(const edm::Event& evt, const edm::EventSetup& edm::LogInfo("SiStripNoisesBuilder") << "... creating dummy SiStripNoises Data for Run " << run << "\n " << std::endl; - SiStripNoises* obj = new SiStripNoises(); + SiStripNoises obj; int count = -1; for (const auto& it : SiStripDetInfoFileReader::read(fp_.fullPath()).getAllData()) { @@ -28,14 +28,14 @@ void SiStripNoisesBuilder::analyze(const edm::Event& evt, const edm::EventSetup& //double badStripProb = .5; //bool disable = (CLHEP::RandFlat::shoot(1.) < badStripProb ? true:false); - obj->setData(noise, theSiStripVector); + obj.setData(noise, theSiStripVector); if (count < static_cast(printdebug_)) edm::LogInfo("SiStripNoisesBuilder") << "detid " << it.first << " \t" << " strip " << strip << " \t" << noise << " \t" << theSiStripVector.back() / 10 << " \t" << std::endl; } - if (!obj->put(it.first, theSiStripVector)) + if (!obj.put(it.first, theSiStripVector)) edm::LogError("SiStripNoisesBuilder") << "[SiStripNoisesBuilder::analyze] detid already exists" << std::endl; } @@ -44,11 +44,10 @@ void SiStripNoisesBuilder::analyze(const edm::Event& evt, const edm::EventSetup& if (mydbservice.isAvailable()) { if (mydbservice->isNewTagRequest("SiStripNoisesRcd")) { - mydbservice->createNewIOV( - obj, mydbservice->beginOfTime(), mydbservice->endOfTime(), "SiStripNoisesRcd"); + mydbservice->createOneIOV(obj, mydbservice->beginOfTime(), "SiStripNoisesRcd"); } else { //mydbservice->createNewIOV(obj,mydbservice->currentTime(),"SiStripNoisesRcd"); - mydbservice->appendSinceTime(obj, mydbservice->currentTime(), "SiStripNoisesRcd"); + mydbservice->appendOneIOV(obj, mydbservice->currentTime(), "SiStripNoisesRcd"); } } else { edm::LogError("SiStripNoisesBuilder") << "Service is unavailable" << std::endl; diff --git a/CondTools/SiStrip/plugins/SiStripNoisesFromDBMiscalibrator.cc b/CondTools/SiStrip/plugins/SiStripNoisesFromDBMiscalibrator.cc index afa72e8c2dc56..9f5f48813aa75 100644 --- a/CondTools/SiStrip/plugins/SiStripNoisesFromDBMiscalibrator.cc +++ b/CondTools/SiStrip/plugins/SiStripNoisesFromDBMiscalibrator.cc @@ -254,7 +254,7 @@ void SiStripNoisesFromDBMiscalibrator::analyze(const edm::Event& iEvent, const e edm::Service poolDbService; if (poolDbService.isAvailable()) - poolDbService->writeOne(theSiStripNoises.get(), poolDbService->currentTime(), "SiStripNoisesRcd"); + poolDbService->writeOneIOV(*theSiStripNoises, poolDbService->currentTime(), "SiStripNoisesRcd"); else throw std::runtime_error("PoolDBService required."); } diff --git a/CondTools/SiStrip/plugins/SiStripPedestalsBuilder.cc b/CondTools/SiStrip/plugins/SiStripPedestalsBuilder.cc index 8a909dfda5ae6..b24861d0974eb 100644 --- a/CondTools/SiStrip/plugins/SiStripPedestalsBuilder.cc +++ b/CondTools/SiStrip/plugins/SiStripPedestalsBuilder.cc @@ -14,7 +14,7 @@ void SiStripPedestalsBuilder::analyze(const edm::Event& evt, const edm::EventSet edm::LogInfo("SiStripPedestalsBuilder") << "... creating dummy SiStripPedestals Data for Run " << run << "\n " << std::endl; - SiStripPedestals* obj = new SiStripPedestals(); + SiStripPedestals obj; int count = -1; for (const auto& it : SiStripDetInfoFileReader::read(fp_.fullPath()).getAllData()) { @@ -30,11 +30,11 @@ void SiStripPedestalsBuilder::analyze(const edm::Event& evt, const edm::EventSet if (count < static_cast(printdebug_)) edm::LogInfo("SiStripPedestalsBuilder") << "detid " << it.first << " \t" << " strip " << strip << " \t" << ped << " \t" << std::endl; - obj->setData(ped, theSiStripVector); + obj.setData(ped, theSiStripVector); } //SiStripPedestals::Range range(theSiStripVector.begin(),theSiStripVector.end()); - if (!obj->put(it.first, theSiStripVector)) + if (!obj.put(it.first, theSiStripVector)) edm::LogError("SiStripPedestalsBuilder") << "[SiStripPedestalsBuilder::analyze] detid already exists" << std::endl; } @@ -44,11 +44,10 @@ void SiStripPedestalsBuilder::analyze(const edm::Event& evt, const edm::EventSet if (mydbservice.isAvailable()) { if (mydbservice->isNewTagRequest("SiStripPedestalsRcd")) { - mydbservice->createNewIOV( - obj, mydbservice->beginOfTime(), mydbservice->endOfTime(), "SiStripPedestalsRcd"); + mydbservice->createOneIOV(obj, mydbservice->beginOfTime(), "SiStripPedestalsRcd"); } else { //mydbservice->createNewIOV(obj,mydbservice->currentTime(),"SiStripPedestalsRcd"); - mydbservice->appendSinceTime(obj, mydbservice->currentTime(), "SiStripPedestalsRcd"); + mydbservice->appendOneIOV(obj, mydbservice->currentTime(), "SiStripPedestalsRcd"); } } else { edm::LogError("SiStripPedestalsBuilder") << "Service is unavailable" << std::endl; diff --git a/CondTools/SiStrip/plugins/SiStripSummaryBuilder.cc b/CondTools/SiStrip/plugins/SiStripSummaryBuilder.cc index 6f97ae269dd36..8b76ceb33d0d8 100644 --- a/CondTools/SiStrip/plugins/SiStripSummaryBuilder.cc +++ b/CondTools/SiStrip/plugins/SiStripSummaryBuilder.cc @@ -13,8 +13,8 @@ void SiStripSummaryBuilder::analyze(const edm::Event& evt, const edm::EventSetup edm::LogInfo("SiStripSummaryBuilder") << "... creating dummy SiStripSummary Data for Run " << run << "\n " << std::endl; - SiStripSummary* obj = new SiStripSummary(); - obj->setRunNr(run); + SiStripSummary obj; + obj.setRunNr(run); //* DISCOVER SET OF HISTOGRAMS & QUANTITIES TO BE UPLOADED*// @@ -51,12 +51,12 @@ void SiStripSummaryBuilder::analyze(const edm::Event& evt, const edm::EventSetup } } } - obj->setUserDBContent(userDBContent); + obj.setUserDBContent(userDBContent); std::stringstream ss1; ss1 << "QUANTITIES TO BE INSERTED IN DB :" << " \n"; - std::vector userDBContentA = obj->getUserDBContent(); + std::vector userDBContentA = obj.getUserDBContent(); for (size_t i = 0; i < userDBContentA.size(); ++i) ss1 << userDBContentA[i] << std::endl; edm::LogInfo("SiStripSummaryBuilder") << ss1.str(); @@ -73,7 +73,7 @@ void SiStripSummaryBuilder::analyze(const edm::Event& evt, const edm::EventSetup for (size_t j = 0; j < values.size(); ++j) ss2 << "\n\t\t " << userDBContent[j] << " " << values[j]; - obj->put(detid, values, userDBContent); + obj.put(detid, values, userDBContent); // See CondFormats/SiStripObjects/SiStripSummary.h for detid definitions @@ -103,10 +103,9 @@ void SiStripSummaryBuilder::analyze(const edm::Event& evt, const edm::EventSetup if (mydbservice.isAvailable()) { if (mydbservice->isNewTagRequest("SiStripSummaryRcd")) { - mydbservice->createNewIOV( - obj, mydbservice->beginOfTime(), mydbservice->endOfTime(), "SiStripSummaryRcd"); + mydbservice->createOneIOV(obj, mydbservice->beginOfTime(), "SiStripSummaryRcd"); } else { - mydbservice->appendSinceTime(obj, mydbservice->currentTime(), "SiStripSummaryRcd"); + mydbservice->appendOneIOV(obj, mydbservice->currentTime(), "SiStripSummaryRcd"); } } else { edm::LogError("SiStripSummaryBuilder") << "Service is unavailable" << std::endl; diff --git a/CondTools/SiStrip/plugins/SiStripThresholdBuilder.cc b/CondTools/SiStrip/plugins/SiStripThresholdBuilder.cc index 0ab00548e345c..5d3439d5ce4cd 100644 --- a/CondTools/SiStrip/plugins/SiStripThresholdBuilder.cc +++ b/CondTools/SiStrip/plugins/SiStripThresholdBuilder.cc @@ -14,7 +14,7 @@ void SiStripThresholdBuilder::analyze(const edm::Event& evt, const edm::EventSet edm::LogInfo("SiStripThresholdBuilder") << "... creating dummy SiStripThreshold Data for Run " << run << "\n " << std::endl; - SiStripThreshold* obj = new SiStripThreshold(); + SiStripThreshold obj; int count = -1; for (const auto& it : SiStripDetInfoFileReader::read(fp_.fullPath()).getAllData()) { @@ -32,7 +32,7 @@ void SiStripThresholdBuilder::analyze(const edm::Event& evt, const edm::EventSet } float cTh = (CLHEP::RandFlat::shoot(1.) * 30.); - obj->setData(strip, lTh, hTh, cTh, theSiStripVector); + obj.setData(strip, lTh, hTh, cTh, theSiStripVector); if (count < (int)printdebug_) { std::stringstream ss; theSiStripVector.back().print(ss); @@ -45,10 +45,10 @@ void SiStripThresholdBuilder::analyze(const edm::Event& evt, const edm::EventSet << "FirstStrip_and_Hth: " << theSiStripVector.back().FirstStrip_and_Hth << " \n" << ss.str() << std::endl; } - obj->setData(strip + 1, lTh, hTh, theSiStripVector); + obj.setData(strip + 1, lTh, hTh, theSiStripVector); strip = (uint16_t)(CLHEP::RandFlat::shoot(strip + 2, 128 * it.second.nApvs)); } - if (!obj->put(it.first, theSiStripVector)) + if (!obj.put(it.first, theSiStripVector)) edm::LogError("SiStripThresholdBuilder") << "[SiStripThresholdBuilder::analyze] detid already exists" << std::endl; } @@ -58,10 +58,9 @@ void SiStripThresholdBuilder::analyze(const edm::Event& evt, const edm::EventSet if (mydbservice.isAvailable()) { if (mydbservice->isNewTagRequest("SiStripThresholdRcd")) { - mydbservice->createNewIOV( - obj, mydbservice->beginOfTime(), mydbservice->endOfTime(), "SiStripThresholdRcd"); + mydbservice->createOneIOV(obj, mydbservice->beginOfTime(), "SiStripThresholdRcd"); } else { - mydbservice->appendSinceTime(obj, mydbservice->currentTime(), "SiStripThresholdRcd"); + mydbservice->appendOneIOV(obj, mydbservice->currentTime(), "SiStripThresholdRcd"); } } else { edm::LogError("SiStripThresholdBuilder") << "Service is unavailable" << std::endl; diff --git a/Configuration/AlCa/python/autoCond.py b/Configuration/AlCa/python/autoCond.py index fd7bcda098947..babae05777c2c 100644 --- a/Configuration/AlCa/python/autoCond.py +++ b/Configuration/AlCa/python/autoCond.py @@ -8,77 +8,75 @@ # GlobalTag for MC production (Heavy Ions collisions) with realistic alignment and calibrations for Run1 'run1_mc_hi' : '121X_mcRun1_HeavyIon_v7', # GlobalTag for MC production with pessimistic alignment and calibrations for Run2 - 'run2_mc_50ns' : '121X_mcRun2_startup_v6', + 'run2_mc_50ns' : '121X_mcRun2_startup_v8', # GlobalTag for MC production (2015 L1 Trigger Stage1) with startup-like alignment and calibrations for Run2, L1 trigger in Stage1 mode - 'run2_mc_l1stage1' : '121X_mcRun2_asymptotic_l1stage1_v6', + 'run2_mc_l1stage1' : '121X_mcRun2_asymptotic_l1stage1_v8', # GlobalTag for MC production with perfectly aligned and calibrated detector for Run2 - 'run2_design' : '121X_mcRun2_design_v6', + 'run2_design' : '121X_mcRun2_design_v8', #GlobalTag for MC production with optimistic alignment and calibrations for 2016, prior to VFP change - 'run2_mc_pre_vfp' : '121X_mcRun2_asymptotic_preVFP_v6', + 'run2_mc_pre_vfp' : '121X_mcRun2_asymptotic_preVFP_v8', #GlobalTag for MC production with optimistic alignment and calibrations for 2016, after VFP change - 'run2_mc' : '121X_mcRun2_asymptotic_v6', + 'run2_mc' : '121X_mcRun2_asymptotic_v8', # GlobalTag for MC production (cosmics) with starup-like alignment and calibrations for Run2, Strip tracker in peak mode - 'run2_mc_cosmics' : '121X_mcRun2cosmics_asymptotic_deco_v6', + 'run2_mc_cosmics' : '121X_mcRun2cosmics_asymptotic_deco_v8', # GlobalTag for MC production (Heavy Ions collisions) with optimistic alignment and calibrations for Run2 - 'run2_mc_hi' : '121X_mcRun2_HeavyIon_v6', + 'run2_mc_hi' : '121X_mcRun2_HeavyIon_v8', # GlobalTag for MC production (p-Pb collisions) with realistic alignment and calibrations for Run2 - 'run2_mc_pa' : '121X_mcRun2_pA_v6', + 'run2_mc_pa' : '121X_mcRun2_pA_v8', # GlobalTag for Run2 data reprocessing - 'run2_data' : '121X_dataRun2_v5', + 'run2_data' : '121X_dataRun2_v11', # GlobalTag for Run2 data 2018B relvals only: HEM-15-16 fail - 'run2_data_HEfail' : '121X_dataRun2_HEfail_v5', + 'run2_data_HEfail' : '121X_dataRun2_HEfail_v11', # GlobalTag for Run2 data relvals: allows customization to run with fixed L1 menu - 'run2_data_relval' : '121X_dataRun2_relval_v5', + 'run2_data_relval' : '121X_dataRun2_relval_v11', # GlobalTag for Run2 HI data - 'run2_data_promptlike_hi' : '121X_dataRun2_PromptLike_HI_v5', + 'run2_data_promptlike_hi' : '121X_dataRun2_PromptLike_HI_v10', # GlobalTag for Run3 HLT: it points to the online GT - 'run3_hlt' : '120X_dataRun3_HLT_v3', + 'run3_hlt' : '121X_dataRun3_HLT_v11', # GlobalTag with fixed snapshot time for Run2 HLT RelVals: customizations to run with fixed L1 Menu - 'run2_hlt_relval' : '121X_dataRun2_HLT_relval_v5', + 'run2_hlt_relval' : '121X_dataRun2_HLT_relval_v11', # GlobalTag for Run3 data relvals (express GT) - 'run3_data_express' : '120X_dataRun3_Express_v2', + 'run3_data_express' : '121X_dataRun3_Express_v11', # GlobalTag for Run3 data relvals - 'run3_data_prompt' : '120X_dataRun3_Prompt_v2', + 'run3_data_prompt' : '121X_dataRun3_Prompt_v10', # GlobalTag for Run3 offline data reprocessing - 'run3_data' : '121X_dataRun3_v5', + 'run3_data' : '121X_dataRun3_v10', # GlobalTag for MC production with perfectly aligned and calibrated detector for Phase1 2017 (and 0,0,~0-centred beamspot) - 'phase1_2017_design' : '121X_mc2017_design_v6', + 'phase1_2017_design' : '121X_mc2017_design_v9', # GlobalTag for MC production with realistic conditions for Phase1 2017 detector - 'phase1_2017_realistic' : '121X_mc2017_realistic_v6', - # GlobalTag for MC production with realistic conditions for Phase1 2017 detector, for PP reference run - 'phase1_2017_realistic_ppref' : '120X_mc2017_realistic_forppRef5TeV_v2', + 'phase1_2017_realistic' : '121X_mc2017_realistic_v9', # GlobalTag for MC production (cosmics) with realistic alignment and calibrations for Phase1 2017 detector, Strip tracker in DECO mode - 'phase1_2017_cosmics' : '121X_mc2017cosmics_realistic_deco_v6', + 'phase1_2017_cosmics' : '121X_mc2017cosmics_realistic_deco_v9', # GlobalTag for MC production (cosmics) with realistic alignment and calibrations for Phase1 2017 detector, Strip tracker in PEAK mode - 'phase1_2017_cosmics_peak' : '121X_mc2017cosmics_realistic_peak_v6', + 'phase1_2017_cosmics_peak' : '121X_mc2017cosmics_realistic_peak_v9', # GlobalTag for MC production with perfectly aligned and calibrated detector for full Phase1 2018 (and 0,0,0-centred beamspot) - 'phase1_2018_design' : '121X_upgrade2018_design_v6', + 'phase1_2018_design' : '121X_upgrade2018_design_v8', # GlobalTag for MC production with realistic conditions for full Phase1 2018 detector - 'phase1_2018_realistic' : '121X_upgrade2018_realistic_v6', + 'phase1_2018_realistic' : '121X_upgrade2018_realistic_v8', # GlobalTag for MC production with realistic run-dependent (RD) conditions for full Phase1 2018 detector - 'phase1_2018_realistic_rd' : '121X_upgrade2018_realistic_RD_v6', + 'phase1_2018_realistic_rd' : '121X_upgrade2018_realistic_RD_v8', # GlobalTag for MC production with realistic conditions for full Phase1 2018 detector for Heavy Ion - 'phase1_2018_realistic_hi' : '121X_upgrade2018_realistic_HI_v6', + 'phase1_2018_realistic_hi' : '121X_upgrade2018_realistic_HI_v8', # GlobalTag for MC production with realistic conditions for full Phase1 2018 detector: HEM-15-16 fail - 'phase1_2018_realistic_HEfail' : '121X_upgrade2018_realistic_HEfail_v6', + 'phase1_2018_realistic_HEfail' : '121X_upgrade2018_realistic_HEfail_v8', # GlobalTag for MC production (cosmics) with realistic conditions for full Phase1 2018 detector, Strip tracker in DECO mode - 'phase1_2018_cosmics' : '121X_upgrade2018cosmics_realistic_deco_v8', + 'phase1_2018_cosmics' : '121X_upgrade2018cosmics_realistic_deco_v10', # GlobalTag for MC production (cosmics) with realistic conditions for full Phase1 2018 detector, Strip tracker in PEAK mode - 'phase1_2018_cosmics_peak' : '121X_upgrade2018cosmics_realistic_peak_v6', + 'phase1_2018_cosmics_peak' : '121X_upgrade2018cosmics_realistic_peak_v8', # GlobalTag for MC production with perfectly aligned and calibrated detector for Phase1 2021 - 'phase1_2021_design' : '121X_mcRun3_2021_design_v10', + 'phase1_2021_design' : '121X_mcRun3_2021_design_v16', # GlobalTag for MC production with realistic conditions for Phase1 2021 - 'phase1_2021_realistic' : '121X_mcRun3_2021_realistic_v12', + 'phase1_2021_realistic' : '121X_mcRun3_2021_realistic_v18', # GlobalTag for MC production (cosmics) with realistic conditions for Phase1 2021, Strip tracker in DECO mode - 'phase1_2021_cosmics' : '121X_mcRun3_2021cosmics_realistic_deco_v12', + 'phase1_2021_cosmics' : '121X_mcRun3_2021cosmics_realistic_deco_v18', # GlobalTag for MC production with realistic conditions for Phase1 2021 detector for Heavy Ion - 'phase1_2021_realistic_hi' : '121X_mcRun3_2021_realistic_HI_v12', + 'phase1_2021_realistic_hi' : '121X_mcRun3_2021_realistic_HI_v18', # GlobalTag for MC production with realistic conditions for Phase1 2023 - 'phase1_2023_realistic' : '121X_mcRun3_2023_realistic_v11', + 'phase1_2023_realistic' : '121X_mcRun3_2023_realistic_v17', # GlobalTag for MC production with realistic conditions for Phase1 2024 - 'phase1_2024_realistic' : '121X_mcRun3_2024_realistic_v11', + 'phase1_2024_realistic' : '121X_mcRun3_2024_realistic_v17', # GlobalTag for MC production with realistic conditions for Phase2 - 'phase2_realistic' : '121X_mcRun4_realistic_v6' + 'phase2_realistic' : '121X_mcRun4_realistic_v8' } aliases = { @@ -108,9 +106,14 @@ from Configuration.AlCa.autoCondModifiers import autoCondHLTHI autoCond = autoCondHLTHI(autoCond) -# special GT for 2021 DD4HEP geometry -from Configuration.AlCa.autoCondModifiers import autoCondDD4HEP -autoCond = autoCondDD4HEP(autoCond) +# special GT for Run3 DDD geometry +from Configuration.AlCa.autoCondModifiers import autoCondDDD +autoCond = autoCondDDD(autoCond) + +# special GT for 2017 ppRef 5 TeV +from Configuration.AlCa.autoCondModifiers import autoCond2017ppRef5TeV +autoCond = autoCond2017ppRef5TeV(autoCond) + ### OLD KEYS ### kept for backward compatibility # GlobalTag for MC production with perfectly aligned and calibrated detector diff --git a/Configuration/AlCa/python/autoCondModifiers.py b/Configuration/AlCa/python/autoCondModifiers.py index 710fe1b75213d..a3bfa964e7e25 100644 --- a/Configuration/AlCa/python/autoCondModifiers.py +++ b/Configuration/AlCa/python/autoCondModifiers.py @@ -31,43 +31,66 @@ def autoCondHLTHI(autoCond): autoCond.update(GlobalTagsHLTHI) return autoCond -def autoCondDD4HEP(autoCond): +def autoCondDDD(autoCond): - GlobalTagsDDHEP = {} - # substitute the DDD geometry tags with DD4HEP ones - CSCRECODIGI_Geometry_dd4hep = ','.join( ['CSCRECODIGI_Geometry_120DD4hepV1' , "CSCRecoDigiParametersRcd", connectionString, "", "2021-09-28 12:00:00.000"] ) - CSCRECO_Geometry_dd4hep = ','.join( ['CSCRECO_Geometry_120DD4hepV1' , "CSCRecoGeometryRcd" , connectionString, "", "2021-09-28 12:00:00.000"] ) - DTRECO_Geometry_dd4hep = ','.join( ['DTRECO_Geometry_120DD4hepV1' , "DTRecoGeometryRcd" , connectionString, "", "2021-09-28 12:00:00.000"] ) - GEMRECO_Geometry_dd4hep = ','.join( ['GEMRECO_Geometry_120DD4hepV1' , "GEMRecoGeometryRcd" , connectionString, "", "2021-09-28 12:00:00.000"] ) - XMLFILE_Geometry_dd4hep = ','.join( ['XMLFILE_Geometry_121DD4hepV1_Extended2021_mc', "GeometryFileRcd" , connectionString, "Extended", "2021-09-28 12:00:00.000"] ) - HCALParameters_Geometry_dd4hep = ','.join( ['HCALParameters_Geometry_120DD4hepV1' , "HcalParametersRcd" , connectionString, "", "2021-09-28 12:00:00.000"] ) - TKRECO_Geometry_dd4hep = ','.join( ['TKRECO_Geometry_121DD4hepV1' , "IdealGeometryRecord" , connectionString, "", "2021-09-28 12:00:00.000"] ) - CTRECO_Geometry_dd4hep = ','.join( ['CTRECO_Geometry_120DD4hepV1' , "PCaloTowerRcd" , connectionString, "", "2021-09-28 12:00:00.000"] ) - EBRECO_Geometry_dd4hep = ','.join( ['EBRECO_Geometry_120DD4hepV1' , "PEcalBarrelRcd" , connectionString, "", "2021-09-28 12:00:00.000"] ) - EERECO_Geometry_dd4hep = ','.join( ['EERECO_Geometry_120DD4hepV1' , "PEcalEndcapRcd" , connectionString, "", "2021-09-28 12:00:00.000"] ) - EPRECO_Geometry_dd4hep = ','.join( ['EPRECO_Geometry_120DD4hepV1' , "PEcalPreshowerRcd" , connectionString, "", "2021-09-28 12:00:00.000"] ) - HCALRECO_Geometry_dd4hep = ','.join( ['HCALRECO_Geometry_120DD4hepV1' , "PHcalRcd" , connectionString, "", "2021-09-28 12:00:00.000"] ) - TKParameters_Geometry_dd4hep = ','.join( ['TKParameters_Geometry_120DD4hepV1' , "PTrackerParametersRcd" , connectionString, "", "2021-09-28 12:00:00.000"] ) - ZDCRECO_Geometry_dd4hep = ','.join( ['ZDCRECO_Geometry_120DD4hepV1' , "PZdcRcd" , connectionString, "", "2021-09-28 12:00:00.000"] ) - RPCRECO_Geometry_dd4hep = ','.join( ['RPCRECO_Geometry_120DD4hepV1' , "RPCRecoGeometryRcd" , connectionString, "", "2021-09-28 12:00:00.000"] ) + GlobalTagsDDD = {} + # substitute the DD4hep geometry tags with DDD ones + CSCRECODIGI_Geometry_ddd = ','.join( ['CSCRECODIGI_Geometry_112YV2' , "CSCRecoDigiParametersRcd", connectionString, "", "2021-09-28 12:00:00.000"] ) + CSCRECO_Geometry_ddd = ','.join( ['CSCRECO_Geometry_112YV2' , "CSCRecoGeometryRcd" , connectionString, "", "2021-09-28 12:00:00.000"] ) + DTRECO_Geometry_ddd = ','.join( ['DTRECO_Geometry_112YV2' , "DTRecoGeometryRcd" , connectionString, "", "2021-09-28 12:00:00.000"] ) + GEMRECO_Geometry_ddd = ','.join( ['GEMRECO_Geometry_113YV4' , "GEMRecoGeometryRcd" , connectionString, "", "2021-09-28 12:00:00.000"] ) + XMLFILE_Geometry_ddd = ','.join( ['XMLFILE_Geometry_121YV1_Extended2021_mc', "GeometryFileRcd" , connectionString, "Extended", "2021-09-28 12:00:00.000"] ) + HCALParameters_Geometry_ddd = ','.join( ['HCALParameters_Geometry_112YV2' , "HcalParametersRcd" , connectionString, "", "2021-09-28 12:00:00.000"] ) + TKRECO_Geometry_ddd = ','.join( ['TKRECO_Geometry_120YV2' , "IdealGeometryRecord" , connectionString, "", "2021-09-28 12:00:00.000"] ) + CTRECO_Geometry_ddd = ','.join( ['CTRECO_Geometry_112YV2' , "PCaloTowerRcd" , connectionString, "", "2021-09-28 12:00:00.000"] ) + EBRECO_Geometry_ddd = ','.join( ['EBRECO_Geometry_112YV2' , "PEcalBarrelRcd" , connectionString, "", "2021-09-28 12:00:00.000"] ) + EERECO_Geometry_ddd = ','.join( ['EERECO_Geometry_112YV2' , "PEcalEndcapRcd" , connectionString, "", "2021-09-28 12:00:00.000"] ) + EPRECO_Geometry_ddd = ','.join( ['EPRECO_Geometry_112YV2' , "PEcalPreshowerRcd" , connectionString, "", "2021-09-28 12:00:00.000"] ) + HCALRECO_Geometry_ddd = ','.join( ['HCALRECO_Geometry_112YV2' , "PHcalRcd" , connectionString, "", "2021-09-28 12:00:00.000"] ) + TKParameters_Geometry_ddd = ','.join( ['TKParameters_Geometry_112YV2' , "PTrackerParametersRcd" , connectionString, "", "2021-09-28 12:00:00.000"] ) + ZDCRECO_Geometry_ddd = ','.join( ['ZDCRECO_Geometry_112YV2' , "PZdcRcd" , connectionString, "", "2021-09-28 12:00:00.000"] ) + RPCRECO_Geometry_ddd = ','.join( ['RPCRECO_Geometry_112YV2' , "RPCRecoGeometryRcd" , connectionString, "", "2021-09-28 12:00:00.000"] ) for key,val in autoCond.items(): - if key == 'phase1_2021_realistic': # modification of the DD4HEP relval GT - GlobalTagsDDHEP['phase1_2021_dd4hep'] = (autoCond[key], - CSCRECODIGI_Geometry_dd4hep, - CSCRECO_Geometry_dd4hep, - DTRECO_Geometry_dd4hep, - GEMRECO_Geometry_dd4hep, - XMLFILE_Geometry_dd4hep, - HCALParameters_Geometry_dd4hep, - TKRECO_Geometry_dd4hep, - CTRECO_Geometry_dd4hep, - EBRECO_Geometry_dd4hep, - EERECO_Geometry_dd4hep, - EPRECO_Geometry_dd4hep, - HCALRECO_Geometry_dd4hep, - TKParameters_Geometry_dd4hep, - ZDCRECO_Geometry_dd4hep, - RPCRECO_Geometry_dd4hep) - autoCond.update(GlobalTagsDDHEP) + if 'phase1_202' in key: # modification of the DDD relval GT + GlobalTagsDDD[key+'_ddd'] = (autoCond[key], + CSCRECODIGI_Geometry_ddd, + CSCRECO_Geometry_ddd, + DTRECO_Geometry_ddd, + GEMRECO_Geometry_ddd, + XMLFILE_Geometry_ddd, + HCALParameters_Geometry_ddd, + TKRECO_Geometry_ddd, + CTRECO_Geometry_ddd, + EBRECO_Geometry_ddd, + EERECO_Geometry_ddd, + EPRECO_Geometry_ddd, + HCALRECO_Geometry_ddd, + TKParameters_Geometry_ddd, + ZDCRECO_Geometry_ddd, + RPCRECO_Geometry_ddd) + autoCond.update(GlobalTagsDDD) + return autoCond + +def autoCond2017ppRef5TeV(autoCond): + + GlobalTag2017ppRef5TeV = {} + # substitute tags needed for 2017 ppRef 5 TeV GT + BeamSpotObjects_2017ppRef5TeV = ','.join( ['BeamSpotObjects_pp_2017G_MC_2021sample_for_UL' , "BeamSpotObjectsRcd", connectionString, "", "2021-10-28 12:00:00.000"] ) + EcalLaserAPDPNRatios_2017ppRef5TeV = ','.join( ['EcalLaserAPDPNRatios_mc_Run2017G_306580' , "EcalLaserAPDPNRatiosRcd", connectionString, "", "2021-10-28 12:00:00.000"] ) + EcalPedestals_2017ppRef5TeV = ','.join( ['EcalPedestals_Run2017G_306580' , "EcalPedestalsRcd", connectionString, "", "2021-10-28 12:00:00.000"] ) + EcalTPGLinearizationConst_2017ppRef5TeV = ','.join( ['EcalTPGLinearizationConst_Run2017G_306580' , "EcalTPGLinearizationConstRcd", connectionString, "", "2021-10-28 12:00:00.000"] ) + EcalTPGPedestals_2017ppRef5TeV = ','.join( ['EcalTPGPedestals_Run2017G_306580' , "EcalTPGPedestalsRcd", connectionString, "", "2021-10-28 12:00:00.000"] ) + L1Menu_2017ppRef5TeV = ','.join( ['L1Menu_pp502Collisions2017_v4_m6_xml' , "L1TUtmTriggerMenuRcd", connectionString, "", "2021-10-28 12:00:00.000"] ) + + for key,val in autoCond.items(): + if 'phase1_2017_realistic' in key: + GlobalTag2017ppRef5TeV[key+'_ppref'] = (autoCond[key], + BeamSpotObjects_2017ppRef5TeV, + EcalLaserAPDPNRatios_2017ppRef5TeV, + EcalPedestals_2017ppRef5TeV, + EcalTPGLinearizationConst_2017ppRef5TeV, + EcalTPGPedestals_2017ppRef5TeV, + L1Menu_2017ppRef5TeV) + autoCond.update(GlobalTag2017ppRef5TeV) return autoCond diff --git a/Configuration/AlCa/python/autoPCL.py b/Configuration/AlCa/python/autoPCL.py index 0876ddef0fc4c..c39f1fadff178 100644 --- a/Configuration/AlCa/python/autoPCL.py +++ b/Configuration/AlCa/python/autoPCL.py @@ -10,5 +10,6 @@ 'PromptCalibProdEcalPedestals': 'EcalPedestals', 'PromptCalibProdLumiPCC': 'LumiPCC', 'PromptCalibProdPPS' : 'PPSTimingCalibration', - 'PromptCalibProdPPSDiamondSampic' : 'PPSDiamondSampicTimingCalibration' + 'PromptCalibProdPPSDiamondSampic' : 'PPSDiamondSampicTimingCalibration', + 'PromptCalibProdPPSAlig' : 'PPSAlignment' } diff --git a/Configuration/Applications/python/ConfigBuilder.py b/Configuration/Applications/python/ConfigBuilder.py index 4c40035cdb79e..6a83d34958e97 100644 --- a/Configuration/Applications/python/ConfigBuilder.py +++ b/Configuration/Applications/python/ConfigBuilder.py @@ -252,6 +252,7 @@ def __init__(self, options, process = None, with_output = False, with_input = Fa self.create_process() self.define_Configs() self.schedule = list() + self.scheduleIndexOfFirstHLTPath = None # we are doing three things here: # creating a process to catch errors @@ -1525,7 +1526,6 @@ def prepare_L1REPACK(self, sequence = None): print("L1REPACK with '",sequence,"' is not supported! Supported choices are: ",supported) raise Exception('unsupported feature') - def prepare_HLT(self, sequence = None): """ Enrich the schedule with the HLT simulation step""" if not sequence: @@ -1560,7 +1560,7 @@ def prepare_HLT(self, sequence = None): else: self.executeAndRemember('process.loadHltConfiguration("%s",%s)'%(sequence.replace(',',':'),optionsForHLTConfig)) else: - self.loadAndRemember('HLTrigger/Configuration/HLT_%s_cff' % sequence) + self.loadAndRemember('HLTrigger/Configuration/HLT_%s_cff' % sequence) if self._options.isMC: self._options.customisation_file.append("HLTrigger/Configuration/customizeHLTforMC.customizeHLTforMC") @@ -1572,10 +1572,13 @@ def prepare_HLT(self, sequence = None): from HLTrigger.Configuration.CustomConfigs import ProcessName self.process = ProcessName(self.process) - self.schedule.append(self.process.HLTSchedule) - [self.blacklist_paths.append(path) for path in self.process.HLTSchedule if isinstance(path,(cms.Path,cms.EndPath))] + if self.process.schedule == None: + raise Exception('the HLT step did not attach a valid schedule to the process') + + self.scheduleIndexOfFirstHLTPath = len(self.schedule) + [self.blacklist_paths.append(path) for path in self.process.schedule if isinstance(path,(cms.Path,cms.EndPath))] - #this is a fake, to be removed with fastim migration and HLT menu dump + # this is a fake, to be removed with fastim migration and HLT menu dump if self._options.fast: if not hasattr(self.process,'HLTEndSequence'): self.executeAndRemember("process.HLTEndSequence = cms.Sequence( process.dummyModule )") @@ -2241,27 +2244,29 @@ def prepare(self, doChecking = False): # dump the schedule self.pythonCfgCode += "\n# Schedule definition\n" - result = "process.schedule = cms.Schedule(" # handling of the schedule - self.process.schedule = cms.Schedule() - for item in self.schedule: - if not isinstance(item, cms.Schedule): + pathNames = ['process.'+p.label_() for p in self.schedule] + if self.process.schedule == None: + self.process.schedule = cms.Schedule() + for item in self.schedule: self.process.schedule.append(item) - else: - self.process.schedule.extend(item) - - if hasattr(self.process,"HLTSchedule"): - beforeHLT = self.schedule[:self.schedule.index(self.process.HLTSchedule)] - afterHLT = self.schedule[self.schedule.index(self.process.HLTSchedule)+1:] - pathNames = ['process.'+p.label_() for p in beforeHLT] - result += ','.join(pathNames)+')\n' - result += 'process.schedule.extend(process.HLTSchedule)\n' - pathNames = ['process.'+p.label_() for p in afterHLT] - result += 'process.schedule.extend(['+','.join(pathNames)+'])\n' + result = 'process.schedule = cms.Schedule('+','.join(pathNames)+')\n' else: - pathNames = ['process.'+p.label_() for p in self.schedule] - result ='process.schedule = cms.Schedule('+','.join(pathNames)+')\n' + if not isinstance(self.scheduleIndexOfFirstHLTPath, int): + raise Exception('the schedule was imported from a cff in HLTrigger.Configuration, but the final index of the first HLT path is undefined') + + for index, item in enumerate(self.schedule): + if index < self.scheduleIndexOfFirstHLTPath: + self.process.schedule.insert(index, item) + else: + self.process.schedule.append(item) + + result = "# process.schedule imported from cff in HLTrigger.Configuration\n" + for index, item in enumerate(pathNames[:self.scheduleIndexOfFirstHLTPath]): + result += 'process.schedule.insert('+str(index)+', '+item+')\n' + if self.scheduleIndexOfFirstHLTPath < len(pathNames): + result += 'process.schedule.extend(['+','.join(pathNames[self.scheduleIndexOfFirstHLTPath:])+'])\n' self.pythonCfgCode += result diff --git a/Configuration/Eras/python/Era_Phase2_cff.py b/Configuration/Eras/python/Era_Phase2_cff.py index b77860ca7414e..51e9a8d63cb3e 100644 --- a/Configuration/Eras/python/Era_Phase2_cff.py +++ b/Configuration/Eras/python/Era_Phase2_cff.py @@ -16,5 +16,6 @@ from Configuration.Eras.Modifier_phase2_timing_layer_cff import phase2_timing_layer from Configuration.Eras.Modifier_phase2_trigger_cff import phase2_trigger from Configuration.Eras.Modifier_ctpps_2021_cff import ctpps_2021 +from Configuration.ProcessModifiers.dd4hep_cff import dd4hep -Phase2 = cms.ModifierChain(Run3_noMkFit.copyAndExclude([phase1Pixel,trackingPhase1,ctpps_2021]), phase2_common, phase2_tracker, trackingPhase2PU140, phase2_ecal, phase2_hcal, phase2_hgcal, phase2_muon, phase2_GEM, hcalHardcodeConditions, phase2_timing, phase2_timing_layer, phase2_trigger) +Phase2 = cms.ModifierChain(Run3_noMkFit.copyAndExclude([phase1Pixel,trackingPhase1,ctpps_2021,dd4hep]), phase2_common, phase2_tracker, trackingPhase2PU140, phase2_ecal, phase2_hcal, phase2_hgcal, phase2_muon, phase2_GEM, hcalHardcodeConditions, phase2_timing, phase2_timing_layer, phase2_trigger) diff --git a/Configuration/Eras/python/Era_Run2_2016_cff.py b/Configuration/Eras/python/Era_Run2_2016_cff.py index b0100810f4af5..a1ed461c1d24d 100644 --- a/Configuration/Eras/python/Era_Run2_2016_cff.py +++ b/Configuration/Eras/python/Era_Run2_2016_cff.py @@ -13,7 +13,8 @@ from Configuration.Eras.Modifier_run2_jme_2016_cff import run2_jme_2016 from Configuration.Eras.Modifier_strips_vfp30_2016_cff import strips_vfp30_2016 from Configuration.Eras.Modifier_run2_ECAL_2016_cff import run2_ECAL_2016 +from Configuration.ProcessModifiers.trackingNoLoopers_cff import trackingNoLoopers Run2_2016 = cms.ModifierChain(run2_common, run2_25ns_specific, - stage2L1Trigger, ctpps, ctpps_2016, run2_HLTconditions_2016, run2_ECAL_2016, run2_muon_2016, run2_egamma_2016, run2_L1prefiring, pixel_2016, run2_jme_2016, strips_vfp30_2016) + stage2L1Trigger, ctpps, ctpps_2016, run2_HLTconditions_2016, run2_ECAL_2016, run2_muon_2016, run2_egamma_2016, run2_L1prefiring, pixel_2016, run2_jme_2016, strips_vfp30_2016, trackingNoLoopers) diff --git a/Configuration/Eras/python/Era_Run2_2016_pA_cff.py b/Configuration/Eras/python/Era_Run2_2016_pA_cff.py index 06b736d256f12..12e6ea7629d4c 100644 --- a/Configuration/Eras/python/Era_Run2_2016_pA_cff.py +++ b/Configuration/Eras/python/Era_Run2_2016_pA_cff.py @@ -2,6 +2,7 @@ from Configuration.Eras.Era_Run2_2016_cff import Run2_2016 from Configuration.Eras.Modifier_pA_2016_cff import pA_2016 +from Configuration.ProcessModifiers.trackingNoLoopers_cff import trackingNoLoopers -Run2_2016_pA = cms.ModifierChain(Run2_2016, pA_2016) +Run2_2016_pA = cms.ModifierChain(Run2_2016.copyAndExclude([trackingNoLoopers]), pA_2016) diff --git a/Configuration/Eras/python/Era_Run2_2017_cff.py b/Configuration/Eras/python/Era_Run2_2017_cff.py index f3edca7cba96f..5b418ba6d64ee 100644 --- a/Configuration/Eras/python/Era_Run2_2017_cff.py +++ b/Configuration/Eras/python/Era_Run2_2017_cff.py @@ -1,5 +1,5 @@ import FWCore.ParameterSet.Config as cms - +from Configuration.ProcessModifiers.trackdnn_cff import trackdnn from Configuration.Eras.Era_Run2_2016_cff import Run2_2016 from Configuration.Eras.Modifier_phase1Pixel_cff import phase1Pixel from Configuration.Eras.Modifier_run2_ECAL_2017_cff import run2_ECAL_2017 @@ -27,5 +27,5 @@ Run2_2017 = cms.ModifierChain(Run2_2016.copyAndExclude([run2_muon_2016, run2_HLTconditions_2016, run2_ECAL_2016, run2_egamma_2016,pixel_2016,run2_jme_2016, strips_vfp30_2016, ctpps_2016]), phase1Pixel, run2_ECAL_2017, run2_HF_2017, run2_HCAL_2017, run2_HE_2017, run2_HEPlan1_2017, - trackingPhase1, trackingMkFitProd, run2_GEM_2017, stage2L1Trigger_2017, run2_HLTconditions_2017, run2_muon_2017,run2_egamma_2017, ctpps_2017, run2_jme_2017) + trackingPhase1, trackdnn, trackingMkFitProd, run2_GEM_2017, stage2L1Trigger_2017, run2_HLTconditions_2017, run2_muon_2017,run2_egamma_2017, ctpps_2017, run2_jme_2017) diff --git a/Configuration/Eras/python/Era_Run2_2017_noMkFit_cff.py b/Configuration/Eras/python/Era_Run2_2017_noMkFit_cff.py new file mode 100644 index 0000000000000..5f16f54a8d542 --- /dev/null +++ b/Configuration/Eras/python/Era_Run2_2017_noMkFit_cff.py @@ -0,0 +1,6 @@ +import FWCore.ParameterSet.Config as cms +from Configuration.ProcessModifiers.trackdnn_CKF_cff import trackdnn_CKF +from Configuration.Eras.Era_Run2_2017_cff import Run2_2017 +from Configuration.Eras.ModifierChain_trackingMkFitProd_cff import trackingMkFitProd + +Run2_2017_noMkFit = cms.ModifierChain(Run2_2017.copyAndExclude([trackingMkFitProd]), trackdnn_CKF) diff --git a/Configuration/Eras/python/Era_Run2_2017_ppRef_cff.py b/Configuration/Eras/python/Era_Run2_2017_ppRef_cff.py index 480841cb46837..0a337f771e48e 100644 --- a/Configuration/Eras/python/Era_Run2_2017_ppRef_cff.py +++ b/Configuration/Eras/python/Era_Run2_2017_ppRef_cff.py @@ -3,5 +3,6 @@ from Configuration.Eras.Era_Run2_2017_cff import Run2_2017 from Configuration.Eras.Modifier_ppRef_2017_cff import ppRef_2017 from Configuration.Eras.ModifierChain_trackingMkFitProd_cff import trackingMkFitProd +from Configuration.ProcessModifiers.trackingNoLoopers_cff import trackingNoLoopers -Run2_2017_ppRef = cms.ModifierChain(Run2_2017.copyAndExclude([trackingMkFitProd]), ppRef_2017) +Run2_2017_ppRef = cms.ModifierChain(Run2_2017.copyAndExclude([trackingMkFitProd, trackingNoLoopers]), ppRef_2017) diff --git a/Configuration/Eras/python/Era_Run2_2017_pp_on_XeXe_cff.py b/Configuration/Eras/python/Era_Run2_2017_pp_on_XeXe_cff.py index 047cfbb2ee477..2b973a66c8f28 100644 --- a/Configuration/Eras/python/Era_Run2_2017_pp_on_XeXe_cff.py +++ b/Configuration/Eras/python/Era_Run2_2017_pp_on_XeXe_cff.py @@ -3,5 +3,6 @@ from Configuration.Eras.Era_Run2_2017_cff import Run2_2017 from Configuration.Eras.Modifier_pp_on_XeXe_2017_cff import pp_on_XeXe_2017 from Configuration.Eras.ModifierChain_trackingMkFitProd_cff import trackingMkFitProd +from Configuration.ProcessModifiers.trackingNoLoopers_cff import trackingNoLoopers -Run2_2017_pp_on_XeXe = cms.ModifierChain(Run2_2017.copyAndExclude([trackingMkFitProd]), pp_on_XeXe_2017) +Run2_2017_pp_on_XeXe = cms.ModifierChain(Run2_2017.copyAndExclude([trackingMkFitProd,trackingNoLoopers]), pp_on_XeXe_2017) diff --git a/Configuration/Eras/python/Era_Run2_2018_highBetaStar_cff.py b/Configuration/Eras/python/Era_Run2_2018_highBetaStar_cff.py index dd1aed83d7836..b4ae7aa5fd081 100644 --- a/Configuration/Eras/python/Era_Run2_2018_highBetaStar_cff.py +++ b/Configuration/Eras/python/Era_Run2_2018_highBetaStar_cff.py @@ -1,6 +1,6 @@ import FWCore.ParameterSet.Config as cms - +from Configuration.ProcessModifiers.trackdnn_cff import trackdnn from Configuration.Eras.Era_Run2_2018_cff import Run2_2018 from Configuration.Eras.Modifier_highBetaStar_2018_cff import highBetaStar_2018 -Run2_2018_highBetaStar = cms.ModifierChain(Run2_2018, highBetaStar_2018) +Run2_2018_highBetaStar = cms.ModifierChain(Run2_2018.copyAndExclude([trackdnn]), highBetaStar_2018) diff --git a/Configuration/Eras/python/Era_Run2_2018_noMkFit_cff.py b/Configuration/Eras/python/Era_Run2_2018_noMkFit_cff.py new file mode 100644 index 0000000000000..55fde3056b3ee --- /dev/null +++ b/Configuration/Eras/python/Era_Run2_2018_noMkFit_cff.py @@ -0,0 +1,6 @@ +import FWCore.ParameterSet.Config as cms +from Configuration.ProcessModifiers.trackdnn_CKF_cff import trackdnn_CKF +from Configuration.Eras.Era_Run2_2018_cff import Run2_2018 +from Configuration.Eras.ModifierChain_trackingMkFitProd_cff import trackingMkFitProd + +Run2_2018_noMkFit = cms.ModifierChain(Run2_2018.copyAndExclude([trackingMkFitProd]), trackdnn_CKF) diff --git a/Configuration/Eras/python/Era_Run2_2018_pp_on_AA_cff.py b/Configuration/Eras/python/Era_Run2_2018_pp_on_AA_cff.py index 50f6caac90be3..0245702c787b9 100644 --- a/Configuration/Eras/python/Era_Run2_2018_pp_on_AA_cff.py +++ b/Configuration/Eras/python/Era_Run2_2018_pp_on_AA_cff.py @@ -1,8 +1,10 @@ import FWCore.ParameterSet.Config as cms - +from Configuration.ProcessModifiers.trackdnn_cff import trackdnn from Configuration.Eras.Era_Run2_2018_cff import Run2_2018 from Configuration.ProcessModifiers.pp_on_AA_cff import pp_on_AA from Configuration.Eras.Modifier_pp_on_AA_2018_cff import pp_on_AA_2018 from Configuration.Eras.ModifierChain_trackingMkFitProd_cff import trackingMkFitProd +from Configuration.ProcessModifiers.trackingNoLoopers_cff import trackingNoLoopers + +Run2_2018_pp_on_AA = cms.ModifierChain(Run2_2018.copyAndExclude([trackingMkFitProd, trackdnn, trackingNoLoopers]), pp_on_AA, pp_on_AA_2018) -Run2_2018_pp_on_AA = cms.ModifierChain(Run2_2018.copyAndExclude([trackingMkFitProd]), pp_on_AA, pp_on_AA_2018) diff --git a/Configuration/Eras/python/Era_Run3_DDD_cff.py b/Configuration/Eras/python/Era_Run3_DDD_cff.py new file mode 100644 index 0000000000000..874d56a2d9e59 --- /dev/null +++ b/Configuration/Eras/python/Era_Run3_DDD_cff.py @@ -0,0 +1,7 @@ +import FWCore.ParameterSet.Config as cms + +from Configuration.Eras.Era_Run3_cff import Run3 +from Configuration.ProcessModifiers.dd4hep_cff import dd4hep + +Run3_DDD = Run3.copyAndExclude([dd4hep]) + diff --git a/Configuration/Eras/python/Era_Run3_cff.py b/Configuration/Eras/python/Era_Run3_cff.py index 05670459f6219..568bfb058b543 100644 --- a/Configuration/Eras/python/Era_Run3_cff.py +++ b/Configuration/Eras/python/Era_Run3_cff.py @@ -9,6 +9,7 @@ from Configuration.Eras.Modifier_stage2L1Trigger_2021_cff import stage2L1Trigger_2021 from Configuration.Eras.Modifier_ctpps_2018_cff import ctpps_2018 from Configuration.Eras.Modifier_ctpps_2021_cff import ctpps_2021 +from Configuration.ProcessModifiers.dd4hep_cff import dd4hep -Run3 = cms.ModifierChain(Run2_2018.copyAndExclude([run2_GEM_2017, ctpps_2018]), run3_common, run3_GEM, run3_HB, run3_HFSL, stage2L1Trigger_2021, ctpps_2021) +Run3 = cms.ModifierChain(Run2_2018.copyAndExclude([run2_GEM_2017, ctpps_2018]), run3_common, run3_GEM, run3_HB, run3_HFSL, stage2L1Trigger_2021, ctpps_2021, dd4hep) diff --git a/Configuration/Eras/python/Era_Run3_dd4hep_cff.py b/Configuration/Eras/python/Era_Run3_dd4hep_cff.py index 42ae535a85276..6154f8b5970a0 100644 --- a/Configuration/Eras/python/Era_Run3_dd4hep_cff.py +++ b/Configuration/Eras/python/Era_Run3_dd4hep_cff.py @@ -3,5 +3,6 @@ from Configuration.Eras.Era_Run3_cff import Run3 from Configuration.ProcessModifiers.dd4hep_cff import dd4hep -Run3_dd4hep = cms.ModifierChain(Run3, dd4hep) +#Run3 includes DD4hep as default starting from 12_1_0_pre5 +Run3_dd4hep = Run3 diff --git a/Configuration/Eras/python/Era_Run3_noMkFit_cff.py b/Configuration/Eras/python/Era_Run3_noMkFit_cff.py index 839d5e8299968..6cae044556261 100644 --- a/Configuration/Eras/python/Era_Run3_noMkFit_cff.py +++ b/Configuration/Eras/python/Era_Run3_noMkFit_cff.py @@ -1,6 +1,6 @@ import FWCore.ParameterSet.Config as cms - +from Configuration.ProcessModifiers.trackdnn_CKF_cff import trackdnn_CKF from Configuration.Eras.Era_Run3_cff import Run3 from Configuration.Eras.ModifierChain_trackingMkFitProd_cff import trackingMkFitProd -Run3_noMkFit = Run3.copyAndExclude([trackingMkFitProd]) +Run3_noMkFit = cms.ModifierChain(Run3.copyAndExclude([trackingMkFitProd]), trackdnn_CKF) diff --git a/Configuration/Eras/python/Era_Run3_pp_on_PbPb_cff.py b/Configuration/Eras/python/Era_Run3_pp_on_PbPb_cff.py index 097759b30e15c..329a644a289a0 100644 --- a/Configuration/Eras/python/Era_Run3_pp_on_PbPb_cff.py +++ b/Configuration/Eras/python/Era_Run3_pp_on_PbPb_cff.py @@ -1,7 +1,10 @@ import FWCore.ParameterSet.Config as cms - +from Configuration.ProcessModifiers.trackdnn_CKF_cff import trackdnn_CKF +from Configuration.ProcessModifiers.trackdnn_cff import trackdnn from Configuration.Eras.Era_Run3_noMkFit_cff import Run3_noMkFit from Configuration.ProcessModifiers.pp_on_AA_cff import pp_on_AA from Configuration.Eras.Modifier_pp_on_PbPb_run3_cff import pp_on_PbPb_run3 +from Configuration.ProcessModifiers.trackingNoLoopers_cff import trackingNoLoopers + +Run3_pp_on_PbPb = cms.ModifierChain(Run3_noMkFit.copyAndExclude([trackdnn, trackdnn_CKF, trackingNoLoopers]), pp_on_AA, pp_on_PbPb_run3) -Run3_pp_on_PbPb = cms.ModifierChain(Run3_noMkFit, pp_on_AA, pp_on_PbPb_run3) diff --git a/Configuration/Eras/python/ModifierChain_trackingMkFitProd_cff.py b/Configuration/Eras/python/ModifierChain_trackingMkFitProd_cff.py index 18f55b8ff947b..448e0cad2e17a 100644 --- a/Configuration/Eras/python/ModifierChain_trackingMkFitProd_cff.py +++ b/Configuration/Eras/python/ModifierChain_trackingMkFitProd_cff.py @@ -6,6 +6,8 @@ from Configuration.ProcessModifiers.trackingMkFitInitialStep_cff import * from Configuration.ProcessModifiers.trackingMkFitHighPtTripletStep_cff import * from Configuration.ProcessModifiers.trackingMkFitDetachedQuadStep_cff import * +from Configuration.ProcessModifiers.trackingMkFitDetachedTripletStep_cff import * +from Configuration.ProcessModifiers.trackingMkFitPixelLessStep_cff import * trackingMkFitProd = cms.ModifierChain( trackingMkFitCommon, @@ -13,4 +15,6 @@ trackingMkFitInitialStep, trackingMkFitHighPtTripletStep, trackingMkFitDetachedQuadStep, + trackingMkFitDetachedTripletStep, + trackingMkFitPixelLessStep, ) diff --git a/Configuration/EventContent/python/AlCaRecoOutput_cff.py b/Configuration/EventContent/python/AlCaRecoOutput_cff.py index 611adb9ba5b4b..835c8b99eaf70 100644 --- a/Configuration/EventContent/python/AlCaRecoOutput_cff.py +++ b/Configuration/EventContent/python/AlCaRecoOutput_cff.py @@ -149,6 +149,7 @@ from CalibPPS.TimingCalibration.ALCARECOPPSCalTrackBasedSel_Output_cff import * from CalibPPS.TimingCalibration.ALCARECOPPSTimingCalib_Output_cff import * from CalibPPS.TimingCalibration.ALCARECOPPSDiamondSampicTimingCalib_Output_cff import * +from CalibPPS.AlignmentGlobal.ALCARECOPPSAlignment_Output_cff import * ############################################################### # stream for prompt-calibration @ Tier0 diff --git a/Configuration/Generator/python/Chib1PToUpsilon1SGamma_MuFilter_TuneCP5_14TeV-pythia8_evtgen_cfi.py b/Configuration/Generator/python/Chib1PToUpsilon1SGamma_MuFilter_TuneCP5_14TeV-pythia8_evtgen_cfi.py new file mode 100644 index 0000000000000..173e0542c534b --- /dev/null +++ b/Configuration/Generator/python/Chib1PToUpsilon1SGamma_MuFilter_TuneCP5_14TeV-pythia8_evtgen_cfi.py @@ -0,0 +1,115 @@ +# cfg file for Chi_{b1,b2}(1P) -> Upsilon(1S) gamma, we are neglecting Chi_b0. Masses and widths are matched between pythia, evtgen and PDG 2016 +# +import FWCore.ParameterSet.Config as cms +from Configuration.Generator.Pythia8CommonSettings_cfi import * +from Configuration.Generator.MCTunes2017.PythiaCP5Settings_cfi import * + +generator = cms.EDFilter("Pythia8GeneratorFilter", + pythiaPylistVerbosity = cms.untracked.int32(0), + pythiaHepMCVerbosity = cms.untracked.bool(False), + maxEventsToPrint = cms.untracked.int32(0), + comEnergy = cms.double(14000.0), + ExternalDecays = cms.PSet( + EvtGen130 = cms.untracked.PSet( + decay_table = cms.string('GeneratorInterface/EvtGenInterface/data/DECAY_2014_NOLONGLIFE.DEC'), + particle_property_file = cms.FileInPath('GeneratorInterface/EvtGenInterface/data/evt_2014.pdl'), + list_forced_decays = cms.vstring('mychi_b1','mychi_b2'), # will force one at the time + operates_on_particles = cms.vint32(20553,555), # we care just about our signal particles + convertPythiaCodes = cms.untracked.bool(False), + user_decay_embedded= cms.vstring( +""" +Particle Upsilon 9.4603000 0.00005402 +Particle chi_b1 9.8927800 0.00000 +Particle chi_b2 9.9122100 0.00000 +Alias myUpsilon Upsilon +Alias mychi_b1 chi_b1 +Alias mychi_b2 chi_b2 +Decay myUpsilon +1.0 mu+ mu- PHOTOS VLL; +Enddecay +Decay mychi_b1 +1.0 gamma myUpsilon HELAMP 1. 0. 1. 0. -1. 0. -1. 0.; +Enddecay +Decay mychi_b2 +1.0 gamma myUpsilon PHSP; +Enddecay +End +""" + ) + ), + parameterSets = cms.vstring('EvtGen130') + ), + PythiaParameters = cms.PSet( + pythia8CommonSettingsBlock, + pythia8CP5SettingsBlock, + processParameters = cms.vstring( + 'Bottomonium:states(3PJ) = 20553,555', + 'Bottomonium:O(3PJ)[3P0(1)] = 0.085,0.085', + 'Bottomonium:O(3PJ)[3S1(8)] = 0.04,0.04', + 'Bottomonium:gg2bbbar(3PJ)[3PJ(1)]g = on,on', + 'Bottomonium:qg2bbbar(3PJ)[3PJ(1)]q = on,on', + 'Bottomonium:qqbar2bbbar(3PJ)[3PJ(1)]g = on,on', + 'Bottomonium:gg2bbbar(3PJ)[3S1(8)]g = on,on', + 'Bottomonium:qg2bbbar(3PJ)[3S1(8)]q = on,on', + 'Bottomonium:qqbar2bbbar(3PJ)[3S1(8)]g = on,on', + 'PhaseSpace:pTHatMin = 2.', + '20553:m0 = 9.89278', + '555:m0 = 9.91221', + '20553:onMode = off', + '555:onMode = off' + ), + parameterSets = cms.vstring('pythia8CommonSettings', + 'pythia8CP5Settings', + 'processParameters', + ) + ) +) + +# We will filter for chi_b1, and chi_b2, first on the ID, then in the mass, this will constraint the photon daughter + +pwaveIDfilter = cms.EDFilter("MCSingleParticleFilter", + ParticleID = cms.untracked.vint32(20553,555), + MinPt = cms.untracked.vdouble(0.0, 0.0), + MinEta = cms.untracked.vdouble(-9., -9.), + MaxEta = cms.untracked.vdouble(9., 9.), + Status = cms.untracked.vint32(2, 2) +) + +pwaveMassfilter = cms.EDFilter("MCParticlePairFilter", + Status = cms.untracked.vint32(2, 1), + MinPt = cms.untracked.vdouble(7.9, 0.2), + MaxEta = cms.untracked.vdouble(1.6, 1.6), + MinEta = cms.untracked.vdouble(-1.6, -1.6), + ParticleCharge = cms.untracked.int32(0), + MinP = cms.untracked.vdouble(0.,0.), + ParticleID1 = cms.untracked.vint32(553), + ParticleID2 = cms.untracked.vint32(22), + MinInvMass = cms.untracked.double(9.88), + MaxInvMass = cms.untracked.double(9.93), +) + +# Next two muon filter are derived from muon reconstruction + +muminusfilter = cms.EDFilter("PythiaDauVFilter", + MotherID = cms.untracked.int32(0), + MinPt = cms.untracked.vdouble(2.5, 2.5, 3.5), + ParticleID = cms.untracked.int32(553), + ChargeConjugation = cms.untracked.bool(False), + MinEta = cms.untracked.vdouble(1.2, -1.6, -1.2), + MaxEta = cms.untracked.vdouble(1.6, -1.2, 1.2), + NumberDaughters = cms.untracked.int32(1), + DaughterIDs = cms.untracked.vint32(-13, -13, -13) +) + +muplusfilter = cms.EDFilter("PythiaDauVFilter", + MotherID = cms.untracked.int32(0), + MinPt = cms.untracked.vdouble(2.5, 2.5, 3.5), + ParticleID = cms.untracked.int32(553), + ChargeConjugation = cms.untracked.bool(False), + MinEta = cms.untracked.vdouble(1.2, -1.6, -1.2), + MaxEta = cms.untracked.vdouble(1.6, -1.2, 1.2), + NumberDaughters = cms.untracked.int32(1), + DaughterIDs = cms.untracked.vint32(13, 13, 13) +) + +ProductionFilterSequence = cms.Sequence(generator*pwaveIDfilter*pwaveMassfilter*muminusfilter*muplusfilter) diff --git a/Configuration/Generator/python/ChicToJpsiGamma_MuFilter_TuneCP5_14TeV_pythia8_evtgen_cfi.py b/Configuration/Generator/python/ChicToJpsiGamma_MuFilter_TuneCP5_14TeV_pythia8_evtgen_cfi.py new file mode 100644 index 0000000000000..530c370cbefcf --- /dev/null +++ b/Configuration/Generator/python/ChicToJpsiGamma_MuFilter_TuneCP5_14TeV_pythia8_evtgen_cfi.py @@ -0,0 +1,79 @@ +import FWCore.ParameterSet.Config as cms +from Configuration.Generator.MCTunes2017.PythiaCP5Settings_cfi import * +from Configuration.Generator.Pythia8CommonSettings_cfi import * + +generator = cms.EDFilter("Pythia8GeneratorFilter", + pythiaPylistVerbosity = cms.untracked.int32(0), + pythiaHepMCVerbosity = cms.untracked.bool(False), + maxEventsToPrint = cms.untracked.int32(0), + comEnergy = cms.double(14000.0), + ExternalDecays = cms.PSet( + EvtGen130 = cms.untracked.PSet( + decay_table = cms.string('GeneratorInterface/EvtGenInterface/data/DECAY_2014_NOLONGLIFE.DEC'), + particle_property_file = cms.FileInPath('GeneratorInterface/EvtGenInterface/data/evt_2014.pdl'), + operates_on_particles = cms.vint32(20443,445), # we care just about our signal particles + convertPythiaCodes = cms.untracked.bool(False), + user_decay_file = cms.vstring('GeneratorInterface/ExternalDecays/data/Onia_chic_jpsigamma.dec'), + list_forced_decays = cms.vstring('Mychi_c1','Mychi_c2'), + ), + parameterSets = cms.vstring('EvtGen130') + ), + PythiaParameters = cms.PSet( + pythia8CommonSettingsBlock, + pythia8CP5SettingsBlock, + processParameters = cms.vstring( + # generate just the needed and nothing else + 'Charmonium:states(3PJ) = 20443,445', + 'Charmonium:O(3PJ)[3P0(1)] = 0.05,0.05', + 'Charmonium:O(3PJ)[3S1(8)] = 0.0031,0.0031', + 'Charmonium:gg2ccbar(3PJ)[3PJ(1)]g = on,on', + 'Charmonium:qg2ccbar(3PJ)[3PJ(1)]q = on,on', + 'Charmonium:qqbar2ccbar(3PJ)[3PJ(1)]g = on,on', + 'Charmonium:gg2ccbar(3PJ)[3S1(8)]g = on,on', + 'Charmonium:qg2ccbar(3PJ)[3S1(8)]q = on,on', + 'Charmonium:qqbar2ccbar(3PJ)[3S1(8)]g = on,on', +# + 'PhaseSpace:pTHatMin = 10.' # (filter efficiency 4.671e-02) be aware of this ckin(3) equivalent + ), + parameterSets = cms.vstring('pythia8CommonSettings', + 'pythia8CP5Settings', + 'processParameters', + ) + ) +) + +# Next two muon filter are derived from muon reconstruction +oniafilter = cms.EDFilter("MCParticlePairFilter", + Status = cms.untracked.vint32(2, 1), + MinPt = cms.untracked.vdouble(16., 0.2), + MaxEta = cms.untracked.vdouble(1.6, 1.6), + MinEta = cms.untracked.vdouble(-1.6, -1.6), + ParticleCharge = cms.untracked.int32(0), + MinP = cms.untracked.vdouble(0.,0.), + ParticleID1 = cms.untracked.vint32(443), + ParticleID2 = cms.untracked.vint32(22) +) + +muminusfilter = cms.EDFilter("PythiaDauVFilter", + MotherID = cms.untracked.int32(0), + MinPt = cms.untracked.vdouble(2.5, 2.5, 3.5), + ParticleID = cms.untracked.int32(443), + ChargeConjugation = cms.untracked.bool(False), + MinEta = cms.untracked.vdouble(1.2, -1.6, -1.2), + MaxEta = cms.untracked.vdouble(1.6, -1.2, 1.2), + NumberDaughters = cms.untracked.int32(1), + DaughterIDs = cms.untracked.vint32(-13, -13, -13) +) + +muplusfilter = cms.EDFilter("PythiaDauVFilter", + MotherID = cms.untracked.int32(0), + MinPt = cms.untracked.vdouble(2.5, 2.5, 3.5), + ParticleID = cms.untracked.int32(443), + ChargeConjugation = cms.untracked.bool(False), + MinEta = cms.untracked.vdouble(1.2, -1.6, -1.2), + MaxEta = cms.untracked.vdouble(1.6, -1.2, 1.2), + NumberDaughters = cms.untracked.int32(1), + DaughterIDs = cms.untracked.vint32(13, 13, 13) +) + +ProductionFilterSequence = cms.Sequence(generator*oniafilter*muminusfilter*muplusfilter) diff --git a/Configuration/Geometry/README.md b/Configuration/Geometry/README.md index 9c360b7004360..dd5c1ab82c9ae 100644 --- a/Configuration/Geometry/README.md +++ b/Configuration/Geometry/README.md @@ -98,6 +98,7 @@ The script also handles the common and forward elements of the geometry: * O6: same as O5 with changes needed for new defintion of boundaries * O7: same as O6 with changes needed for new defintion of calorimeter boundaries * O8: same as O7 with changes needed for a newer definition of calorimeter boundaries +* O9: same as O8 with changes needed to support the additional notch in ETL * F2: modifications needed to accommodate detailed cavern, ZDC description is removed. * F3: same as F2 but changes due to HFNose diff --git a/Configuration/Geometry/python/dict2026Geometry.py b/Configuration/Geometry/python/dict2026Geometry.py index b84940ef49003..f68319cadda04 100644 --- a/Configuration/Geometry/python/dict2026Geometry.py +++ b/Configuration/Geometry/python/dict2026Geometry.py @@ -139,6 +139,33 @@ ], "era" : "phase2_common, phase2_trigger", }, + "O9" : { + 1 : [ + 'Geometry/CMSCommonData/data/materials/2021/v1/materials.xml', + 'Geometry/CMSCommonData/data/rotations.xml', + 'Geometry/CMSCommonData/data/extend/v2/cmsextent.xml', + 'Geometry/CMSCommonData/data/cavernData/2021/v1/cavernData.xml', + 'Geometry/CMSCommonData/data/cms/2026/v5/cms.xml', + 'Geometry/CMSCommonData/data/cmsMother.xml', + 'Geometry/CMSCommonData/data/eta3/etaMax.xml', + 'Geometry/CMSCommonData/data/cmsTracker.xml', + 'Geometry/CMSCommonData/data/caloBase/2026/v7/caloBase.xml', + 'Geometry/CMSCommonData/data/cmsCalo.xml', + 'Geometry/CMSCommonData/data/muonBase/2026/v5/muonBase.xml', + 'Geometry/CMSCommonData/data/cmsMuon.xml', + 'Geometry/CMSCommonData/data/mgnt.xml', + 'Geometry/CMSCommonData/data/beampipe/2026/v3/beampipe.xml', + 'Geometry/CMSCommonData/data/cmsBeam/2026/v1/cmsBeam.xml', + 'Geometry/CMSCommonData/data/muonMB.xml', + 'Geometry/CMSCommonData/data/muonMagnet.xml', + 'Geometry/CMSCommonData/data/cavern/2021/v1/cavern.xml', + 'Geometry/CMSCommonData/data/cavernFloor/2017/v1/cavernFloor.xml', + ], + 5 : [ + 'Geometry/CMSCommonData/data/FieldParameters.xml', + ], + "era" : "phase2_common, phase2_trigger", + }, } trackerDict = { diff --git a/Configuration/ProcessModifiers/python/convertHGCalDigisReco_cff.py b/Configuration/ProcessModifiers/python/convertHGCalDigisReco_cff.py deleted file mode 100644 index 921fa6a26f917..0000000000000 --- a/Configuration/ProcessModifiers/python/convertHGCalDigisReco_cff.py +++ /dev/null @@ -1,5 +0,0 @@ -import FWCore.ParameterSet.Config as cms - -# to convert old-format HGCal digis into new format during RawToDigi step - -convertHGCalDigisReco = cms.Modifier() diff --git a/Configuration/ProcessModifiers/python/trackdnn_CKF_cff.py b/Configuration/ProcessModifiers/python/trackdnn_CKF_cff.py new file mode 100644 index 0000000000000..9f37111ec2af7 --- /dev/null +++ b/Configuration/ProcessModifiers/python/trackdnn_CKF_cff.py @@ -0,0 +1,5 @@ +import FWCore.ParameterSet.Config as cms + +# This modifier sets the used tracking classifier to be a deep neural network instead of the BDT + +trackdnn_CKF = cms.Modifier() diff --git a/Configuration/ProcessModifiers/python/trackdnn_cff.py b/Configuration/ProcessModifiers/python/trackdnn_cff.py index aa14e5d6711e4..9374be026580b 100644 --- a/Configuration/ProcessModifiers/python/trackdnn_cff.py +++ b/Configuration/ProcessModifiers/python/trackdnn_cff.py @@ -2,3 +2,4 @@ # This modifier sets the used tracking classifier to be a deep neural network instead of the BDT trackdnn = cms.Modifier() + diff --git a/Configuration/ProcessModifiers/python/trackingNoLoopers_cff.py b/Configuration/ProcessModifiers/python/trackingNoLoopers_cff.py new file mode 100644 index 0000000000000..f2de612d51721 --- /dev/null +++ b/Configuration/ProcessModifiers/python/trackingNoLoopers_cff.py @@ -0,0 +1,4 @@ +import FWCore.ParameterSet.Config as cms + +# This modifier removes the looper tracks reconstruction +trackingNoLoopers = cms.Modifier() diff --git a/Configuration/PyReleaseValidation/README.md b/Configuration/PyReleaseValidation/README.md index 6942ed89355d1..6f5395d74d9bc 100644 --- a/Configuration/PyReleaseValidation/README.md +++ b/Configuration/PyReleaseValidation/README.md @@ -63,6 +63,7 @@ The offsets currently in use are: * 0.9921: Production-like premixing stage1+stage2 * 0.911: DD4Hep reading geometry from XML * 0.912: DD4Hep reading geometry from the DB +* 0.914: DDD DB * 0.101: Phase-2 aging, 1000fb-1 * 0.103: Phase-2 aging, 3000fb-1 * 0.9001: Sonic Triton diff --git a/Configuration/PyReleaseValidation/python/MatrixUtil.py b/Configuration/PyReleaseValidation/python/MatrixUtil.py index d3cd4862c0de9..e0cb155068f83 100644 --- a/Configuration/PyReleaseValidation/python/MatrixUtil.py +++ b/Configuration/PyReleaseValidation/python/MatrixUtil.py @@ -151,7 +151,11 @@ def lumis(self): if self.ls: for run in self.ls.keys(): run_lumis = [] - for rng in self.ls[run]: run_lumis.append(str(rng[0])+","+str(rng[1])) + for rng in self.ls[run]: + if isinstance(rng, int): + run_lumis.append(str(rng)) + else: + run_lumis.append(str(rng[0])+","+str(rng[1])) query_lumis.append(":".join(run_lumis)) return query_lumis diff --git a/Configuration/PyReleaseValidation/python/relval_2017.py b/Configuration/PyReleaseValidation/python/relval_2017.py index 0c65ccc7fd102..1dd7cd8f9c419 100644 --- a/Configuration/PyReleaseValidation/python/relval_2017.py +++ b/Configuration/PyReleaseValidation/python/relval_2017.py @@ -28,7 +28,7 @@ # (Patatrack ECAL-only: TTbar - on CPU) # (Patatrack HCAL-only: TTbar - on CPU) # 2021 (DD4HEP XML: TTbar, ZMM) -# (DD4HEP DB: TTbar) +# (DDD DB: TTbar, ZMM) # (ele guns 10, 35, 1000; pho guns 10, 35; mu guns 1, 10, 100, 1000, QCD 3TeV, QCD Flat) # (ZMM, TTbar, ZEE, MinBias, TTbar PU, TTbar PU premix, ZEE PU, TTbar design, GluGluTo2Jets, GluGluTo2Jets PU) # (TTbar trackingOnly, pixelTrackingOnly, trackingMkFit, trackdnn) @@ -56,7 +56,7 @@ 10824.511, 10824.521, 11634.911, 11650.911, - 11634.912, + 11634.914, 11650.914, 11601.0,11602.0,11603.0,11604.0,11605.0,11606.0,11607.0,11608.0,11609.0,11630.0,11643.0, 11650.0,11634.0,11646.0,11640.0,11834.0,11834.99,11846.0,12034.0,11725.0,11925.0, 11634.1,11634.5,11634.7,11634.91, diff --git a/Configuration/PyReleaseValidation/python/relval_2026.py b/Configuration/PyReleaseValidation/python/relval_2026.py index 7a06ac66c7ce7..63b1b0b72ea0a 100644 --- a/Configuration/PyReleaseValidation/python/relval_2026.py +++ b/Configuration/PyReleaseValidation/python/relval_2026.py @@ -24,9 +24,11 @@ numWFIB.extend([31434.0]) #2026D68 numWFIB.extend([32234.0]) #2026D70 numWFIB.extend([34634.0]) #2026D76 -numWFIB.extend([34834.999]) #2026D76 premixing combined stage1+stage2 (ttbar+PU50 for PR test) +numWFIB.extend([34834.99,34834.999]) #2026D76 premixing combined stage1+stage2 (ttbar+PU200, ttbar+PU50 for PR test) numWFIB.extend([34634.21,34834.21,34834.9921]) #2026D76 prodlike, prodlike PU, prodlike premix stage1+stage2 numWFIB.extend([35034.0]) #2026D77 +numWFIB.extend([35234.99,35234.999]) #2026D77 premixing combined stage1+stage2 (ttbar+PU200, ttbar+PU50 for PR test) +numWFIB.extend([35034.21,35234.21,35234.9921]) #2026D77 prodlike, prodlike PU, prodlike premix stage1+stage2 numWFIB.extend([35434.0]) #2026D78 numWFIB.extend([35834.0]) #2026D79 numWFIB.extend([36234.0]) #2026D80 diff --git a/Configuration/PyReleaseValidation/python/relval_production.py b/Configuration/PyReleaseValidation/python/relval_production.py index f0f540b6cbc1a..452907378db3c 100644 --- a/Configuration/PyReleaseValidation/python/relval_production.py +++ b/Configuration/PyReleaseValidation/python/relval_production.py @@ -26,6 +26,7 @@ workflows[1040.1] = ['',['RunExpressPhy2017F','TIER0EXPSIPIXELCAL','ALCASPLITSIPIXELCAL','ALCAHARVDSIPIXELCAL']] workflows[1041] = ['',['RunExpressPhy2017F','TIER0EXPPPSCAL','ALCASPLITPPSCAL','ALCAHARVDPPSCAL']] +workflows[1042] = ['',['RunExpressPhy2017F','TIER0EXPPPSCALALIG','ALCASPLITPPSALIG','ALCAHARVDPPSALIG']] ## MC production test #workflows[1100] = [ '',[]] diff --git a/Configuration/PyReleaseValidation/python/relval_standard.py b/Configuration/PyReleaseValidation/python/relval_standard.py index d82ea4a2e5a1a..5761360b5c565 100644 --- a/Configuration/PyReleaseValidation/python/relval_standard.py +++ b/Configuration/PyReleaseValidation/python/relval_standard.py @@ -436,6 +436,8 @@ ### LS2 - MWGR ### workflows[138.1] = ['',['RunCosmics2021','RECOCOSDPROMPTRUN3','ALCACOSDPROMPTRUN3','HARVESTDCPROMPTRUN3']] workflows[138.2] = ['',['RunCosmics2021','RECOCOSDEXPRUN3','ALCACOSDEXPRUN3','HARVESTDCEXPRUN3']] +### 2021 Splash events +workflows[138.3] = ['',['RunMinimumBias2021Splash','COPYPASTER3', 'RECODR3Splash','HARVESTDR3']] #### Test of lumi section boundary crossing with run2 2018D #### workflows[136.8861] = ['',['RunEGamma2018Dml1','HLTDR2_2018ml','RECODR2_2018reHLT_skimEGamma_Prompt_L1TEgDQM','HARVEST2018_L1TEgDQM_Prompt']] diff --git a/Configuration/PyReleaseValidation/python/relval_steps.py b/Configuration/PyReleaseValidation/python/relval_steps.py index af8689b01b987..0363195ae326c 100644 --- a/Configuration/PyReleaseValidation/python/relval_steps.py +++ b/Configuration/PyReleaseValidation/python/relval_steps.py @@ -100,7 +100,7 @@ steps['HighMet2011B']={'INPUT':InputInfo(dataSet='/Jet/Run2011B-HighMET-19Nov2011-v1/RAW-RECO',label='2011B',run=Run2011BSk)} steps['RunHI2010']={'INPUT':InputInfo(dataSet='/HIAllPhysics/HIRun2010-v1/RAW',label='hi2010',run=[152698],events=10000,location='STD')} -steps['RunHI2011']={'INPUT':InputInfo(dataSet='/HIMinBiasUPC/HIRun2011-v1/RAW',label='hi2011',run=[182124],events=10000,location='STD')} +steps['RunHI2011']={'INPUT':InputInfo(dataSet='/HIMinBiasUPC/HIRun2011-v1/RAW',label='hi2011',ls={182124: [40]},events=10000,location='STD')} steps['RunPA2013']={'INPUT':InputInfo(dataSet='/PAMinBiasUPC/HIRun2013-v1/RAW',label='pa2013',run=[211313],events=10000,location='STD')} Run2015HI={263400: [[65,904]]} @@ -497,6 +497,11 @@ ##Run 344518 @ 0T 2021CRUZET steps['RunCosmics2021CRUZET']={'INPUT':InputInfo(dataSet='/Cosmics/Commissioning2021-v1/RAW',label='2021CRUZET',run=[344518],events=100000,location='STD')} +#### run3 Splash #### +##Run 345881 +steps['RunMinimumBias2021Splash']={'INPUT':InputInfo(dataSet='/MinimumBias/Commissioning2021-v1/RAW',label='2021Splash',ls={345881: [782, 790, 796, 801, 1031, 1037]},events=100000,location='STD')} + + #### Test of lumi section boundary crossing with run2 2018D #### Run2018Dml1={320822: [[1,1]] , 320823: [[1,1]]} Run2018Dml2={320822: [[1,2]]} @@ -1904,6 +1909,9 @@ def lhegensim2018ml(fragment,howMuch): steps['RECODR2_2016']=merge([{'--scenario':'pp','--conditions':'auto:run2_data_relval','--era':'Run2_2016','--customise':'Configuration/DataProcessing/RecoTLR.customisePostEra_Run2_2016'},dataReco]) steps['RECODR2_2017']=merge([{'--scenario':'pp','--conditions':'auto:run2_data_relval','--era':'Run2_2017','--customise':'Configuration/DataProcessing/RecoTLR.customisePostEra_Run2_2017'},dataReco]) steps['RECODR2_2018']=merge([{'--scenario':'pp','--conditions':'auto:run2_data_relval','--era':'Run2_2018','--customise':'Configuration/DataProcessing/RecoTLR.customisePostEra_Run2_2018'},dataReco]) +#Run 3 +steps['RECODR3']=merge([{'--scenario':'pp','--conditions':'auto:run3_data_prompt','--era':'Run3','--customise':'Configuration/DataProcessing/RecoTLR.customisePostEra_Run3'},dataReco]) +steps['RECODR3Splash']=merge([{'-n': 2},steps['RECODR3']]) steps['RECODR2AlCaEle']=merge([{'--scenario':'pp','--conditions':'auto:run2_data_relval','--customise':'Configuration/DataProcessing/RecoTLR.customisePromptRun2',},dataRecoAlCaCalo]) @@ -2095,6 +2103,17 @@ def lhegensim2018ml(fragment,howMuch): '--eventcontent':'ALCARECO', } +steps['TIER0EXPPPSCALALIG']={'-s':'RAW2DIGI,L1Reco,ALCAPRODUCER:PPSCalTrackBasedSel,ENDJOB', + '-n':1000, + '--process':'ALCARECO', + '--scenario': 'pp', + '--era':'Run2_2017', + '--conditions':'auto:run2_data', + '--data': '', + '--datatier':'ALCARECO', + '--eventcontent':'ALCARECO', + } + steps['ALCASPLITHPBS']={'-s':'ALCAOUTPUT:TkAlMinBias,ALCA:PromptCalibProdBeamSpotHP+PromptCalibProdBeamSpotHPLowPU', '--scenario':'pp', '--data':'', @@ -2126,6 +2145,17 @@ def lhegensim2018ml(fragment,howMuch): '--triggerResultsProcess':'RECO', } +steps['ALCASPLITPPSALIG']={'-s':'ALCAOUTPUT:PPSCalTrackBasedSel,ALCA:PPSAlignment', + '-n':1000, + '--scenario':'pp', + '--data':'', + '--era':'Run2_2017', + '--datatier':'ALCARECO', + '--eventcontent':'ALCARECO', + '--conditions':'auto:run3_data_express', + '--triggerResultsProcess':'RECO', + } + steps['ALCAHARVDHPBS']={'-s':'ALCAHARVEST:%s'%(autoPCL['PromptCalibProdBeamSpotHP']), #'--conditions':'auto:run2_data_promptlike', '--conditions':'auto:run3_data_express', # to replaced with line above once run2_data_promptlike will contain DropBoxMetadata @@ -2165,6 +2195,13 @@ def lhegensim2018ml(fragment,howMuch): '--era':'Run2_2017', '--filein':'file:PPSTimingCalib.root'} +steps['ALCAHARVDPPSALIG']={'-s':'ALCAHARVEST:%s'%(autoPCL['PromptCalibProdPPSAlig']), + '--conditions':'auto:run3_data_express', + '--scenario':'pp', + '--data':'', + '--era':'Run2_2017', + '--filein':'file:PPSAlignment.root'} + steps['RECOCOSD']=merge([{'--scenario':'cosmics', '-s':'RAW2DIGI,L1Reco,RECO,DQM', '--datatier':'RECO,DQMIO', # no miniAOD for cosmics @@ -2445,7 +2482,7 @@ def gen2021HiMix(fragment,howMuch): steps['RECOMINUP15']=merge([{'-s':'RAW2DIGI,L1Reco,RECO,RECOSIM,EI,ALCA:SiStripCalZeroBias+SiStripCalMinBias,VALIDATION,DQM'},step3Up2015Defaults]) steps['RECOAODUP15']=merge([{'--datatier':'AODSIM,MINIAODSIM,DQMIO','--eventcontent':'AODSIM,MINIAODSIM,DQM'},step3Up2015Defaults]) -steps['RECODDQM']=merge([{'-s':'RAW2DIGI,L1Reco,RECO,EI,DQM:@common+@muon+@hcal+@jetmet+@ecal'},steps['RECOD']]) +steps['RECODDQM']=merge([{'-s':'RAW2DIGI,L1Reco,RECO,EI,DQM:@allForPrompt'},steps['RECOD']]) steps['RECOPU1']=merge([PU,steps['RECO']]) steps['RECOPU2']=merge([PU2,steps['RECO']]) @@ -2786,6 +2823,10 @@ def gen2021HiMix(fragment,howMuch): '--filein':"file:step6_inDQM.root,file:step3_inDQM.root", }, steps['HARVEST2018_L1TEgDQM'] ]) + +#RUN3 +steps['HARVESTDR3'] = merge([ {'--conditions':'auto:run3_data_prompt','--era':'Run3'}, steps['HARVESTD'] ]) + steps['DQMHLTonAOD_2017']={ '-s':'DQM:offlineHLTSourceOnAOD', ### DQM-only workflow on AOD input: for HLT '--conditions':'auto:run2_data', @@ -2814,7 +2855,7 @@ def gen2021HiMix(fragment,howMuch): steps['HARVESTDQMHLTonAOD_2017'] = merge([ {'--filein':'file:DQMHLTonAOD.root','-s':'HARVESTING:hltOfflineDQMClient'}, steps['HARVEST2017'] ]) ### Harvesting step for the DQM-only workflow -steps['HARVESTDDQM']=merge([{'-s':'HARVESTING:@common+@muon+@hcal+@jetmet+@ecal'},steps['HARVESTD']]) +steps['HARVESTDDQM']=merge([{'-s':'HARVESTING:@allForPrompt'},steps['HARVESTD']]) steps['HARVESTDfst2']=merge([{'--filein':'file:step2_inDQM.root'},steps['HARVESTDR1']]) @@ -3096,6 +3137,7 @@ def gen2021HiMix(fragment,howMuch): '--conditions':'auto:run1_mc', '--output':'\'[{"t":"RAW","e":"ALL"}]\'', '--customise_commands':'"process.ALLRAWoutput.fastCloning=cms.untracked.bool(False)"'} +steps['COPYPASTER3'] = merge([{'--era' : 'Run3'}, steps['COPYPASTE']]) #miniaod stepMiniAODDefaults = { '-s' : 'PAT', @@ -3310,6 +3352,7 @@ def gen2021HiMix(fragment,howMuch): defaultDataSets['2024']='CMSSW_12_0_0_pre4-120X_mcRun3_2024_realistic_v2-v' defaultDataSets['2026D49']='CMSSW_12_0_0_pre4-113X_mcRun4_realistic_v7_2026D49noPU-v' defaultDataSets['2026D76']='CMSSW_12_0_0_pre4-113X_mcRun4_realistic_v7_2026D76noPU-v' +defaultDataSets['2026D77']='CMSSW_12_1_0_pre2-113X_mcRun4_realistic_v7_2026D77noPU-v' puDataSets = {} for key, value in defaultDataSets.items(): puDataSets[key+'PU'] = value diff --git a/Configuration/PyReleaseValidation/python/upgradeWorkflowComponents.py b/Configuration/PyReleaseValidation/python/upgradeWorkflowComponents.py index d6cb11b15e450..c18e59bcf4ff5 100644 --- a/Configuration/PyReleaseValidation/python/upgradeWorkflowComponents.py +++ b/Configuration/PyReleaseValidation/python/upgradeWorkflowComponents.py @@ -1157,7 +1157,7 @@ def condition(self, fragment, stepList, key, hasHarvest): class UpgradeWorkflow_DD4hep(UpgradeWorkflow): def setup_(self, step, stepName, stepDict, k, properties): if 'Run3' in stepDict[step][k]['--era']: - stepDict[stepName][k] = merge([{'--geometry': 'DD4hepExtended2021', '--procModifiers': 'dd4hep'}, stepDict[step][k]]) + stepDict[stepName][k] = merge([{'--geometry': 'DD4hepExtended2021'}, stepDict[step][k]]) elif 'Phase2' in stepDict[step][k]['--era']: dd4hepGeom="DD4hep" dd4hepGeom+=stepDict[step][k]['--geometry'] @@ -1183,10 +1183,12 @@ def condition(self, fragment, stepList, key, hasHarvest): ) upgradeWFs['DD4hep'].allowReuse = False +#This workflow is now obsolete, it becomes default for Run-3. +#Keep it for future use in Phase-2, then delete class UpgradeWorkflow_DD4hepDB(UpgradeWorkflow): def setup_(self, step, stepName, stepDict, k, properties): if 'Run3' in stepDict[step][k]['--era']: - stepDict[stepName][k] = merge([{'--conditions': 'auto:phase1_2021_dd4hep', '--geometry': 'DB:Extended', '--procModifiers': 'dd4hep'}, stepDict[step][k]]) + stepDict[stepName][k] = merge([{'--conditions': 'auto:phase1_2021_realistic', '--geometry': 'DB:Extended'}, stepDict[step][k]]) def condition(self, fragment, stepList, key, hasHarvest): return '2021' in key upgradeWFs['DD4hepDB'] = UpgradeWorkflow_DD4hepDB( @@ -1208,6 +1210,31 @@ def condition(self, fragment, stepList, key, hasHarvest): ) upgradeWFs['DD4hepDB'].allowReuse = False +class UpgradeWorkflow_DDDDB(UpgradeWorkflow): + def setup_(self, step, stepName, stepDict, k, properties): + if 'Run3' in stepDict[step][k]['--era']: + stepDict[stepName][k] = merge([{'--conditions': 'auto:phase1_2021_realistic_ddd', '--geometry': 'DB:Extended', '--era': 'Run3_DDD'}, stepDict[step][k]]) + def condition(self, fragment, stepList, key, hasHarvest): + return '2021' in key +upgradeWFs['DDDDB'] = UpgradeWorkflow_DDDDB( + steps = [ + 'GenSim', + 'GenSimHLBeamSpot', + 'GenSimHLBeamSpot14', + 'Digi', + 'DigiTrigger', + 'Reco', + 'RecoGlobal', + 'HARVEST', + 'HARVESTGlobal', + 'ALCA', + ], + PU = [], + suffix = '_DDDDB', + offset = 0.914, +) +upgradeWFs['DDDDB'].allowReuse = False + class UpgradeWorkflow_SonicTriton(UpgradeWorkflow): def setup_(self, step, stepName, stepDict, k, properties): stepDict[stepName][k] = merge([{'--procModifiers': 'allSonicTriton'}, stepDict[step][k]]) diff --git a/Configuration/PyReleaseValidation/scripts/das-selected-lumis.py b/Configuration/PyReleaseValidation/scripts/das-selected-lumis.py index c316ecbafe079..72177c7b96c13 100755 --- a/Configuration/PyReleaseValidation/scripts/das-selected-lumis.py +++ b/Configuration/PyReleaseValidation/scripts/das-selected-lumis.py @@ -17,7 +17,10 @@ def match_in(sub_list,lumi_list): for i in range(int(sub_list[0]),int(sub_list[1])+1): - if i >= int(lumi_list[0]) and i <= int(lumi_list[1]): return True + if len(lumi_list) == 1: + if i == int(lumi_list[0]): return True + else: + if i >= int(lumi_list[0]) and i <= int(lumi_list[1]): return True return False def check_lumi_ranges(given_lumi_list , sub_range): diff --git a/Configuration/PyReleaseValidation/scripts/runTheMatrix.py b/Configuration/PyReleaseValidation/scripts/runTheMatrix.py index 471e4e7f3d7da..69d13ed783906 100755 --- a/Configuration/PyReleaseValidation/scripts/runTheMatrix.py +++ b/Configuration/PyReleaseValidation/scripts/runTheMatrix.py @@ -81,21 +81,23 @@ def runSelected(opt): 1306.0, #SingleMu Pt1 UP15 1325.81, #test NanoAOD from existing MINI UL 106Xv1 136.8523, #test NanoAOD from existing reMINI UL 106Xv2 - 1330, #Run2 MC Zmm - 135.4, #Run 2 Zee ttbar + 1330, #Run2 2015/2016 MC Zmm + 135.4, #Run 2 2015/2016 Zee ttbar fastsim 10042.0, #2017 ZMM 10024.0, #2017 ttbar 10224.0, #2017 ttbar PU 10824.0, #2018 ttbar + 2018.1, #2018 ttbar fastsim 11634.911, #2021 DD4hep ttbar reading geometry from XML - 11634.912, #2021 DD4hep ttbar reading geometry from the DB - 11634.0, #2021 ttbar + 11634.914, #2021 DDD ttbar reading geometry from the DB + 11634.0, #2021 ttbar (switching to DD4hep by default) 11634.7, #2021 ttbar mkFit 12434.0, #2023 ttbar 23234.0, #2026D49 ttbar (HLT TDR baseline w/ HGCal v11) 28234.0, #2026D60 (exercise HF nose) - 34634.0, #2026D76 ttbar (2021 new baseline) - 34834.999, #2026D76 ttbar premixing stage1+stage2, PU50 + 35034.0, #2026D77 ttbar (2021 new baseline) + 35234.999, #2026D77 ttbar premixing stage1+stage2, PU50 + 38634.0, #2026D86 ttbar 25202.0, #2016 ttbar UP15 PU 250202.181, #2018 ttbar stage1 + stage2 premix ], diff --git a/Configuration/StandardSequences/python/AlCaHarvesting_cff.py b/Configuration/StandardSequences/python/AlCaHarvesting_cff.py index 583a05feb7453..88b0b11b71024 100644 --- a/Configuration/StandardSequences/python/AlCaHarvesting_cff.py +++ b/Configuration/StandardSequences/python/AlCaHarvesting_cff.py @@ -13,6 +13,7 @@ from CalibTracker.SiPixelQuality.DQMEventInfoSiPixelQuality_cff import * from CalibPPS.TimingCalibration.PPSTimingCalibrationHarvester_cff import * from CalibPPS.TimingCalibration.ALCARECOPPSDiamondSampicTimingCalibHarvester_cff import * +from CalibPPS.AlignmentGlobal.PPSAlignmentHarvester_cff import * from Calibration.TkAlCaRecoProducers.PCLMetadataWriter_cfi import * @@ -239,6 +240,11 @@ tag = cms.string('DiamondSampicCalibration'), timetype = cms.untracked.string('runnumber')) +ALCAHARVESTPPSAlignment_metadata = cms.PSet(record = cms.untracked.string('CTPPSRPAlignmentCorrectionsDataRcd')) +ALCAHARVESTPPSAlignment_dbOutput = cms.PSet(record = cms.string('CTPPSRPAlignmentCorrectionsDataRcd'), + tag = cms.string('CTPPSRPAlignment_real_pcl'), + timetype = cms.untracked.string('runnumber')) + # define all the paths BeamSpotByRun = cms.Path(ALCAHARVESTBeamSpotByRun) BeamSpotByLumi = cms.Path(ALCAHARVESTBeamSpotByLumi) @@ -256,6 +262,7 @@ SiPixelQuality = cms.Path(dqmEnvSiPixelQuality+ALCAHARVESTSiPixelQuality)#+siPixelPhase1DQMHarvester) PPSTimingCalibration = cms.Path(ALCAHARVESTPPSTimingCalibration) PPSDiamondSampicTimingCalibration = cms.Path(ALCAHARVESTPPSDiamondSampicTimingCalibration) +PPSAlignment = cms.Path(ALCAHARVESTPPSAlignment) ALCAHARVESTDQMSaveAndMetadataWriter = cms.Path(dqmSaver+pclMetadataWriter) diff --git a/Configuration/StandardSequences/python/AlCaRecoStreams_cff.py b/Configuration/StandardSequences/python/AlCaRecoStreams_cff.py index ce3ebcfb8cad7..ad3bc858f980b 100644 --- a/Configuration/StandardSequences/python/AlCaRecoStreams_cff.py +++ b/Configuration/StandardSequences/python/AlCaRecoStreams_cff.py @@ -133,6 +133,8 @@ from CalibPPS.TimingCalibration.ALCARECOPPSCalTrackBasedSel_cff import * from CalibPPS.TimingCalibration.ALCARECOPPSTimingCalib_cff import * from CalibPPS.TimingCalibration.ALCARECOPPSDiamondSampicTimingCalib_cff import * +# Alignment +from CalibPPS.AlignmentGlobal.ALCARECOPPSAlignment_cff import * ############################################################### # nonbeam alcas @@ -243,6 +245,7 @@ pathALCARECORpcCalHLT = cms.Path(seqALCARECORpcCalHLT) pathALCARECOPPSTimingCalib = cms.Path(taskALCARECOPPSTimingCalib) pathALCARECOPPSDiamondSampicTimingCalib = cms.Path(taskALCARECOPPSDiamondSampicTimingCalib) +pathALCARECOPPSAlignment = cms.Path(taskALCARECOPPSAlignment) pathALCARECOTkAlBeamHalo = cms.Path(seqALCARECOTkAlBeamHalo*ALCARECOTkAlBeamHaloDQM) pathALCARECOMuAlBeamHaloOverlaps = cms.Path(seqALCARECOMuAlBeamHaloOverlaps) pathALCARECOMuAlBeamHalo = cms.Path(seqALCARECOMuAlBeamHalo) @@ -903,6 +906,15 @@ dataTier = cms.untracked.string('ALCARECO') ) +ALCARECOStreamPPSAlignment = cms.FilteredStream( + responsible = 'Mateusz Kocot', + name = 'PPSAlignment', + paths = (pathALCARECOPPSAlignment), + content = OutALCARECOPPSAlignment.outputCommands, + selectEvents = OutALCARECOPPSAlignment.SelectEvents, + dataTier = cms.untracked.string('ALCARECO') +) + ALCARECOStreamPromptCalibProd = cms.FilteredStream( responsible = 'Gianluca Cerminara', name = 'PromptCalibProd', diff --git a/Configuration/StandardSequences/python/Eras.py b/Configuration/StandardSequences/python/Eras.py index f2d80ef09702d..08f280c8c1b73 100644 --- a/Configuration/StandardSequences/python/Eras.py +++ b/Configuration/StandardSequences/python/Eras.py @@ -21,6 +21,7 @@ def __init__(self): 'Run2_2016_trackingLowPU', 'Run2_2016_pA', 'Run2_2017', + 'Run2_2017_noMkFit', 'Run2_2017_FastSim', #new modifier for Phase1 FastSim, skips the muon GEM sequence 'Run2_2017_trackingRun2', 'Run2_2017_trackingLowPU', @@ -31,10 +32,12 @@ def __init__(self): 'Run2_2018_pp_on_AA', 'Run2_2018_pp_on_AA_noHCALmitigation', 'Run2_2018_highBetaStar', + 'Run2_2018_noMkFit', 'Run3', 'Run3_noMkFit', 'Run3_pp_on_PbPb', 'Run3_dd4hep', + 'Run3_DDD', 'Phase2', 'Phase2C9', 'Phase2C10', diff --git a/DPGAnalysis/Skims/python/runonSM.py b/DPGAnalysis/Skims/python/runonSM.py index e5a48accc2f7a..45e5c1fbe2f38 100755 --- a/DPGAnalysis/Skims/python/runonSM.py +++ b/DPGAnalysis/Skims/python/runonSM.py @@ -1,6 +1,6 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 from __future__ import print_function -import os,string,sys,commands,time +import os,string,sys,time # template file to be used MODFILE="reco_skim_cfg_mod.py" diff --git a/DPGAnalysis/Skims/python/runonSM_350.py b/DPGAnalysis/Skims/python/runonSM_350.py index 7bdc76ef9cf7c..0b4b65fe9a839 100755 --- a/DPGAnalysis/Skims/python/runonSM_350.py +++ b/DPGAnalysis/Skims/python/runonSM_350.py @@ -1,6 +1,6 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 from __future__ import print_function -import os,string,sys,commands,time +import os,string,sys,time # template file to be used MODFILE="reco_skim_cfg_mod_350.py" diff --git a/DPGAnalysis/Skims/python/runonSMtunnel.py b/DPGAnalysis/Skims/python/runonSMtunnel.py index b135de34fdf8d..70fa5816ab06a 100755 --- a/DPGAnalysis/Skims/python/runonSMtunnel.py +++ b/DPGAnalysis/Skims/python/runonSMtunnel.py @@ -1,6 +1,6 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 from __future__ import print_function -import os,string,sys,commands,time +import os,string,sys,time # template file to be used MODFILE="reco_skim_cfg_mod.py" diff --git a/DQM/BeamMonitor/plugins/BeamMonitor.cc b/DQM/BeamMonitor/plugins/BeamMonitor.cc index 8728e4907dad7..6989ba262470e 100644 --- a/DQM/BeamMonitor/plugins/BeamMonitor.cc +++ b/DQM/BeamMonitor/plugins/BeamMonitor.cc @@ -533,7 +533,8 @@ void BeamMonitor::beginLuminosityBlock(const LuminosityBlock& lumiSeg, const Eve DBloggerReturn_ = 0; if (onlineDbService_.isAvailable()) { onlineDbService_->logger().start(); - onlineDbService_->logger().logInfo() << "BeamMonitor::beginLuminosityBlock - LS: " << lumiSeg.luminosityBlock(); + onlineDbService_->logger().logInfo() << "BeamMonitor::beginLuminosityBlock - LS: " << lumiSeg.luminosityBlock() + << " - Run: " << lumiSeg.getRun().run(); } int nthlumi = lumiSeg.luminosityBlock(); diff --git a/DQM/BeamMonitor/plugins/BeamSpotDipServer.cc b/DQM/BeamMonitor/plugins/BeamSpotDipServer.cc index bcb6d6ec84d2b..3f8e46dabae1a 100644 --- a/DQM/BeamMonitor/plugins/BeamSpotDipServer.cc +++ b/DQM/BeamMonitor/plugins/BeamSpotDipServer.cc @@ -55,6 +55,10 @@ BeamSpotDipServer::BeamSpotDipServer(const edm::ParameterSet& ps) { // dip = Dip::create("CmsBeamSpotServer"); + + // + dip->setDNSNode("dipns1,dipns2"); + edm::LogInfo("BeamSpotDipServer") << "reading from " << (readFromNFS ? "file (NFS)" : "database"); } diff --git a/DQM/BeamMonitor/plugins/FakeBeamMonitor.cc b/DQM/BeamMonitor/plugins/FakeBeamMonitor.cc index 17fe6c8b0859a..05a468f6ca130 100644 --- a/DQM/BeamMonitor/plugins/FakeBeamMonitor.cc +++ b/DQM/BeamMonitor/plugins/FakeBeamMonitor.cc @@ -527,7 +527,8 @@ void FakeBeamMonitor::beginLuminosityBlock(const LuminosityBlock& lumiSeg, const DBloggerReturn_ = 0; if (onlineDbService_.isAvailable()) { onlineDbService_->logger().start(); - onlineDbService_->logger().logInfo() << "FakeBeamMonitor::beginLuminosityBlock - LS: " << lumiSeg.luminosityBlock(); + onlineDbService_->logger().logInfo() << "FakeBeamMonitor::beginLuminosityBlock - LS: " << lumiSeg.luminosityBlock() + << " - Run: " << lumiSeg.getRun().run(); } int nthlumi = lumiSeg.luminosityBlock(); diff --git a/DQM/BeamMonitor/plugins/OnlineBeamMonitor.cc b/DQM/BeamMonitor/plugins/OnlineBeamMonitor.cc index 534d639bf858a..0c2773cda89ad 100644 --- a/DQM/BeamMonitor/plugins/OnlineBeamMonitor.cc +++ b/DQM/BeamMonitor/plugins/OnlineBeamMonitor.cc @@ -109,11 +109,15 @@ void OnlineBeamMonitor::bookHistograms(DQMStore::IBooker& ibooker, // create and cd into new folder ibooker.setCurrentFolder(monitorName_ + "Validation"); //Book histograms - bsChoice_ = ibooker.book1D("bsChoice", - "Choice between HLT (+1) and Legacy (-1) BS", - lastLumi - firstLumi + 1, - firstLumi - 0.5, - lastLumi + 0.5); + bsChoice_ = ibooker.bookProfile("bsChoice", + "BS Choice (+1): HLT - (-1): Legacy - (-10): Fake BS - (0): No Transient ", + lastLumi - firstLumi + 1, + firstLumi - 0.5, + lastLumi + 0.5, + 100, + -10, + 1, + ""); bsChoice_->setAxisTitle("Lumisection", 1); bsChoice_->setAxisTitle("Choice", 2); } @@ -236,18 +240,18 @@ void OnlineBeamMonitor::globalEndLuminosityBlock(const LuminosityBlock& iLumi, c if (beamSpotsMap_.find("Transient") != beamSpotsMap_.end()) { if (beamSpotsMap_.find("HLT") != beamSpotsMap_.end() && beamSpotsMap_["Transient"].x0() == beamSpotsMap_["HLT"].x0()) { - bsChoice_->setBinContent(iLumi.id().luminosityBlock(), 1); + bsChoice_->Fill(iLumi.id().luminosityBlock(), 1); bsChoice_->setBinError(iLumi.id().luminosityBlock(), 0.05); } else if (beamSpotsMap_.find("Legacy") != beamSpotsMap_.end() && beamSpotsMap_["Transient"].x0() == beamSpotsMap_["Legacy"].x0()) { - bsChoice_->setBinContent(iLumi.id().luminosityBlock(), -1); + bsChoice_->Fill(iLumi.id().luminosityBlock(), -1); bsChoice_->setBinError(iLumi.id().luminosityBlock(), 0.05); } else { - bsChoice_->setBinContent(iLumi.id().luminosityBlock(), -10); + bsChoice_->Fill(iLumi.id().luminosityBlock(), -10); bsChoice_->setBinError(iLumi.id().luminosityBlock(), 0.05); } } else { - bsChoice_->setBinContent(iLumi.id().luminosityBlock(), 0); + bsChoice_->Fill(iLumi.id().luminosityBlock(), 0); bsChoice_->setBinError(iLumi.id().luminosityBlock(), 0.05); } diff --git a/DQM/BeamMonitor/plugins/Vx3DHLTAnalyzer.cc b/DQM/BeamMonitor/plugins/Vx3DHLTAnalyzer.cc index 85b27594cfc07..237ddd40ca620 100644 --- a/DQM/BeamMonitor/plugins/Vx3DHLTAnalyzer.cc +++ b/DQM/BeamMonitor/plugins/Vx3DHLTAnalyzer.cc @@ -1239,7 +1239,8 @@ void Vx3DHLTAnalyzer::dqmEndLuminosityBlock(const LuminosityBlock& lumiBlock, co } } myGaussFit->SetRange(minXfit - (maxXfit - minXfit) / 2., maxXfit + (maxXfit - minXfit) / 2.); - Vx_X_Fit->getTH1()->Fit(myGaussFit, "QRL"); + if (Vx_X_Fit->getTH1()->GetEntries() > 0) + Vx_X_Fit->getTH1()->Fit(myGaussFit, "QRL"); myGaussFit->SetParameter(0, Vx_Y_Fit->getTH1()->GetMaximum()); myGaussFit->SetParameter(1, Vx_Y_Fit->getTH1()->GetMean()); @@ -1259,7 +1260,8 @@ void Vx3DHLTAnalyzer::dqmEndLuminosityBlock(const LuminosityBlock& lumiBlock, co } } myGaussFit->SetRange(minXfit - (maxXfit - minXfit) / 2., maxXfit + (maxXfit - minXfit) / 2.); - Vx_Y_Fit->getTH1()->Fit(myGaussFit, "QRL"); + if (Vx_Y_Fit->getTH1()->GetEntries() > 0) + Vx_Y_Fit->getTH1()->Fit(myGaussFit, "QRL"); myGaussFit->SetParameter(0, Vx_Z_Fit->getTH1()->GetMaximum()); myGaussFit->SetParameter(1, Vx_Z_Fit->getTH1()->GetMean()); @@ -1279,7 +1281,8 @@ void Vx3DHLTAnalyzer::dqmEndLuminosityBlock(const LuminosityBlock& lumiBlock, co } } myGaussFit->SetRange(minXfit - (maxXfit - minXfit) / 2., maxXfit + (maxXfit - minXfit) / 2.); - Vx_Z_Fit->getTH1()->Fit(myGaussFit, "QRL"); + if (Vx_Z_Fit->getTH1()->GetEntries() > 0) + Vx_Z_Fit->getTH1()->Fit(myGaussFit, "QRL"); delete myGaussFit; } else if ((nLumiFit != 0) && (lumiCounter % nLumiFit != 0) && (beginTimeOfFit != 0) && (runNumber != 0)) { diff --git a/DQM/BeamMonitor/test/beamspotdip_dqm_sourceclient-file_cfg.py b/DQM/BeamMonitor/test/beamspotdip_dqm_sourceclient-file_cfg.py index 13e0c508fe62e..798c886a95796 100644 --- a/DQM/BeamMonitor/test/beamspotdip_dqm_sourceclient-file_cfg.py +++ b/DQM/BeamMonitor/test/beamspotdip_dqm_sourceclient-file_cfg.py @@ -1,6 +1,14 @@ from __future__ import print_function import FWCore.ParameterSet.Config as cms +# copy log4cplus.properties from >script directory< to >local< +import sys +import os +from shutil import copy +configFile = os.path.dirname(sys.argv[1]) + "/log4cplus.properties" +print("copying " + configFile + " to local") +copy(configFile,".") + # process = cms.Process("BeamSpotDipServer") process.load("DQMServices.Core.DQM_cfg") diff --git a/DQM/CTPPS/plugins/BuildFile.xml b/DQM/CTPPS/plugins/BuildFile.xml index 6e804109707e8..545d763e6edea 100644 --- a/DQM/CTPPS/plugins/BuildFile.xml +++ b/DQM/CTPPS/plugins/BuildFile.xml @@ -14,4 +14,5 @@ + diff --git a/DQM/CTPPS/plugins/CTPPSDiamondDQMSource.cc b/DQM/CTPPS/plugins/CTPPSDiamondDQMSource.cc index adba4530d145e..1d6afd266755a 100644 --- a/DQM/CTPPS/plugins/CTPPSDiamondDQMSource.cc +++ b/DQM/CTPPS/plugins/CTPPSDiamondDQMSource.cc @@ -1,10 +1,11 @@ /**************************************************************************** * -* This is a part of CTPPS offline software. +* This is a part of CTPPSDQM software. * Authors: * Jan KaÅ¡par (jan.kaspar@gmail.com) * Nicola Minafra * Laurent Forthomme +* Christopher Misan * ****************************************************************************/ @@ -37,6 +38,9 @@ #include "Geometry/VeryForwardGeometryBuilder/interface/CTPPSGeometry.h" #include "Geometry/Records/interface/VeryForwardRealGeometryRecord.h" +// #include "CondFormats/RunInfo/interface/LHCInfo.h" +// #include "CondFormats/DataRecord/interface/LHCInfoRcd.h" + #include //---------------------------------------------------------------------------------------------------- @@ -68,10 +72,10 @@ namespace dds { class CTPPSDiamondDQMSource : public DQMOneEDAnalyzer> { public: CTPPSDiamondDQMSource(const edm::ParameterSet&); - ~CTPPSDiamondDQMSource() override; protected: void dqmBeginRun(const edm::Run&, const edm::EventSetup&) override; + void dqmEndRun(edm::Run const&, edm::EventSetup const&) override; void bookHistograms(DQMStore::IBooker&, const edm::Run&, const edm::EventSetup&) override; void analyze(const edm::Event&, const edm::EventSetup&) override; std::shared_ptr globalBeginLuminosityBlock(const edm::LuminosityBlock&, @@ -80,48 +84,39 @@ class CTPPSDiamondDQMSource : public DQMOneEDAnalyzer> tokenStatus_; - edm::EDGetTokenT> tokenPixelTrack_; - edm::EDGetTokenT> tokenDigi_; - edm::EDGetTokenT> tokenDiamondHit_; - edm::EDGetTokenT> tokenDiamondTrack_; - edm::EDGetTokenT> tokenFEDInfo_; - - edm::ESGetToken ctppsGeometryRunToken_; - edm::ESGetToken ctppsGeometryEventToken_; - - bool excludeMultipleHits_; - bool perLSsaving_; //to avoid nanoDQMIO crashing, driven by DQMServices/Core/python/DQMStore_cfi.py - double horizontalShiftBwDiamondPixels_; - double horizontalShiftOfDiamond_; - std::vector> runParameters_; - int centralOOT_; - unsigned int verbosity_; + /// Number of seconds per lumisection: used to compute hit rates in Hz + static constexpr double SEC_PER_LUMI_SECTION = 23.31; + /// Channel ID of the VFAT that contains clock data + static constexpr unsigned short CHANNEL_OF_VFAT_CLOCK = 30; + /// Bin width of histograms showing hits and tracks (in mm) + static constexpr double DISPLAY_RESOLUTION_FOR_HITS_MM = 0.1; + static constexpr double INV_DISPLAY_RESOLUTION_FOR_HITS_MM = 1. / DISPLAY_RESOLUTION_FOR_HITS_MM; + /// ns per HPTDC bin + static constexpr double HPTDC_BIN_WIDTH_NS = 25. / 1024; + static constexpr unsigned short CTPPS_PIXEL_STATION_ID = 2; + static constexpr unsigned short CTPPS_FAR_RP_ID = 3; + static constexpr unsigned short CTPPS_DIAMOND_NUM_OF_CHANNELS = 12; + static constexpr unsigned short CTPPS_FED_ID_45 = 583; + static constexpr unsigned short CTPPS_FED_ID_56 = 582; + static constexpr unsigned short HPTDC_0_CHANNEL = 6; + static constexpr unsigned short HPTDC_1_CHANNEL = 7; + /// Number of OOT indices monitored + static constexpr unsigned int FIRST_RUN_W_PIXELS = 300000; /// plots related to the whole system struct GlobalPlots { - GlobalPlots() {} + GlobalPlots() = default; GlobalPlots(DQMStore::IBooker& ibooker); }; - - GlobalPlots globalPlot_; - + /// plots related to one sector + struct SectorPlots { + // Tracks + MonitorElement* trackCorrelation = nullptr; + MonitorElement* trackCorrelationLowMultiplicity = nullptr; + MonitorElement* digiSentPercentage = nullptr; + SectorPlots(){}; + SectorPlots(DQMStore::IBooker& ibooker, unsigned int id, bool plotOnline); + }; /// plots related to one Diamond detector package struct PotPlots { std::unordered_map activity_per_bx; @@ -139,7 +134,7 @@ class CTPPSDiamondDQMSource : public DQMOneEDAnalyzer potPlots_; - int EC_difference_56_, EC_difference_45_; + // MonitorElement* TOTVsLSProfile = nullptr; + // MonitorElement* trackTimeVsLSProfile = nullptr; + MonitorElement* trackTimeVsBXProfile = nullptr; + // MonitorElement* trackTimeVsXAngleProfile = nullptr; + PotPlots() = default; + PotPlots(DQMStore::IBooker& ibooker, unsigned int id, unsigned int windowsNum, bool plotOnline, bool plotOffline); + }; /// plots related to one Diamond plane struct PlanePlots { MonitorElement* digiProfileCumulativePerPlane = nullptr; @@ -177,12 +180,9 @@ class CTPPSDiamondDQMSource : public DQMOneEDAnalyzer planePlots_; - /// plots related to one Diamond channel struct ChannelPlots { std::unordered_map activity_per_bx; @@ -191,46 +191,90 @@ class CTPPSDiamondDQMSource : public DQMOneEDAnalyzer> tokenStatus_; + edm::EDGetTokenT> tokenPixelTrack_; + edm::EDGetTokenT> tokenDigi_; + edm::EDGetTokenT> tokenDiamondHit_; + edm::EDGetTokenT> tokenDiamondTrack_; + edm::EDGetTokenT> tokenFEDInfo_; + + edm::ESGetToken ctppsGeometryRunToken_; + edm::ESGetToken ctppsGeometryEventToken_; + // edm::ESGetToken ctppsLhcInfoToken_; + + bool excludeMultipleHits_; + bool perLSsaving_; //to avoid nanoDQMIO crashing, driven by DQMServices/Core/python/DQMStore_cfi.py + const bool extract_digi_info_; + struct DiamondShifts { + double global, withPixels; }; + std::unordered_map diamShifts_; + std::vector> runParameters_; + int centralOOT_; + unsigned int verbosity_; + const bool plotOnline_; + const bool plotOffline_; + unsigned int windowsNum_; + unsigned int trackCorrelationThreshold_; + GlobalPlots globalPlot_; + std::unordered_map potPlots_; + std::unordered_map sectorPlots_; + std::unordered_map planePlots_; std::unordered_map channelPlots_; + + int EC_difference_56_, EC_difference_45_; }; //---------------------------------------------------------------------------------------------------- -// Values for all constants -const double CTPPSDiamondDQMSource::SEC_PER_LUMI_SECTION = 23.31; -const int CTPPSDiamondDQMSource::CHANNEL_OF_VFAT_CLOCK = 30; -const double CTPPSDiamondDQMSource::DISPLAY_RESOLUTION_FOR_HITS_MM = 0.1; -const double CTPPSDiamondDQMSource::INV_DISPLAY_RESOLUTION_FOR_HITS_MM = 1. / DISPLAY_RESOLUTION_FOR_HITS_MM; -const double CTPPSDiamondDQMSource::HPTDC_BIN_WIDTH_NS = 25. / 1024; -const int CTPPSDiamondDQMSource::CTPPS_NUM_OF_ARMS = 2; -const int CTPPSDiamondDQMSource::CTPPS_DIAMOND_STATION_ID = 1; -const int CTPPSDiamondDQMSource::CTPPS_PIXEL_STATION_ID = 2; -const int CTPPSDiamondDQMSource::CTPPS_DIAMOND_RP_ID = 6; -const int CTPPSDiamondDQMSource::CTPPS_NEAR_RP_ID = 2; -const int CTPPSDiamondDQMSource::CTPPS_FAR_RP_ID = 3; -const int CTPPSDiamondDQMSource::CTPPS_DIAMOND_NUM_OF_PLANES = 4; -const int CTPPSDiamondDQMSource::CTPPS_DIAMOND_NUM_OF_CHANNELS = 12; -const int CTPPSDiamondDQMSource::CTPPS_FED_ID_56 = 582; -const int CTPPSDiamondDQMSource::CTPPS_FED_ID_45 = 583; +CTPPSDiamondDQMSource::GlobalPlots::GlobalPlots(DQMStore::IBooker& ibooker) { ibooker.setCurrentFolder("CTPPS"); } //---------------------------------------------------------------------------------------------------- -CTPPSDiamondDQMSource::GlobalPlots::GlobalPlots(DQMStore::IBooker& ibooker) { ibooker.setCurrentFolder("CTPPS"); } +CTPPSDiamondDQMSource::SectorPlots::SectorPlots(DQMStore::IBooker& ibooker, unsigned int id, bool plotOnline) { + std::string path, title; + CTPPSDiamondDetId(id).armName(path, CTPPSDiamondDetId::nPath); + ibooker.setCurrentFolder(path); -//---------------------------------------------------------------------------------------------------- + CTPPSDiamondDetId(id).armName(title, CTPPSDiamondDetId::nFull); + + trackCorrelation = ibooker.book2D("tracks correlation near-far", + title + " tracks correlation near-far;x (mm);x (mm)", + 19. * INV_DISPLAY_RESOLUTION_FOR_HITS_MM, + -1, + 18, + 19. * INV_DISPLAY_RESOLUTION_FOR_HITS_MM, + -1, + 18); + trackCorrelationLowMultiplicity = + ibooker.book2D("tracks correlation with low multiplicity near-far", + title + " tracks correlation with low multiplicity near-far;x (mm);x (mm)", + 19. * INV_DISPLAY_RESOLUTION_FOR_HITS_MM, + -1, + 18, + 19. * INV_DISPLAY_RESOLUTION_FOR_HITS_MM, + -1, + 18); +} -CTPPSDiamondDQMSource::PotPlots::PotPlots(DQMStore::IBooker& ibooker, unsigned int id) +//---------------------------------------------------------------------------------------------------- +CTPPSDiamondDQMSource::PotPlots::PotPlots( + DQMStore::IBooker& ibooker, unsigned int id, unsigned int windowsNum, bool plotOnline, bool plotOffline) : HitCounter(0), MHCounter(0), LeadingOnlyCounter(0), @@ -243,12 +287,85 @@ CTPPSDiamondDQMSource::PotPlots::PotPlots(DQMStore::IBooker& ibooker, unsigned i CTPPSDiamondDetId(id).rpName(title, CTPPSDiamondDetId::nFull); - activity_per_bx[0] = - ibooker.book1D("activity per BX 0 25", title + " Activity per BX 0 - 25 ns;Event.BX", 3600, -1.5, 3598. + 0.5); - activity_per_bx[1] = - ibooker.book1D("activity per BX 25 50", title + " Activity per BX 25 - 50 ns;Event.BX", 3600, -1.5, 3598. + 0.5); - activity_per_bx[2] = - ibooker.book1D("activity per BX 50 75", title + " Activity per BX 50 - 75 ns;Event.BX", 3600, -1.5, 3598. + 0.5); + if (plotOnline) { + hitDistribution2d_lumisection = + ibooker.book2D("hits in planes lumisection", + title + " hits in planes in the last lumisection;plane number;x (mm)", + 10, + -0.5, + 4.5, + 19. * INV_DISPLAY_RESOLUTION_FOR_HITS_MM, + -0.5, + 18.5); + + hitDistribution2dOOT_le = + ibooker.book2D("hits with OOT in planes (le only)", + title + " hits with OOT in planes (le only);plane number, OOT index;x (mm)", + 1 + windowsNum * 4, + -1. / windowsNum, + 4, + 19. * INV_DISPLAY_RESOLUTION_FOR_HITS_MM, + -0.5, + 18.5); + + activePlanesInclusive = + ibooker.book1D("active planes inclusive", + title + " active planes, MH and le only included (per event);number of active planes", + 6, + -0.5, + 5.5); + + ECCheck = ibooker.book1D("optorxEC(8bit) - vfatEC", title + " EC Error;optorxEC-vfatEC", 50, -25, 25); + + EfficiencyOfChannelsInPot = + ibooker.book2D("Efficiency in channels", + title + " Efficiency (%) in channels (diamonds only);plane number;ch number", + 10, + -0.5, + 4.5, + 14, + -1, + 13); + } + + if (plotOffline) { + ibooker.setCurrentFolder(path + "/timing_profiles"); + // TOTVsLS=ibooker.book2D("ToT vs LS",title +" ToT vs LS;LS;ToT(ns)",4000,0,4000, 200,5,25); + // trackTimeVsLS=ibooker.book2D("track time vs LS",title+" track time vs LS;LS;track_time(ns)",4000,0,4000, 500, -25, 25); + trackTimeVsBX = + ibooker.book2D("track time vs BX", title + " track time vs BX;BX;track_time(ns)", 4000, 0, 4000, 500, -25, 25); + // trackTimeVsXAngle = ibooker.book2D( + // "track time vs xangle", title + " track time vs xangle;xangle;track_time(ns)", 60, 120, 180, 500, -25, 25); + + // TOTVsLSProfile=ibooker.bookProfile("ToT vs LS profile",title+" ToT vs LS profile;LS;track_time(ns)", 500, -25, 25,4000,0,4000); + // trackTimeVsLSProfile=ibooker.bookProfile("track time vs LS profile",title+" track time vs LS profile;LS;track_time(ns)", 500, -25, 25,4000,0,4000); + trackTimeVsBXProfile = ibooker.bookProfile( + "track time vs BX profile", title + " track time vs BX profile;BX;track_time(ns)", 500, -25, 25, 4000, 0, 4000); + // trackTimeVsXAngleProfile = ibooker.bookProfile("track time vs xangle profile", + // title + " track time vs xangle profile;xangle;track_time(ns)", + // 500, + // -25, + // 25, + // 60, + // 120, + // 180); + ibooker.setCurrentFolder(path); + } + + for (unsigned int i = 0; i < windowsNum; i++) { + std::string window = std::to_string(i * 25) + "-" + std::to_string((i + 1) * 25); + activity_per_bx[i] = ibooker.book1D( + "activity per BX " + window, title + " Activity per BX " + window + " ns;Event.BX", 3600, -1.5, 3598. + 0.5); + pixelTomographyAll[i] = + ibooker.book2D("tomography pixel " + window, + title + " tomography with pixel " + window + " ns (all planes);x + 25*plane(mm);y (mm)", + 100, + 0, + 100, + 10, + -5, + 5); + } hitDistribution2d = ibooker.book2D("hits in planes", title + " hits in planes;plane number;x (mm)", @@ -258,38 +375,33 @@ CTPPSDiamondDQMSource::PotPlots::PotPlots(DQMStore::IBooker& ibooker, unsigned i 19. * INV_DISPLAY_RESOLUTION_FOR_HITS_MM, -0.5, 18.5); - hitDistribution2d_lumisection = ibooker.book2D("hits in planes lumisection", - title + " hits in planes in the last lumisection;plane number;x (mm)", - 10, - -0.5, - 4.5, - 19. * INV_DISPLAY_RESOLUTION_FOR_HITS_MM, - -0.5, - 18.5); + hitDistribution2dOOT = ibooker.book2D("hits with OOT in planes", - title + " hits with OOT in planes;plane number + 0.25 OOT;x (mm)", - 17, - -0.25, + title + " hits with OOT in planes;plane number, OOT index;x (mm)", + 1 + windowsNum * 4, + -1. / windowsNum, 4, 19. * INV_DISPLAY_RESOLUTION_FOR_HITS_MM, -0.5, 18.5); - hitDistribution2dOOT_le = ibooker.book2D("hits with OOT in planes (le only)", - title + " hits with OOT in planes (le only);plane number + 0.25 OOT;x (mm)", - 17, - -0.25, - 4, - 19. * INV_DISPLAY_RESOLUTION_FOR_HITS_MM, - -0.5, - 18.5); + + { // bin labelling (for clarity) + int idx = 2; // start counting at 1, first bin is empty + for (int pl = 0; pl < 4; ++pl) + for (unsigned int oot = 0; oot < windowsNum; ++oot) { + const std::string bin_label = + (oot == 0 ? "Plane " + std::to_string(pl) + ", " : "") + "OOT" + std::to_string(oot); + hitDistribution2dOOT->setBinLabel(idx, bin_label); + if (plotOnline) + hitDistribution2dOOT_le->setBinLabel(idx, bin_label); + ++idx; + } + } + + recHitTime = ibooker.book1D("recHit time", title + " recHit time; t (ns)", 500, -25, 25); + activePlanes = ibooker.book1D("active planes", title + " active planes (per event);number of active planes", 6, -0.5, 5.5); - activePlanesInclusive = - ibooker.book1D("active planes inclusive", - title + " active planes, MH and le only included (per event);number of active planes", - 6, - -0.5, - 5.5); trackDistribution = ibooker.book1D("tracks", title + " tracks;x (mm)", 19. * INV_DISPLAY_RESOLUTION_FOR_HITS_MM, -0.5, 18.5); @@ -302,53 +414,37 @@ CTPPSDiamondDQMSource::PotPlots::PotPlots(DQMStore::IBooker& ibooker, unsigned i -0.5, 18.5); - pixelTomographyAll[0] = - ibooker.book2D("tomography pixel 0 25", - title + " tomography with pixel 0 - 25 ns (all planes);x + 25*plane(mm);y (mm)", - 100, - 0, - 100, - 8, - 0, - 8); - pixelTomographyAll[1] = - ibooker.book2D("tomography pixel 25 50", - title + " tomography with pixel 25 - 50 ns (all planes);x + 25*plane(mm);y (mm)", - 100, - 0, - 100, - 8, - 0, - 8); - pixelTomographyAll[2] = - ibooker.book2D("tomography pixel 50 75", - title + " tomography with pixel 50 - 75 ns (all planes);x + 25*plane(mm);y (mm)", - 100, - 0, - 100, - 8, - 0, - 8); - - leadingEdgeCumulative_both = ibooker.book1D( - "leading edge (le and te)", title + " leading edge (le and te) (recHits); leading edge (ns)", 75, 0, 75); - leadingEdgeCumulative_all = ibooker.book1D( - "leading edge (all)", title + " leading edge (with or without te) (DIGIs); leading edge (ns)", 75, 0, 75); - leadingEdgeCumulative_le = - ibooker.book1D("leading edge (le only)", title + " leading edge (le only) (DIGIs); leading edge (ns)", 75, 0, 75); - trailingEdgeCumulative_te = ibooker.book1D( - "trailing edge (te only)", title + " trailing edge (te only) (DIGIs); trailing edge (ns)", 75, 0, 75); + leadingEdgeCumulative_both = ibooker.book1D("leading edge (le and te)", + title + " leading edge (le and te) (recHits); leading edge (ns)", + 25 * windowsNum, + 0, + 25 * windowsNum); + leadingEdgeCumulative_all = ibooker.book1D("leading edge (all)", + title + " leading edge (with or without te) (DIGIs); leading edge (ns)", + 25 * windowsNum, + 0, + 25 * windowsNum); + leadingEdgeCumulative_le = ibooker.book1D("leading edge (le only)", + title + " leading edge (le only) (DIGIs); leading edge (ns)", + 25 * windowsNum, + 0, + 25 * windowsNum); + trailingEdgeCumulative_te = ibooker.book1D("trailing edge (te only)", + title + " trailing edge (te only) (DIGIs); trailing edge (ns)", + 25 * windowsNum, + 0, + 25 * windowsNum); timeOverThresholdCumulativePot = ibooker.book1D("time over threshold", title + " time over threshold;time over threshold (ns)", 250, -25, 100); - leadingTrailingCorrelationPot = - ibooker.book2D("leading trailing correlation", - title + " leading trailing correlation;leading edge (ns);trailing edge (ns)", - 75, - 0, - 75, - 75, - 0, - 75); + // leadingTrailingCorrelationPot = + // ibooker.book2D("leading trailing correlation", + // title + " leading trailing correlation;leading edge (ns);trailing edge (ns)", + // 75, + // 0, + // 75, + // 75, + // 0, + // 75); leadingWithoutTrailingCumulativePot = ibooker.book1D("event category", title + " leading edges without trailing;;%", 3, 0.5, 3.5); @@ -356,8 +452,6 @@ CTPPSDiamondDQMSource::PotPlots::PotPlots(DQMStore::IBooker& ibooker, unsigned i leadingWithoutTrailingCumulativePot->setBinLabel(2, "Trailing only"); leadingWithoutTrailingCumulativePot->setBinLabel(3, "Both"); - ECCheck = ibooker.book1D("optorxEC(8bit) - vfatEC", title + " EC Error;optorxEC-vfatEC", 50, -25, 25); - HPTDCErrorFlags_2D = ibooker.book2D("HPTDC Errors", title + " HPTDC Errors", 16, -0.5, 16.5, 9, -0.5, 8.5); for (unsigned short error_index = 1; error_index < 16; ++error_index) HPTDCErrorFlags_2D->setBinLabel(error_index, HPTDCErrorFlags::hptdcErrorName(error_index - 1)); @@ -376,16 +470,6 @@ CTPPSDiamondDQMSource::PotPlots::PotPlots(DQMStore::IBooker& ibooker, unsigned i MHComprensive = ibooker.book2D("MH in channels", title + " MH (%) in channels;plane number;ch number", 10, -0.5, 4.5, 14, -1, 13); - EfficiencyOfChannelsInPot = - ibooker.book2D("Efficiency in channels", - title + " Efficiency (%) in channels (diamonds only);plane number;ch number", - 10, - -0.5, - 4.5, - 14, - -1, - 13); - // ibooker.setCurrentFolder( path+"/clock/" ); // clock_Digi1_le = ibooker.book1D( "clock1 leading edge", title+" clock1;leading edge (ns)", 250, 0, 25 ); // clock_Digi1_te = ibooker.book1D( "clock1 trailing edge", title+" clock1;trailing edge (ns)", 75, 0, 75 ); @@ -395,7 +479,7 @@ CTPPSDiamondDQMSource::PotPlots::PotPlots(DQMStore::IBooker& ibooker, unsigned i //---------------------------------------------------------------------------------------------------- -CTPPSDiamondDQMSource::PlanePlots::PlanePlots(DQMStore::IBooker& ibooker, unsigned int id) +CTPPSDiamondDQMSource::PlanePlots::PlanePlots(DQMStore::IBooker& ibooker, unsigned int id, unsigned int windowsNum) : pixelTracksMapWithDiamonds("Pixel track maps for efficiency with coincidence", "Pixel track maps for efficiency with coincidence", 25, @@ -410,20 +494,30 @@ CTPPSDiamondDQMSource::PlanePlots::PlanePlots(DQMStore::IBooker& ibooker, unsign CTPPSDiamondDetId(id).planeName(title, CTPPSDiamondDetId::nFull); - digiProfileCumulativePerPlane = ibooker.book1D("digi profile", title + " digi profile; ch number", 12, -0.5, 11.5); + digiProfileCumulativePerPlane = ibooker.book1D("digi profile", + title + " digi profile; ch number", + CTPPS_DIAMOND_NUM_OF_CHANNELS, + -0.5, + CTPPS_DIAMOND_NUM_OF_CHANNELS - 0.5); hitProfile = ibooker.book1D( "hit profile", title + " hit profile;x (mm)", 19. * INV_DISPLAY_RESOLUTION_FOR_HITS_MM, -0.5, 18.5); hit_multiplicity = ibooker.book1D("channels per plane", title + " channels per plane; ch per plane", 13, -0.5, 12.5); - pixelTomography_far = - ibooker.book2D("tomography pixel", title + " tomography with pixel;x + 25 OOT (mm);y (mm)", 75, 0, 75, 8, 0, 8); + pixelTomography_far = ibooker.book2D("tomography pixel", + title + " tomography with pixel;x + 25 OOT (mm);y (mm)", + 25 * windowsNum, + 0, + 25 * windowsNum, + 8, + 0, + 8); EfficiencyWRTPixelsInPlane = ibooker.book2D("Efficiency wrt pixels", title + " Efficiency wrt pixels;x (mm);y (mm)", 25, 0, 25, 12, -2, 10); } //---------------------------------------------------------------------------------------------------- -CTPPSDiamondDQMSource::ChannelPlots::ChannelPlots(DQMStore::IBooker& ibooker, unsigned int id) +CTPPSDiamondDQMSource::ChannelPlots::ChannelPlots(DQMStore::IBooker& ibooker, unsigned int id, unsigned int windowsNum) : HitCounter(0), MHCounter(0), LeadingOnlyCounter(0), TrailingOnlyCounter(0), CompleteCounter(0) { std::string path, title; CTPPSDiamondDetId(id).channelName(path, CTPPSDiamondDetId::nPath); @@ -436,62 +530,77 @@ CTPPSDiamondDQMSource::ChannelPlots::ChannelPlots(DQMStore::IBooker& ibooker, un leadingWithoutTrailing->setBinLabel(2, "Trailing only"); leadingWithoutTrailing->setBinLabel(3, "Full"); - activity_per_bx[0] = - ibooker.book1D("activity per BX 0 25", title + " Activity per BX 0 - 25 ns;Event.BX", 500, -1.5, 498. + 0.5); - activity_per_bx[1] = - ibooker.book1D("activity per BX 25 50", title + " Activity per BX 25 - 50 ns;Event.BX", 500, -1.5, 498. + 0.5); - activity_per_bx[2] = - ibooker.book1D("activity per BX 50 75", title + " Activity per BX 50 - 75 ns;Event.BX", 500, -1.5, 498. + 0.5); + for (unsigned int i = 0; i < windowsNum; i++) { + std::string window = std::to_string(i * 25) + "-" + std::to_string((i + 1) * 25); + activity_per_bx[i] = ibooker.book1D( + "activity per BX " + window, title + " Activity per BX " + window + " ns;Event.BX", 3600, -1.5, 3598. + 0.5); + } HPTDCErrorFlags = ibooker.book1D("hptdc_Errors", title + " HPTDC Errors", 16, -0.5, 16.5); for (unsigned short error_index = 1; error_index < 16; ++error_index) HPTDCErrorFlags->setBinLabel(error_index, HPTDCErrorFlags::hptdcErrorName(error_index - 1)); HPTDCErrorFlags->setBinLabel(16, "MH (%)"); - leadingEdgeCumulative_both = - ibooker.book1D("leading edge (le and te)", title + " leading edge (recHits); leading edge (ns)", 75, 0, 75); - leadingEdgeCumulative_le = - ibooker.book1D("leading edge (le only)", title + " leading edge (DIGIs); leading edge (ns)", 75, 0, 75); - trailingEdgeCumulative_te = ibooker.book1D( - "trailing edge (te only)", title + " trailing edge (te only) (DIGIs); trailing edge (ns)", 75, 0, 75); + leadingEdgeCumulative_both = ibooker.book1D("leading edge (le and te)", + title + " leading edge (recHits); leading edge (ns)", + 25 * windowsNum, + 0, + 25 * windowsNum); + leadingEdgeCumulative_le = ibooker.book1D( + "leading edge (le only)", title + " leading edge (DIGIs); leading edge (ns)", 25 * windowsNum, 0, 25 * windowsNum); + trailingEdgeCumulative_te = ibooker.book1D("trailing edge (te only)", + title + " trailing edge (te only) (DIGIs); trailing edge (ns)", + 25 * windowsNum, + 0, + 25 * windowsNum); TimeOverThresholdCumulativePerChannel = ibooker.book1D("time over threshold", title + " time over threshold;time over threshold (ns)", 75, -25, 50); - LeadingTrailingCorrelationPerChannel = - ibooker.book2D("leading trailing correlation", - title + " leading trailing correlation;leading edge (ns);trailing edge (ns)", - 75, - 0, - 75, - 75, - 0, - 75); - - pixelTomography_far = - ibooker.book2D("tomography pixel", "tomography with pixel;x + 25 OOT (mm);y (mm)", 75, 0, 75, 8, 0, 8); + // LeadingTrailingCorrelationPerChannel = + // ibooker.book2D("leading trailing correlation", + // title + " leading trailing correlation;leading edge (ns);trailing edge (ns)", + // 75, + // 0, + // 75, + // 75, + // 0, + // 75); + + pixelTomography_far = ibooker.book2D( + "tomography pixel", "tomography with pixel;x + 25 OOT (mm);y (mm)", 25 * windowsNum, 0, 25 * windowsNum, 8, 0, 8); hit_rate = ibooker.book1D("hit rate", title + "hit rate;rate (Hz)", 40, 0, 20); + + recHitTime = ibooker.book1D("recHit Time", title + " recHit Time; t (ns)", 500, -25, 25); } //---------------------------------------------------------------------------------------------------- CTPPSDiamondDQMSource::CTPPSDiamondDQMSource(const edm::ParameterSet& ps) - : tokenStatus_(consumes>(ps.getParameter("tagStatus"))), - tokenPixelTrack_( + : tokenPixelTrack_( consumes>(ps.getParameter("tagPixelLocalTracks"))), - tokenDigi_(consumes>(ps.getParameter("tagDigi"))), tokenDiamondHit_( consumes>(ps.getParameter("tagDiamondRecHits"))), tokenDiamondTrack_( consumes>(ps.getParameter("tagDiamondLocalTracks"))), - tokenFEDInfo_(consumes>(ps.getParameter("tagFEDInfo"))), ctppsGeometryRunToken_(esConsumes()), ctppsGeometryEventToken_(esConsumes()), + // ctppsLhcInfoToken_(esConsumes()), excludeMultipleHits_(ps.getParameter("excludeMultipleHits")), perLSsaving_(ps.getUntrackedParameter("perLSsaving", false)), + extract_digi_info_(ps.getParameter("extractDigiInfo")), centralOOT_(-999), verbosity_(ps.getUntrackedParameter("verbosity", 0)), + plotOnline_(ps.getUntrackedParameter("plotOnline", true)), + plotOffline_(ps.getUntrackedParameter("plotOffline", false)), + windowsNum_(ps.getUntrackedParameter("windowsNum", 3)), + trackCorrelationThreshold_(ps.getUntrackedParameter("trackCorrelationThreshold", 3)), 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")); + } for (const auto& pset : ps.getParameter>("offsetsOOT")) { runParameters_.emplace_back( std::make_pair(pset.getParameter("validityRange"), pset.getParameter("centralOOT"))); @@ -500,10 +609,6 @@ CTPPSDiamondDQMSource::CTPPSDiamondDQMSource(const edm::ParameterSet& ps) //---------------------------------------------------------------------------------------------------- -CTPPSDiamondDQMSource::~CTPPSDiamondDQMSource() {} - -//---------------------------------------------------------------------------------------------------- - void CTPPSDiamondDQMSource::dqmBeginRun(const edm::Run& iRun, const edm::EventSetup& iSetup) { centralOOT_ = -999; for (const auto& oot : runParameters_) { @@ -515,38 +620,52 @@ void CTPPSDiamondDQMSource::dqmBeginRun(const edm::Run& iRun, const edm::EventSe // Get detector shifts from the geometry const CTPPSGeometry& geom = iSetup.getData(ctppsGeometryRunToken_); - const CTPPSDiamondDetId detid(0, CTPPS_DIAMOND_STATION_ID, CTPPS_DIAMOND_RP_ID, 0, 0); - const DetGeomDesc* det = geom.sensor(detid); - horizontalShiftOfDiamond_ = det->translation().x() - det->getDiamondDimensions().xHalfWidth; - - // Rough alignement of pixel detector for diamond thomography - const CTPPSPixelDetId pixid(0, CTPPS_PIXEL_STATION_ID, CTPPS_FAR_RP_ID, 0); - if (iRun.run() > 300000) { //Pixel installed - det = geom.sensor(pixid); - horizontalShiftBwDiamondPixels_ = - det->translation().x() - det->getDiamondDimensions().xHalfWidth - horizontalShiftOfDiamond_ - 1; - } + for (auto it = geom.beginRP(); it != geom.endRP(); ++it) + if (CTPPSDiamondDetId::check(it->first)) { + const CTPPSDiamondDetId diam_id(it->first); + const auto diam = geom.sensor(it->first); + diamShifts_[diam_id].global = diam->translation().x() - diam->getDiamondDimensions().xHalfWidth; + if (iRun.run() > FIRST_RUN_W_PIXELS) { // pixel installed + const CTPPSPixelDetId pixid(diam_id.arm(), CTPPS_PIXEL_STATION_ID, CTPPS_FAR_RP_ID); + auto pix = geom.sensor(pixid); + // Rough alignement of pixel detector for diamond tomography + diamShifts_[diam_id].withPixels = + pix->translation().x() - pix->getDiamondDimensions().xHalfWidth - diamShifts_[diam_id].global - 1.; + } + } } //---------------------------------------------------------------------------------------------------- -void CTPPSDiamondDQMSource::bookHistograms(DQMStore::IBooker& ibooker, const edm::Run&, const edm::EventSetup&) { +void CTPPSDiamondDQMSource::bookHistograms(DQMStore::IBooker& ibooker, const edm::Run&, const edm::EventSetup& iSetup) { ibooker.cd(); ibooker.setCurrentFolder("CTPPS"); globalPlot_ = GlobalPlots(ibooker); - for (unsigned short arm = 0; arm < CTPPS_NUM_OF_ARMS; ++arm) { - const CTPPSDiamondDetId rpId(arm, CTPPS_DIAMOND_STATION_ID, CTPPS_DIAMOND_RP_ID); - potPlots_[rpId] = PotPlots(ibooker, rpId); - for (unsigned short pl = 0; pl < CTPPS_DIAMOND_NUM_OF_PLANES; ++pl) { - const CTPPSDiamondDetId plId(arm, CTPPS_DIAMOND_STATION_ID, CTPPS_DIAMOND_RP_ID, pl); - planePlots_[plId] = PlanePlots(ibooker, plId); - for (unsigned short ch = 0; ch < CTPPS_DIAMOND_NUM_OF_CHANNELS; ++ch) { - const CTPPSDiamondDetId chId(arm, CTPPS_DIAMOND_STATION_ID, CTPPS_DIAMOND_RP_ID, pl, ch); - channelPlots_[chId] = ChannelPlots(ibooker, chId); - } - } + // book plots from the geometry + const CTPPSGeometry& geom = iSetup.getData(ctppsGeometryRunToken_); + for (auto it = geom.beginSensor(); it != geom.endSensor(); ++it) { + if (!CTPPSDiamondDetId::check(it->first)) + continue; + // per-channel plots + const CTPPSDiamondDetId chId(it->first); + if (plotOnline_ && channelPlots_.count(chId) == 0) + channelPlots_[chId] = ChannelPlots(ibooker, chId, windowsNum_); + + // per-plane plots + const CTPPSDiamondDetId plId(chId.planeId()); + if (planePlots_.count(plId) == 0) + planePlots_[plId] = PlanePlots(ibooker, plId, windowsNum_); + // per-pot plots + const CTPPSDiamondDetId rpId(chId.rpId()); + if (potPlots_.count(rpId) == 0) + potPlots_[rpId] = PotPlots(ibooker, rpId, windowsNum_, plotOnline_, plotOffline_); + + // per-sector plots + const CTPPSDiamondDetId secId(chId.armId()); + if (plotOffline_ && sectorPlots_.count(secId) == 0) + sectorPlots_[secId] = SectorPlots(ibooker, secId, plotOnline_); } } @@ -556,7 +675,7 @@ std::shared_ptr CTPPSDiamondDQMSource::globalBeginLuminosityBlock(co const edm::EventSetup&) const { auto d = std::make_shared(); d->hitDistribution2dMap.reserve(potPlots_.size()); - if (!perLSsaving_) { + if (!perLSsaving_ && plotOnline_) { for (auto& plot : potPlots_) d->hitDistribution2dMap[plot.first] = std::unique_ptr(static_cast(plot.second.hitDistribution2d_lumisection->getTH2F()->Clone())); @@ -568,18 +687,19 @@ std::shared_ptr CTPPSDiamondDQMSource::globalBeginLuminosityBlock(co void CTPPSDiamondDQMSource::analyze(const edm::Event& event, const edm::EventSetup& iSetup) { // get event data + edm::Handle> diamondVFATStatus; - event.getByToken(tokenStatus_, diamondVFATStatus); + edm::Handle> diamondDigis; + edm::Handle> fedInfo; + if (extract_digi_info_) { + event.getByToken(tokenStatus_, diamondVFATStatus); + event.getByToken(tokenDigi_, diamondDigis); + event.getByToken(tokenFEDInfo_, fedInfo); + } edm::Handle> pixelTracks; event.getByToken(tokenPixelTrack_, pixelTracks); - edm::Handle> diamondDigis; - event.getByToken(tokenDigi_, diamondDigis); - - edm::Handle> fedInfo; - event.getByToken(tokenFEDInfo_, fedInfo); - edm::Handle> diamondRecHits; event.getByToken(tokenDiamondHit_, diamondRecHits); @@ -587,32 +707,82 @@ void CTPPSDiamondDQMSource::analyze(const edm::Event& event, const edm::EventSet event.getByToken(tokenDiamondTrack_, diamondLocalTracks); const CTPPSGeometry* ctppsGeometry = &iSetup.getData(ctppsGeometryEventToken_); + // const LHCInfo* hLhcInfo = &iSetup.getData(ctppsLhcInfoToken_); // check validity bool valid = true; - valid &= diamondVFATStatus.isValid(); + if (extract_digi_info_) { // drop DIGI-level validity checks if not monitored + valid &= diamondVFATStatus.isValid(); + valid &= diamondDigis.isValid(); + valid &= fedInfo.isValid(); + } valid &= pixelTracks.isValid(); - valid &= diamondDigis.isValid(); - valid &= fedInfo.isValid(); valid &= diamondRecHits.isValid(); valid &= diamondLocalTracks.isValid(); if (!valid) { - if (verbosity_) { + if (verbosity_) edm::LogProblem("CTPPSDiamondDQMSource") << "ERROR in CTPPSDiamondDQMSource::analyze > some of the required inputs are not valid. Skipping this " "event.\n" + << " DIGI-level: (checked? " << std::boolalpha << extract_digi_info_ << ")\n" << " diamondVFATStatus.isValid = " << diamondVFATStatus.isValid() << "\n" - << " pixelTracks.isValid = " << pixelTracks.isValid() << "\n" << " diamondDigis.isValid = " << diamondDigis.isValid() << "\n" << " fedInfo.isValid = " << fedInfo.isValid() << "\n" + << " RECO-level:\n" + << " pixelTracks.isValid = " << pixelTracks.isValid() << "\n" << " diamondRecHits.isValid = " << diamondRecHits.isValid() << "\n" << " diamondLocalTracks.isValid = " << diamondLocalTracks.isValid(); - } - return; } + //------------------------------ + // Sector Plots + //------------------------------ + // Using CTPPSDiamondLocalTrack + if (plotOffline_) + for (const auto& tracks : *diamondLocalTracks) { + const CTPPSDiamondDetId detId_near(tracks.detId()); + + for (const auto& track : tracks) { + if (!track.isValid()) + continue; + if (potPlots_.count(detId_near.rpId()) == 0) + continue; + TH1F* trackHistoInTimeTmp = potPlots_[detId_near.rpId()].trackDistribution->getTH1F(); + int startBin_near = + trackHistoInTimeTmp->FindBin(track.x0() - diamShifts_[detId_near.rpId()].global - track.x0Sigma()); + int numOfBins_near = 2 * track.x0Sigma() * INV_DISPLAY_RESOLUTION_FOR_HITS_MM; + + for (const auto& tracks_far : *diamondLocalTracks) { + CTPPSDiamondDetId detId_far(tracks_far.detId()); + if (detId_near.arm() != detId_far.arm() || detId_near.station() == detId_far.station()) + continue; + for (const auto& track_far : tracks_far) { + if (!track.isValid()) + continue; + if (sectorPlots_.count(detId_far.armId()) == 0) + continue; + TH2F* trackHistoTmp = sectorPlots_[detId_far.armId()].trackCorrelation->getTH2F(); + TAxis* trackHistoTmpXAxis = trackHistoTmp->GetXaxis(); + TAxis* trackHistoTmpYAxis = trackHistoTmp->GetYaxis(); + int startBin_far = trackHistoTmpYAxis->FindBin(track_far.x0() - diamShifts_[detId_far.rpId()].global - + track_far.x0Sigma()); + int numOfBins_far = 2 * track_far.x0Sigma() * INV_DISPLAY_RESOLUTION_FOR_HITS_MM; + for (int i = 0; i < numOfBins_near; ++i) + for (int y = 0; y < numOfBins_far; ++y) { + trackHistoTmp->Fill(trackHistoTmpXAxis->GetBinCenter(startBin_near + i), + trackHistoTmpYAxis->GetBinCenter(startBin_far + y)); + if (tracks.size() < 3 && tracks_far.size() < trackCorrelationThreshold_) + sectorPlots_[detId_far.armId()].trackCorrelationLowMultiplicity->Fill( + trackHistoTmpXAxis->GetBinCenter(startBin_near + i), + trackHistoTmpYAxis->GetBinCenter(startBin_far + y)); + } + } + } + } + } + //------------------------------ // RP Plots //------------------------------ @@ -621,97 +791,69 @@ void CTPPSDiamondDQMSource::analyze(const edm::Event& event, const edm::EventSet // Correlation Plots //------------------------------ - // Using CTPPSDiamondDigi - for (const auto& digis : *diamondDigis) { - const CTPPSDiamondDetId detId(digis.detId()); - CTPPSDiamondDetId detId_pot(digis.detId()); - - for (const auto& digi : digis) { - detId_pot.setPlane(0); - detId_pot.setChannel(0); - if (detId.channel() == CHANNEL_OF_VFAT_CLOCK) - continue; - if (potPlots_.find(detId_pot) == potPlots_.end()) - continue; - //Leading without trailing investigation - if (digi.leadingEdge() != 0 || digi.trailingEdge() != 0) { - ++(potPlots_[detId_pot].HitCounter); - if (digi.leadingEdge() != 0) { - potPlots_[detId_pot].leadingEdgeCumulative_all->Fill(HPTDC_BIN_WIDTH_NS * digi.leadingEdge()); - } - if (digi.leadingEdge() != 0 && digi.trailingEdge() == 0) { - ++(potPlots_[detId_pot].LeadingOnlyCounter); - potPlots_[detId_pot].leadingEdgeCumulative_le->Fill(HPTDC_BIN_WIDTH_NS * digi.leadingEdge()); - } - if (digi.leadingEdge() == 0 && digi.trailingEdge() != 0) { - ++(potPlots_[detId_pot].TrailingOnlyCounter); - potPlots_[detId_pot].trailingEdgeCumulative_te->Fill(HPTDC_BIN_WIDTH_NS * digi.trailingEdge()); - } - if (digi.leadingEdge() != 0 && digi.trailingEdge() != 0) { - ++(potPlots_[detId_pot].CompleteCounter); - potPlots_[detId_pot].leadingTrailingCorrelationPot->Fill(HPTDC_BIN_WIDTH_NS * digi.leadingEdge(), - HPTDC_BIN_WIDTH_NS * digi.trailingEdge()); + if (extract_digi_info_) { + // Using CTPPSDiamondDigi + for (const auto& digis : *diamondDigis) { + const CTPPSDiamondDetId detId(digis.detId()), detId_pot(detId.rpId()); + for (const auto& digi : digis) { + if (detId.channel() == CHANNEL_OF_VFAT_CLOCK) + continue; + if (potPlots_.count(detId_pot) == 0) + continue; + //Leading without trailing investigation + if (digi.leadingEdge() != 0 || digi.trailingEdge() != 0) { + ++potPlots_[detId_pot].HitCounter; + if (digi.leadingEdge() != 0) { + potPlots_[detId_pot].leadingEdgeCumulative_all->Fill(HPTDC_BIN_WIDTH_NS * digi.leadingEdge()); + } + if (digi.leadingEdge() != 0 && digi.trailingEdge() == 0) { + ++potPlots_[detId_pot].LeadingOnlyCounter; + potPlots_[detId_pot].leadingEdgeCumulative_le->Fill(HPTDC_BIN_WIDTH_NS * digi.leadingEdge()); + } + if (digi.leadingEdge() == 0 && digi.trailingEdge() != 0) { + ++potPlots_[detId_pot].TrailingOnlyCounter; + potPlots_[detId_pot].trailingEdgeCumulative_te->Fill(HPTDC_BIN_WIDTH_NS * digi.trailingEdge()); + } + if (digi.leadingEdge() != 0 && digi.trailingEdge() != 0) { + ++potPlots_[detId_pot].CompleteCounter; + // potPlots_[detId_pot].leadingTrailingCorrelationPot->Fill(HPTDC_BIN_WIDTH_NS * digi.leadingEdge(), + // HPTDC_BIN_WIDTH_NS * digi.trailingEdge()); + } } - } - // HPTDC Errors - const HPTDCErrorFlags hptdcErrors = digi.hptdcErrorFlags(); - if (detId.channel() == 6 || detId.channel() == 7) // ch6 for HPTDC 0 and ch7 for HPTDC 1 - { - int verticalIndex = 2 * detId.plane() + (detId.channel() - 6); - for (unsigned short hptdcErrorIndex = 1; hptdcErrorIndex < 16; ++hptdcErrorIndex) - if (hptdcErrors.errorId(hptdcErrorIndex - 1)) - potPlots_[detId_pot].HPTDCErrorFlags_2D->Fill(hptdcErrorIndex, verticalIndex); + // HPTDC Errors + const HPTDCErrorFlags hptdcErrors = digi.hptdcErrorFlags(); + if (detId.channel() == HPTDC_0_CHANNEL || + detId.channel() == HPTDC_1_CHANNEL) { // ch6 for HPTDC 0 and ch7 for HPTDC 1 + int verticalIndex = 2 * detId.plane() + (detId.channel() - HPTDC_0_CHANNEL); + for (unsigned short hptdcErrorIndex = 1; hptdcErrorIndex < 16; ++hptdcErrorIndex) + if (hptdcErrors.errorId(hptdcErrorIndex - 1)) + potPlots_[detId_pot].HPTDCErrorFlags_2D->Fill(hptdcErrorIndex, verticalIndex); + } + if (digi.multipleHit()) + ++potPlots_[detId_pot].MHCounter; } - if (digi.multipleHit()) - ++(potPlots_[detId_pot].MHCounter); } } // EC Errors - for (const auto& vfat_status : *diamondVFATStatus) { - const CTPPSDiamondDetId detId(vfat_status.detId()); - CTPPSDiamondDetId detId_pot(vfat_status.detId()); - detId_pot.setPlane(0); - detId_pot.setChannel(0); - for (const auto& status : vfat_status) { - if (!status.isOK()) - continue; - if (potPlots_.find(detId_pot) == potPlots_.end()) - continue; - if (channelPlots_.find(detId) == channelPlots_.end()) - continue; + if (extract_digi_info_) { + for (const auto& vfat_status : *diamondVFATStatus) { + const CTPPSDiamondDetId detId(vfat_status.detId()); + for (const auto& status : vfat_status) { + if (!status.isOK()) + continue; + if (potPlots_.count(detId.rpId()) == 0) + continue; + if (channelPlots_.count(detId) == 0) + continue; - // Check Event Number - for (const auto& optorx : *fedInfo) { - if (detId.arm() == 1 && optorx.fedId() == CTPPS_FED_ID_56) { - potPlots_[detId_pot].ECCheck->Fill((int)((optorx.lv1() & 0xFF) - ((unsigned int)status.ec() & 0xFF)) & 0xFF); - if ((static_cast((optorx.lv1() & 0xFF) - status.ec()) != EC_difference_56_) && - (static_cast((optorx.lv1() & 0xFF) - status.ec()) < 128)) - EC_difference_56_ = static_cast(optorx.lv1() & 0xFF) - (static_cast(status.ec()) & 0xFF); - if (EC_difference_56_ != 1 && EC_difference_56_ != -500 && std::abs(EC_difference_56_) < 127) { - if (detId.channel() == 6 || detId.channel() == 7) - potPlots_[detId_pot].HPTDCErrorFlags_2D->Fill(16, 2 * detId.plane() + (detId.channel() - 6)); - if (verbosity_) - edm::LogProblem("CTPPSDiamondDQMSource") - << "FED " << CTPPS_FED_ID_56 << ": ECError at EV: 0x" << std::hex << optorx.lv1() << "\t\tVFAT EC: 0x" - << static_cast(status.ec()) << "\twith ID: " << std::dec << detId - << "\tdiff: " << EC_difference_56_; - } - } else if (detId.arm() == 0 && optorx.fedId() == CTPPS_FED_ID_45) { - potPlots_[detId_pot].ECCheck->Fill((int)((optorx.lv1() & 0xFF) - status.ec()) & 0xFF); - if ((static_cast((optorx.lv1() & 0xFF) - status.ec()) != EC_difference_45_) && - (static_cast((optorx.lv1() & 0xFF) - status.ec()) < 128)) - EC_difference_45_ = static_cast(optorx.lv1() & 0xFF) - (static_cast(status.ec()) & 0xFF); - if (EC_difference_45_ != 1 && EC_difference_45_ != -500 && std::abs(EC_difference_45_) < 127) { - if (detId.channel() == 6 || detId.channel() == 7) - potPlots_[detId_pot].HPTDCErrorFlags_2D->Fill(16, 2 * detId.plane() + (detId.channel() - 6)); - if (verbosity_) - edm::LogProblem("CTPPSDiamondDQMSource") - << "FED " << CTPPS_FED_ID_45 << ": ECError at EV: 0x" << std::hex << optorx.lv1() << "\t\tVFAT EC: 0x" - << static_cast(status.ec()) << "\twith ID: " << std::dec << detId - << "\tdiff: " << EC_difference_45_; - } + // Check Event Number + for (const auto& optorx : *fedInfo) { + if (detId.arm() == 1 && optorx.fedId() == CTPPS_FED_ID_56) + checkEventNumber(detId, optorx, status, potPlots_[detId.rpId()], EC_difference_56_); + else if (detId.arm() == 0 && optorx.fedId() == CTPPS_FED_ID_45) + checkEventNumber(detId, optorx, status, potPlots_[detId.rpId()], EC_difference_45_); } } } @@ -723,10 +865,8 @@ void CTPPSDiamondDQMSource::analyze(const edm::Event& event, const edm::EventSet auto lumiCache = luminosityBlockCache(event.getLuminosityBlock().index()); for (const auto& rechits : *diamondRecHits) { - CTPPSDiamondDetId detId_pot(rechits.detId()); - detId_pot.setPlane(0); - detId_pot.setChannel(0); - const CTPPSDiamondDetId detId(rechits.detId()); + const CTPPSDiamondDetId detId(rechits.detId()), detId_pot(detId.rpId()); + const auto& x_shift = diamShifts_.at(detId_pot); for (const auto& rechit : rechits) { planes_inclusive[detId_pot].insert(detId.plane()); @@ -735,9 +875,11 @@ void CTPPSDiamondDQMSource::analyze(const edm::Event& event, const edm::EventSet if (rechit.toT() != 0 && centralOOT_ != -999 && rechit.ootIndex() == centralOOT_) planes[detId_pot].insert(detId.plane()); - if (potPlots_.find(detId_pot) == potPlots_.end()) + if (potPlots_.count(detId_pot) == 0) continue; + potPlots_[detId_pot].recHitTime->Fill(rechit.time()); + float UFSDShift = 0.0; if (rechit.yWidth() < 3) UFSDShift = 0.5; // Display trick for UFSD that have 2 pixels with same X @@ -745,20 +887,18 @@ void CTPPSDiamondDQMSource::analyze(const edm::Event& event, const edm::EventSet if (rechit.toT() != 0 && centralOOT_ != -999 && rechit.ootIndex() == centralOOT_) { TH2F* hitHistoTmp = potPlots_[detId_pot].hitDistribution2d->getTH2F(); TAxis* hitHistoTmpYAxis = hitHistoTmp->GetYaxis(); - int startBin = hitHistoTmpYAxis->FindBin(rechit.x() - horizontalShiftOfDiamond_ - 0.5 * rechit.xWidth()); + int startBin = hitHistoTmpYAxis->FindBin(rechit.x() - x_shift.global - 0.5 * rechit.xWidth()); int numOfBins = rechit.xWidth() * INV_DISPLAY_RESOLUTION_FOR_HITS_MM; - for (int i = 0; i < numOfBins; ++i) { + for (int i = 0; i < numOfBins; ++i) hitHistoTmp->Fill(detId.plane() + UFSDShift, hitHistoTmpYAxis->GetBinCenter(startBin + i)); - } - if (!perLSsaving_) { + if (!perLSsaving_ && plotOnline_) { hitHistoTmp = lumiCache->hitDistribution2dMap[detId_pot].get(); hitHistoTmpYAxis = hitHistoTmp->GetYaxis(); - startBin = hitHistoTmpYAxis->FindBin(rechit.x() - horizontalShiftOfDiamond_ - 0.5 * rechit.xWidth()); + startBin = hitHistoTmpYAxis->FindBin(rechit.x() - x_shift.global - 0.5 * rechit.xWidth()); numOfBins = rechit.xWidth() * INV_DISPLAY_RESOLUTION_FOR_HITS_MM; - for (int i = 0; i < numOfBins; ++i) { + for (int i = 0; i < numOfBins; ++i) hitHistoTmp->Fill(detId.plane() + UFSDShift, hitHistoTmpYAxis->GetBinCenter(startBin + i)); - } } } @@ -769,42 +909,41 @@ void CTPPSDiamondDQMSource::analyze(const edm::Event& event, const edm::EventSet TH2F* hitHistoOOTTmp = potPlots_[detId_pot].hitDistribution2dOOT->getTH2F(); TAxis* hitHistoOOTTmpYAxis = hitHistoOOTTmp->GetYaxis(); - int startBin = hitHistoOOTTmpYAxis->FindBin(rechit.x() - horizontalShiftOfDiamond_ - 0.5 * rechit.xWidth()); + int startBin = hitHistoOOTTmpYAxis->FindBin(rechit.x() - x_shift.global - 0.5 * rechit.xWidth()); + int numOfBins = rechit.xWidth() * INV_DISPLAY_RESOLUTION_FOR_HITS_MM; + for (int i = 0; i < numOfBins; ++i) + hitHistoOOTTmp->Fill(detId.plane() + 0.25 * rechit.ootIndex(), + hitHistoOOTTmpYAxis->GetBinCenter(startBin + i)); + } else if (rechit.ootIndex() != CTPPSDiamondRecHit::TIMESLICE_WITHOUT_LEADING && plotOnline_) { + // Only leading + TH2F* hitHistoOOTTmp = potPlots_[detId_pot].hitDistribution2dOOT_le->getTH2F(); + TAxis* hitHistoOOTTmpYAxis = hitHistoOOTTmp->GetYaxis(); + int startBin = hitHistoOOTTmpYAxis->FindBin(rechit.x() - x_shift.global - 0.5 * rechit.xWidth()); int numOfBins = rechit.xWidth() * INV_DISPLAY_RESOLUTION_FOR_HITS_MM; for (int i = 0; i < numOfBins; ++i) { hitHistoOOTTmp->Fill(detId.plane() + 0.25 * rechit.ootIndex(), hitHistoOOTTmpYAxis->GetBinCenter(startBin + i)); } - } else { - if (rechit.ootIndex() != CTPPSDiamondRecHit::TIMESLICE_WITHOUT_LEADING) { - // Only leading - TH2F* hitHistoOOTTmp = potPlots_[detId_pot].hitDistribution2dOOT_le->getTH2F(); - TAxis* hitHistoOOTTmpYAxis = hitHistoOOTTmp->GetYaxis(); - int startBin = hitHistoOOTTmpYAxis->FindBin(rechit.x() - horizontalShiftOfDiamond_ - 0.5 * rechit.xWidth()); - int numOfBins = rechit.xWidth() * INV_DISPLAY_RESOLUTION_FOR_HITS_MM; - for (int i = 0; i < numOfBins; ++i) { - hitHistoOOTTmp->Fill(detId.plane() + 0.25 * rechit.ootIndex(), - hitHistoOOTTmpYAxis->GetBinCenter(startBin + i)); - } - } } if (rechit.ootIndex() != CTPPSDiamondRecHit::TIMESLICE_WITHOUT_LEADING && potPlots_[detId_pot].activity_per_bx.count(rechit.ootIndex()) > 0) potPlots_[detId_pot].activity_per_bx.at(rechit.ootIndex())->Fill(event.bunchCrossing()); + + // if(plotOffline_) + // potPlots_[detId_pot].TOTVsLS->Fill(event.luminosityBlock(),rechit.toT()); } } for (const auto& plt : potPlots_) { plt.second.activePlanes->Fill(planes[plt.first].size()); - plt.second.activePlanesInclusive->Fill(planes_inclusive[plt.first].size()); + if (plotOnline_) + plt.second.activePlanesInclusive->Fill(planes_inclusive[plt.first].size()); } // Using CTPPSDiamondLocalTrack for (const auto& tracks : *diamondLocalTracks) { - CTPPSDiamondDetId detId_pot(tracks.detId()); - detId_pot.setPlane(0); - detId_pot.setChannel(0); - const CTPPSDiamondDetId detId(tracks.detId()); + const CTPPSDiamondDetId detId(tracks.detId()), detId_pot(detId.rpId()); + const auto& x_shift = diamShifts_.at(detId_pot); for (const auto& track : tracks) { if (!track.isValid()) @@ -813,33 +952,34 @@ void CTPPSDiamondDQMSource::analyze(const edm::Event& event, const edm::EventSet continue; if (excludeMultipleHits_ && track.multipleHits() > 0) continue; - if (potPlots_.find(detId_pot) == potPlots_.end()) + if (potPlots_.count(detId_pot) == 0) continue; TH2F* trackHistoOOTTmp = potPlots_[detId_pot].trackDistributionOOT->getTH2F(); TAxis* trackHistoOOTTmpYAxis = trackHistoOOTTmp->GetYaxis(); - int startBin = trackHistoOOTTmpYAxis->FindBin(track.x0() - horizontalShiftOfDiamond_ - track.x0Sigma()); + int startBin = trackHistoOOTTmpYAxis->FindBin(track.x0() - x_shift.global - track.x0Sigma()); int numOfBins = 2 * track.x0Sigma() * INV_DISPLAY_RESOLUTION_FOR_HITS_MM; - for (int i = 0; i < numOfBins; ++i) { + for (int i = 0; i < numOfBins; ++i) trackHistoOOTTmp->Fill(track.ootIndex(), trackHistoOOTTmpYAxis->GetBinCenter(startBin + i)); - } if (centralOOT_ != -999 && track.ootIndex() == centralOOT_) { TH1F* trackHistoInTimeTmp = potPlots_[detId_pot].trackDistribution->getTH1F(); - int startBin = trackHistoInTimeTmp->FindBin(track.x0() - horizontalShiftOfDiamond_ - track.x0Sigma()); + int startBin = trackHistoInTimeTmp->FindBin(track.x0() - x_shift.global - track.x0Sigma()); int numOfBins = 2 * track.x0Sigma() * INV_DISPLAY_RESOLUTION_FOR_HITS_MM; - for (int i = 0; i < numOfBins; ++i) { + for (int i = 0; i < numOfBins; ++i) trackHistoInTimeTmp->Fill(trackHistoInTimeTmp->GetBinCenter(startBin + i)); - } + } + if (plotOffline_) { + // potPlots_[detId_pot].trackTimeVsLS->Fill(event.luminosityBlock(),track.time()); + potPlots_[detId_pot].trackTimeVsBX->Fill(event.bunchCrossing(), track.time()); + //potPlots_[detId_pot].trackTimeVsXAngle->Fill(hLhcInfo->crossingAngle(), track.time()); } } } // Channel efficiency using CTPPSDiamondLocalTrack for (const auto& tracks : *diamondLocalTracks) { - CTPPSDiamondDetId detId_pot(tracks.detId()); - detId_pot.setPlane(0); - detId_pot.setChannel(0); + const CTPPSDiamondDetId detId(tracks.detId()), detId_pot(detId.rpId()); for (const auto& track : tracks) { // Find hits and planes in the track int numOfHits = 0; @@ -859,29 +999,24 @@ void CTPPSDiamondDQMSource::analyze(const edm::Event& event, const edm::EventSet } if (numOfHits > 0 && numOfHits <= 10 && planesInTrackSet.size() > 2) { - for (int plane = 0; plane < 4; ++plane) { - for (int channel = 0; channel < 12; ++channel) { - int map_index = plane * 100 + channel; - if (potPlots_[detId_pot].effDoublecountingChMap.find(map_index) == - potPlots_[detId_pot].effDoublecountingChMap.end()) { - potPlots_[detId_pot].effTriplecountingChMap[map_index] = 0; - potPlots_[detId_pot].effDoublecountingChMap[map_index] = 0; - } - CTPPSDiamondDetId detId(detId_pot.arm(), CTPPS_DIAMOND_STATION_ID, CTPPS_DIAMOND_RP_ID, plane, channel); - if (channelAlignedWithTrack(ctppsGeometry, detId, track, 0.2)) { - // Channel should fire - ++(potPlots_[detId_pot].effDoublecountingChMap[map_index]); - for (const auto& rechits : *diamondRecHits) { - CTPPSDiamondDetId detId_hit(rechits.detId()); - if (detId_hit == detId) { - for (const auto& rechit : rechits) { - if (track.containsHit(rechit, 1)) { - // Channel fired - ++(potPlots_[detId_pot].effTriplecountingChMap[map_index]); - } - } - } - } + for (const auto& plt_vs_ch : channelPlots_) { // loop over all channels registered in geometry + const CTPPSDiamondDetId detId(plt_vs_ch.first); + if (detId.rpId() != detId_pot) + continue; + const unsigned short map_index = detId.plane() * 100 + detId.channel(); + if (potPlots_[detId_pot].effDoublecountingChMap.count(map_index) == 0) { + potPlots_[detId_pot].effTriplecountingChMap[map_index] = 0; + potPlots_[detId_pot].effDoublecountingChMap[map_index] = 0; + } + if (channelAlignedWithTrack(ctppsGeometry, detId, track, 0.2)) { + // Channel should fire + ++potPlots_[detId_pot].effDoublecountingChMap[map_index]; + for (const auto& rechits : *diamondRecHits) { + const CTPPSDiamondDetId detId_hit(rechits.detId()); + if (detId_hit == detId) + for (const auto& rechit : rechits) + if (track.containsHit(rechit, 1)) // Channel fired + ++potPlots_[detId_pot].effTriplecountingChMap[map_index]; } } } @@ -891,10 +1026,8 @@ void CTPPSDiamondDQMSource::analyze(const edm::Event& event, const edm::EventSet // Tomography of diamonds using pixel for (const auto& rechits : *diamondRecHits) { - CTPPSDiamondDetId detId_pot(rechits.detId()); - detId_pot.setPlane(0); - detId_pot.setChannel(0); - const CTPPSDiamondDetId detId(rechits.detId()); + const CTPPSDiamondDetId detId(rechits.detId()), detId_pot(detId.rpId()); + const auto pix_shift = diamShifts_.at(detId_pot).withPixels; for (const auto& rechit : rechits) { if (excludeMultipleHits_ && rechit.multipleHits() > 0) continue; @@ -902,7 +1035,7 @@ void CTPPSDiamondDQMSource::analyze(const edm::Event& event, const edm::EventSet continue; if (!pixelTracks.isValid()) continue; - if (potPlots_.find(detId_pot) == potPlots_.end()) + if (potPlots_.count(detId_pot) == 0) continue; for (const auto& ds : *pixelTracks) { @@ -914,11 +1047,10 @@ void CTPPSDiamondDQMSource::analyze(const edm::Event& event, const edm::EventSet for (const auto& lt : ds) { if (lt.isValid() && pixId.arm() == detId_pot.arm()) { if (rechit.ootIndex() != CTPPSDiamondRecHit::TIMESLICE_WITHOUT_LEADING && rechit.ootIndex() >= 0 && - potPlots_[detId_pot].pixelTomographyAll.count(rechit.ootIndex()) > 0 && - lt.x0() - horizontalShiftBwDiamondPixels_ < 24) + potPlots_[detId_pot].pixelTomographyAll.count(rechit.ootIndex()) > 0 && lt.x0() - pix_shift < 24) potPlots_[detId_pot] .pixelTomographyAll.at(rechit.ootIndex()) - ->Fill(lt.x0() - horizontalShiftBwDiamondPixels_ + 25 * detId.plane(), lt.y0()); + ->Fill(lt.x0() - pix_shift + 25 * detId.plane(), lt.y0()); } } } @@ -930,11 +1062,8 @@ void CTPPSDiamondDQMSource::analyze(const edm::Event& event, const edm::EventSet //------------------------------ // Commented out to save space in the DQM files, but code should be kept // for ( const auto& digis : *diamondDigis ) { - // const CTPPSDiamondDetId detId( digis.detId() ); - // CTPPSDiamondDetId detId_pot( digis.detId() ); + // const CTPPSDiamondDetId detId(digis.detId()), detId_pot(detId.rpId()); // if ( detId.channel() == CHANNEL_OF_VFAT_CLOCK ) { - // detId_pot.setPlane( 0 ); - // detId_pot.setChannel( 0 ); // for ( const auto& digi : digis ) { // if ( digi.leadingEdge() != 0 ) { // if ( detId.plane() == 1 ) { @@ -956,47 +1085,41 @@ void CTPPSDiamondDQMSource::analyze(const edm::Event& event, const edm::EventSet // Using CTPPSDiamondDigi std::unordered_map channelsPerPlane; - for (const auto& digis : *diamondDigis) { - const CTPPSDiamondDetId detId(digis.detId()); - CTPPSDiamondDetId detId_plane(digis.detId()); - for (const auto& digi : digis) { - detId_plane.setChannel(0); - if (detId.channel() == CHANNEL_OF_VFAT_CLOCK) - continue; - if (planePlots_.find(detId_plane) == planePlots_.end()) - continue; + if (extract_digi_info_) { + for (const auto& digis : *diamondDigis) { + const CTPPSDiamondDetId detId(digis.detId()), detId_plane(detId.planeId()); + for (const auto& digi : digis) { + if (detId.channel() == CHANNEL_OF_VFAT_CLOCK) + continue; + if (planePlots_.count(detId_plane) == 0) + continue; - if (digi.leadingEdge() != 0) { - planePlots_[detId_plane].digiProfileCumulativePerPlane->Fill(detId.channel()); - if (channelsPerPlane.find(detId_plane) != channelsPerPlane.end()) + if (digi.leadingEdge() != 0) { + planePlots_[detId_plane].digiProfileCumulativePerPlane->Fill(detId.channel()); channelsPerPlane[detId_plane]++; - else - channelsPerPlane[detId_plane] = 0; + } } } } - for (const auto& plt : channelsPerPlane) { + for (const auto& plt : channelsPerPlane) planePlots_[plt.first].hit_multiplicity->Fill(plt.second); - } // Using CTPPSDiamondRecHit for (const auto& rechits : *diamondRecHits) { - CTPPSDiamondDetId detId_plane(rechits.detId()); - detId_plane.setChannel(0); + const CTPPSDiamondDetId detId(rechits.detId()), detId_plane(detId.planeId()), detId_pot(detId.rpId()); for (const auto& rechit : rechits) { if (excludeMultipleHits_ && rechit.multipleHits() > 0) continue; if (rechit.toT() == 0) continue; - if (planePlots_.find(detId_plane) != planePlots_.end()) { + if (planePlots_.count(detId_plane) != 0) { if (centralOOT_ != -999 && rechit.ootIndex() == centralOOT_) { TH1F* hitHistoTmp = planePlots_[detId_plane].hitProfile->getTH1F(); - int startBin = hitHistoTmp->FindBin(rechit.x() - horizontalShiftOfDiamond_ - 0.5 * rechit.xWidth()); + int startBin = hitHistoTmp->FindBin(rechit.x() - diamShifts_.at(detId_pot).global - 0.5 * rechit.xWidth()); int numOfBins = rechit.xWidth() * INV_DISPLAY_RESOLUTION_FOR_HITS_MM; - for (int i = 0; i < numOfBins; ++i) { + for (int i = 0; i < numOfBins; ++i) hitHistoTmp->Fill(hitHistoTmp->GetBinCenter(startBin + i)); - } } } } @@ -1011,24 +1134,27 @@ void CTPPSDiamondDQMSource::analyze(const edm::Event& event, const edm::EventSet continue; for (const auto& lt : ds) { if (lt.isValid()) { - // For efficieny - CTPPSDiamondDetId detId_pot(pixId.arm(), CTPPS_DIAMOND_STATION_ID, CTPPS_DIAMOND_RP_ID); - potPlots_[detId_pot].pixelTracksMap.Fill(lt.x0() - horizontalShiftBwDiamondPixels_, lt.y0()); + for (const auto& sh_vs_id : diamShifts_) { + const CTPPSDiamondDetId& detId_pot = sh_vs_id.first; + const auto& shift = sh_vs_id.second; + if (detId_pot.arm() == pixId.arm()) + // For efficieny + potPlots_[detId_pot].pixelTracksMap.Fill(lt.x0() - shift.withPixels, lt.y0()); + } std::set planesWitHits_set; for (const auto& rechits : *diamondRecHits) { - CTPPSDiamondDetId detId_plane(rechits.detId()); - detId_plane.setChannel(0); + const CTPPSDiamondDetId detId(rechits.detId()), detId_plane(detId.planeId()), detId_pot(detId.rpId()); + const auto pix_shift = diamShifts_.at(detId_pot).withPixels; for (const auto& rechit : rechits) { if (excludeMultipleHits_ && rechit.multipleHits() > 0) continue; if (rechit.ootIndex() == CTPPSDiamondRecHit::TIMESLICE_WITHOUT_LEADING || rechit.toT() == 0) continue; - if (planePlots_.find(detId_plane) == planePlots_.end()) + if (planePlots_.count(detId_plane) == 0) continue; - if (pixId.arm() == detId_plane.arm() && lt.x0() - horizontalShiftBwDiamondPixels_ < 24) { - planePlots_[detId_plane].pixelTomography_far->Fill( - lt.x0() - horizontalShiftBwDiamondPixels_ + 25 * rechit.ootIndex(), lt.y0()); + if (pixId.arm() == detId_plane.arm() && lt.x0() - pix_shift < 24) { + planePlots_[detId_plane].pixelTomography_far->Fill(lt.x0() - pix_shift + 25 * rechit.ootIndex(), lt.y0()); if (centralOOT_ != -999 && rechit.ootIndex() == centralOOT_) planesWitHits_set.insert(detId_plane); } @@ -1036,7 +1162,8 @@ void CTPPSDiamondDQMSource::analyze(const edm::Event& event, const edm::EventSet } for (auto& planeId : planesWitHits_set) - planePlots_[planeId].pixelTracksMapWithDiamonds.Fill(lt.x0() - horizontalShiftBwDiamondPixels_, lt.y0()); + planePlots_[planeId].pixelTracksMapWithDiamonds.Fill(lt.x0() - diamShifts_.at(planeId.rpId()).withPixels, + lt.y0()); } } } @@ -1046,35 +1173,35 @@ void CTPPSDiamondDQMSource::analyze(const edm::Event& event, const edm::EventSet //------------------------------ // digi profile cumulative - for (const auto& digis : *diamondDigis) { - const CTPPSDiamondDetId detId(digis.detId()); - for (const auto& digi : digis) { - if (detId.channel() == CHANNEL_OF_VFAT_CLOCK) - continue; - if (channelPlots_.find(detId) != channelPlots_.end()) { - // HPTDC Errors - const HPTDCErrorFlags hptdcErrors = digi.hptdcErrorFlags(); - for (unsigned short hptdcErrorIndex = 1; hptdcErrorIndex < 16; ++hptdcErrorIndex) - if (hptdcErrors.errorId(hptdcErrorIndex - 1)) - channelPlots_[detId].HPTDCErrorFlags->Fill(hptdcErrorIndex); - if (digi.multipleHit()) - ++(channelPlots_[detId].MHCounter); - - // Check dropped trailing edges - if (digi.leadingEdge() != 0 || digi.trailingEdge() != 0) { - ++(channelPlots_[detId].HitCounter); - if (digi.leadingEdge() != 0 && digi.trailingEdge() == 0) { - ++(channelPlots_[detId].LeadingOnlyCounter); - channelPlots_[detId].leadingEdgeCumulative_le->Fill(HPTDC_BIN_WIDTH_NS * digi.leadingEdge()); - } - if (digi.leadingEdge() == 0 && digi.trailingEdge() != 0) { - ++(channelPlots_[detId].TrailingOnlyCounter); - channelPlots_[detId].trailingEdgeCumulative_te->Fill(HPTDC_BIN_WIDTH_NS * digi.trailingEdge()); - } - if (digi.leadingEdge() != 0 && digi.trailingEdge() != 0) { - ++(channelPlots_[detId].CompleteCounter); - channelPlots_[detId].LeadingTrailingCorrelationPerChannel->Fill(HPTDC_BIN_WIDTH_NS * digi.leadingEdge(), - HPTDC_BIN_WIDTH_NS * digi.trailingEdge()); + if (extract_digi_info_) { + for (const auto& digis : *diamondDigis) { + const CTPPSDiamondDetId detId(digis.detId()); + for (const auto& digi : digis) { + if (detId.channel() == CHANNEL_OF_VFAT_CLOCK) + continue; + if (channelPlots_.count(detId) != 0) { + // HPTDC Errors + const HPTDCErrorFlags hptdcErrors = digi.hptdcErrorFlags(); + for (unsigned short hptdcErrorIndex = 1; hptdcErrorIndex < 16; ++hptdcErrorIndex) + if (hptdcErrors.errorId(hptdcErrorIndex - 1)) + channelPlots_[detId].HPTDCErrorFlags->Fill(hptdcErrorIndex); + if (digi.multipleHit()) + ++channelPlots_[detId].MHCounter; + + // Check dropped trailing edges + if (digi.leadingEdge() != 0 || digi.trailingEdge() != 0) { + ++channelPlots_[detId].HitCounter; + if (digi.trailingEdge() == 0) { + ++channelPlots_[detId].LeadingOnlyCounter; + channelPlots_[detId].leadingEdgeCumulative_le->Fill(HPTDC_BIN_WIDTH_NS * digi.leadingEdge()); + } else if (digi.leadingEdge() == 0) { + ++channelPlots_[detId].TrailingOnlyCounter; + channelPlots_[detId].trailingEdgeCumulative_te->Fill(HPTDC_BIN_WIDTH_NS * digi.trailingEdge()); + } else { + ++channelPlots_[detId].CompleteCounter; + // channelPlots_[detId].LeadingTrailingCorrelationPerChannel->Fill(HPTDC_BIN_WIDTH_NS * digi.leadingEdge(), + // HPTDC_BIN_WIDTH_NS * digi.trailingEdge()); + } } } } @@ -1088,23 +1215,25 @@ void CTPPSDiamondDQMSource::analyze(const edm::Event& event, const edm::EventSet for (const auto& rechit : rechits) { if (excludeMultipleHits_ && rechit.multipleHits() > 0) continue; - if (channelPlots_.find(detId) != channelPlots_.end()) { + if (channelPlots_.count(detId) != 0) { + channelPlots_[detId].recHitTime->Fill(rechit.time()); if (rechit.ootIndex() != CTPPSDiamondRecHit::TIMESLICE_WITHOUT_LEADING && rechit.toT() != 0) { channelPlots_[detId].leadingEdgeCumulative_both->Fill(rechit.time() + 25 * rechit.ootIndex()); channelPlots_[detId].TimeOverThresholdCumulativePerChannel->Fill(rechit.toT()); } - ++(lumiCache->hitsCounterMap[detId]); - } + ++lumiCache->hitsCounterMap[detId]; - if (rechit.ootIndex() != CTPPSDiamondRecHit::TIMESLICE_WITHOUT_LEADING && - channelPlots_[detId].activity_per_bx.count(rechit.ootIndex()) > 0) - channelPlots_[detId].activity_per_bx.at(rechit.ootIndex())->Fill(event.bunchCrossing()); + if (rechit.ootIndex() != CTPPSDiamondRecHit::TIMESLICE_WITHOUT_LEADING && + channelPlots_[detId].activity_per_bx.count(rechit.ootIndex()) > 0) + channelPlots_[detId].activity_per_bx.at(rechit.ootIndex())->Fill(event.bunchCrossing()); + } } } // Tomography of diamonds using pixel for (const auto& rechits : *diamondRecHits) { - const CTPPSDiamondDetId detId(rechits.detId()); + const CTPPSDiamondDetId detId(rechits.detId()), detId_pot(detId.rpId()); + const auto shift_pix = diamShifts_.at(detId_pot).withPixels; for (const auto& rechit : rechits) { if (excludeMultipleHits_ && rechit.multipleHits() > 0) continue; @@ -1112,7 +1241,7 @@ void CTPPSDiamondDQMSource::analyze(const edm::Event& event, const edm::EventSet continue; if (!pixelTracks.isValid()) continue; - if (channelPlots_.find(detId) == channelPlots_.end()) + if (channelPlots_.count(detId) == 0) continue; for (const auto& ds : *pixelTracks) { @@ -1122,9 +1251,8 @@ void CTPPSDiamondDQMSource::analyze(const edm::Event& event, const edm::EventSet if (ds.size() > 1) continue; for (const auto& lt : ds) { - if (lt.isValid() && pixId.arm() == detId.arm() && lt.x0() - horizontalShiftBwDiamondPixels_ < 24) - channelPlots_[detId].pixelTomography_far->Fill( - lt.x0() - horizontalShiftBwDiamondPixels_ + 25 * rechit.ootIndex(), lt.y0()); + if (lt.isValid() && pixId.arm() == detId.arm() && lt.x0() - shift_pix < 24) + channelPlots_[detId].pixelTomography_far->Fill(lt.x0() - shift_pix + 25 * rechit.ootIndex(), lt.y0()); } } } @@ -1136,9 +1264,10 @@ void CTPPSDiamondDQMSource::analyze(const edm::Event& event, const edm::EventSet void CTPPSDiamondDQMSource::globalEndLuminosityBlock(const edm::LuminosityBlock& iLumi, const edm::EventSetup&) { auto lumiCache = luminosityBlockCache(iLumi.index()); if (!perLSsaving_) { - for (auto& plot : potPlots_) { - *(plot.second.hitDistribution2d_lumisection->getTH2F()) = *(lumiCache->hitDistribution2dMap[plot.first]); - } + if (plotOnline_) + for (auto& plot : potPlots_) { + *(plot.second.hitDistribution2d_lumisection->getTH2F()) = *(lumiCache->hitDistribution2dMap[plot.first]); + } for (auto& plot : channelPlots_) { auto hitsCounterPerLumisection = lumiCache->hitsCounterMap[plot.first]; @@ -1167,9 +1296,9 @@ void CTPPSDiamondDQMSource::globalEndLuminosityBlock(const edm::LuminosityBlock& 3, HundredOverHitCounterPot * plot.second.CompleteCounter); plot.second.MHComprensive->Reset(); - CTPPSDiamondDetId rpId(plot.first); + const CTPPSDiamondDetId rpId(plot.first); for (auto& chPlot : channelPlots_) { - CTPPSDiamondDetId chId(chPlot.first); + const CTPPSDiamondDetId chId(chPlot.first); if (chId.arm() == rpId.arm() && chId.rp() == rpId.rp()) { plot.second.MHComprensive->Fill( chId.plane(), chId.channel(), chPlot.second.HPTDCErrorFlags->getBinContent(16)); @@ -1177,29 +1306,28 @@ void CTPPSDiamondDQMSource::globalEndLuminosityBlock(const edm::LuminosityBlock& } } // Efficiencies of single channels - for (auto& plot : potPlots_) { - plot.second.EfficiencyOfChannelsInPot->Reset(); - for (auto& element : plot.second.effTriplecountingChMap) { - if (plot.second.effDoublecountingChMap[element.first] > 0) { - int plane = element.first / 100; - int channel = element.first % 100; - double counted = element.second; - double total = plot.second.effDoublecountingChMap[element.first]; - double efficiency = counted / total; - // double error = std::sqrt( efficiency * ( 1 - efficiency ) / total ); - - plot.second.EfficiencyOfChannelsInPot->Fill(plane, channel, 100 * efficiency); + if (plotOnline_) + for (auto& plot : potPlots_) { + plot.second.EfficiencyOfChannelsInPot->Reset(); + for (auto& element : plot.second.effTriplecountingChMap) { + if (plot.second.effDoublecountingChMap[element.first] > 0) { + int plane = element.first / 100; + int channel = element.first % 100; + double counted = element.second; + double total = plot.second.effDoublecountingChMap[element.first]; + double efficiency = counted / total; + // double error = std::sqrt( efficiency * ( 1 - efficiency ) / total ); + + plot.second.EfficiencyOfChannelsInPot->Fill(plane, channel, 100 * efficiency); + } } } - } // Efficeincy wrt pixels //TODO for (auto& plot : planePlots_) { TH2F* hitHistoTmp = plot.second.EfficiencyWRTPixelsInPlane->getTH2F(); - CTPPSDiamondDetId detId_pot(plot.first); - detId_pot.setPlane(0); - + const CTPPSDiamondDetId detId(plot.first), detId_pot(detId.rpId()); hitHistoTmp->Divide(&(plot.second.pixelTracksMapWithDiamonds), &(potPlots_[detId_pot].pixelTracksMap)); } } //perLSsaving @@ -1207,4 +1335,40 @@ void CTPPSDiamondDQMSource::globalEndLuminosityBlock(const edm::LuminosityBlock& //---------------------------------------------------------------------------------------------------- +void CTPPSDiamondDQMSource::checkEventNumber(const CTPPSDiamondDetId& detId, + const TotemFEDInfo& optorx, + const TotemVFATStatus& status, + CTPPSDiamondDQMSource::PotPlots& plots, + int& EC_difference) const { + const CTPPSDiamondDetId detId_pot(detId.rpId()); + if (plotOnline_) + plots.ECCheck->Fill((int)((optorx.lv1() & 0xFF) - ((unsigned int)status.ec() & 0xFF)) & 0xFF); + if ((static_cast((optorx.lv1() & 0xFF) - status.ec()) != EC_difference) && + (static_cast((optorx.lv1() & 0xFF) - status.ec()) < 128)) + EC_difference = static_cast(optorx.lv1() & 0xFF) - (static_cast(status.ec()) & 0xFF); + if (EC_difference != 1 && EC_difference != -500 && std::abs(EC_difference) < 127) { + if (detId.channel() == HPTDC_0_CHANNEL || detId.channel() == HPTDC_1_CHANNEL) + plots.HPTDCErrorFlags_2D->Fill(16, 2 * detId.plane() + (detId.channel() - HPTDC_0_CHANNEL)); + if (verbosity_) + edm::LogProblem("CTPPSDiamondDQMSource") + << "FED " << optorx.fedId() << ": ECError at EV: 0x" << std::hex << optorx.lv1() << "\t\tVFAT EC: 0x" + << static_cast(status.ec()) << "\twith ID: " << std::dec << detId + << "\tdiff: " << EC_difference; + } +} + +//---------------------------------------------------------------------------------------------------- + +void CTPPSDiamondDQMSource::dqmEndRun(edm::Run const&, edm::EventSetup const&) { + if (plotOffline_) + for (const auto& rpPlots : potPlots_) { + auto plots = rpPlots.second; + // *(plots.TOTVsLSProfile->getTProfile())=*plots.TOTVsLS->getTH2F()->ProfileX(); + // *(plots.trackTimeVsLSProfile->getTProfile())=*plots.trackTimeVsLS->getTH2F()->ProfileX(); + *(plots.trackTimeVsBXProfile->getTProfile()) = *plots.trackTimeVsBX->getTH2F()->ProfileX(); + // *(plots.trackTimeVsXAngleProfile->getTProfile()) = *plots.trackTimeVsXAngle->getTH2F()->ProfileX(); + } +} + +//---------------------------------------------------------------------------------------------------- DEFINE_FWK_MODULE(CTPPSDiamondDQMSource); diff --git a/DQM/CTPPS/plugins/DiamondSampicDQMSource.cc b/DQM/CTPPS/plugins/DiamondSampicDQMSource.cc index 0b4e5198029b2..68f72805e4420 100644 --- a/DQM/CTPPS/plugins/DiamondSampicDQMSource.cc +++ b/DQM/CTPPS/plugins/DiamondSampicDQMSource.cc @@ -8,7 +8,6 @@ * ****************************************************************************/ -#include "FWCore/Framework/interface/ESHandle.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/EventSetup.h" #include "FWCore/Framework/interface/MakerMacros.h" @@ -590,7 +589,7 @@ void DiamondSampicDQMSource::analyze(const edm::Event &event, const edm::EventSe TAxis *hitHistoTmpYAxis = hitHistoTmp->GetYaxis(); int startBin = hitHistoTmpYAxis->FindBin(rechit.x() - horizontalShiftOfDiamond_[detId_pot] - 0.5 * rechit.xWidth()); - int numOfBins = rechit.xWidth() * INV_DISPLAY_RESOLUTION_FOR_HITS_MM; + const int numOfBins = rechit.xWidth() * INV_DISPLAY_RESOLUTION_FOR_HITS_MM; for (int i = 0; i < numOfBins; ++i) { potPlots_[detId_pot].hitDistribution2d->Fill(detId.plane() + UFSDShift, hitHistoTmpYAxis->GetBinCenter(startBin + i)); @@ -613,10 +612,8 @@ void DiamondSampicDQMSource::analyze(const edm::Event &event, const edm::EventSe // Plane Plots if (planePlots_.find(detId_plane) != planePlots_.end()) { TH1F *hitProfileHistoTmp = planePlots_[detId_plane].hitProfile->getTH1F(); - int numOfBins = rechit.yWidth() * INV_DISPLAY_RESOLUTION_FOR_HITS_MM; - int startBin = hitProfileHistoTmp->FindBin(rechit.x() - horizontalShiftOfDiamond_[detId_pot] - - 0.5 * rechit.xWidth()); - numOfBins = rechit.xWidth() * INV_DISPLAY_RESOLUTION_FOR_HITS_MM; + const int startBin = hitProfileHistoTmp->FindBin(rechit.x() - horizontalShiftOfDiamond_[detId_pot] - + 0.5 * rechit.xWidth()); for (int i = 0; i < numOfBins; ++i) hitProfileHistoTmp->Fill(hitProfileHistoTmp->GetBinCenter(startBin + i)); @@ -653,8 +650,9 @@ void DiamondSampicDQMSource::analyze(const edm::Event &event, const edm::EventSe continue; TH1F *trackHistoInTimeTmp = potPlots_[detId_pot].trackDistribution->getTH1F(); - int startBin = trackHistoInTimeTmp->FindBin(track.x0() - horizontalShiftOfDiamond_[detId_pot] - track.x0Sigma()); - int numOfBins = 2 * track.x0Sigma() * INV_DISPLAY_RESOLUTION_FOR_HITS_MM; + const int startBin = + trackHistoInTimeTmp->FindBin(track.x0() - horizontalShiftOfDiamond_[detId_pot] - track.x0Sigma()); + const int numOfBins = 2 * track.x0Sigma() * INV_DISPLAY_RESOLUTION_FOR_HITS_MM; for (int i = 0; i < numOfBins; ++i) { trackHistoInTimeTmp->Fill(trackHistoInTimeTmp->GetBinCenter(startBin + i)); } @@ -674,9 +672,9 @@ void DiamondSampicDQMSource::analyze(const edm::Event &event, const edm::EventSe TH2F *trackHistoTmp = sectorPlots_[detId_far.armId()].trackCorrelation->getTH2F(); TAxis *trackHistoTmpXAxis = trackHistoTmp->GetXaxis(); TAxis *trackHistoTmpYAxis = trackHistoTmp->GetYaxis(); - int startBin_far = + const int startBin_far = trackHistoTmpYAxis->FindBin(track_far.x0() - horizontalShiftOfDiamond_[detId_far] - track_far.x0Sigma()); - int numOfBins_far = 2 * track_far.x0Sigma() * INV_DISPLAY_RESOLUTION_FOR_HITS_MM; + const int numOfBins_far = 2 * track_far.x0Sigma() * INV_DISPLAY_RESOLUTION_FOR_HITS_MM; for (int i = 0; i < numOfBins; ++i) { for (int y = 0; y < numOfBins_far; ++y) { trackHistoTmp->Fill(trackHistoTmpXAxis->GetBinCenter(startBin + i), diff --git a/DQM/CTPPS/python/ctppsDQM_cff.py b/DQM/CTPPS/python/ctppsDQM_cff.py index ba65ef53dca15..f8e1a0980914c 100644 --- a/DQM/CTPPS/python/ctppsDQM_cff.py +++ b/DQM/CTPPS/python/ctppsDQM_cff.py @@ -59,7 +59,7 @@ _ctppsDQMOfflineSource = cms.Sequence( ctppsPixelDQMOfflineSource - + ctppsDiamondDQMSource + + ctppsDiamondDQMOfflineSource + diamondSampicDQMSourceOffline + ctppsCommonDQMSourceOffline ) @@ -72,7 +72,7 @@ _ctppsDQMOfflineSource, cms.Sequence( ctppsPixelDQMOfflineSource - + ctppsDiamondDQMSource + + ctppsDiamondDQMOfflineSource + totemTimingDQMSource + ctppsCommonDQMSourceOffline ) diff --git a/DQM/CTPPS/python/ctppsDiamondDQMSource_cfi.py b/DQM/CTPPS/python/ctppsDiamondDQMSource_cfi.py index 7611902ba1a6c..905c436dfcebf 100644 --- a/DQM/CTPPS/python/ctppsDiamondDQMSource_cfi.py +++ b/DQM/CTPPS/python/ctppsDiamondDQMSource_cfi.py @@ -8,9 +8,56 @@ tagDiamondRecHits = cms.InputTag("ctppsDiamondRecHits"), tagDiamondLocalTracks = cms.InputTag("ctppsDiamondLocalTracks"), tagPixelLocalTracks = cms.InputTag("ctppsPixelLocalTracks"), + + excludeMultipleHits = cms.bool(True), + extractDigiInfo = cms.bool(True), + + plotOnline = cms.untracked.bool(True), + plotOffline= cms.untracked.bool(False), + + offsetsOOT = cms.VPSet( # cut on the OOT bin for physics hits + # 2016, after TS2 + cms.PSet( + validityRange = cms.EventRange("1:min - 292520:max"), + centralOOT = cms.int32(1), + ), + # 2017 + cms.PSet( + validityRange = cms.EventRange("292521:min - 301417:max"), + centralOOT = cms.int32(3), + ), + # 2017, after channel delays corrections + cms.PSet( + validityRange = cms.EventRange("301418:min - 301517:max"), + centralOOT = cms.int32(1), + ), + # 2017, after channel delays corrections + cms.PSet( + validityRange = cms.EventRange("301518:min - 9999999:max"), + centralOOT = cms.int32(0), + ), + ), + + perLSsaving = cms.untracked.bool(False), #driven by DQMServices/Core/python/DQMStore_cfi.py + + verbosity = cms.untracked.uint32(10), +) + +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"), + excludeMultipleHits = cms.bool(True), + extractDigiInfo = cms.bool(True), + plotOnline = cms.untracked.bool(False), + plotOffline= cms.untracked.bool(True), + offsetsOOT = cms.VPSet( # cut on the OOT bin for physics hits # 2016, after TS2 cms.PSet( @@ -35,6 +82,6 @@ ), perLSsaving = cms.untracked.bool(False), #driven by DQMServices/Core/python/DQMStore_cfi.py - + verbosity = cms.untracked.uint32(10), ) diff --git a/DQM/CTPPS/test/diamond_dqm_test_cfg.py b/DQM/CTPPS/test/diamond_dqm_test_cfg.py index 78eeebdfa86c8..b3aa3a277c22c 100644 --- a/DQM/CTPPS/test/diamond_dqm_test_cfg.py +++ b/DQM/CTPPS/test/diamond_dqm_test_cfg.py @@ -1,21 +1,19 @@ import FWCore.ParameterSet.Config as cms -import string +from Configuration.Eras.Era_Run2_2018_cff import Run2_2018 -process = cms.Process('RECODQM') +process = cms.Process('RECODQM', Run2_2018) process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) ) process.verbosity = cms.untracked.PSet( input = cms.untracked.int32(-1) ) # minimum of logs process.MessageLogger = cms.Service("MessageLogger", - statistics = cms.untracked.vstring(), - destinations = cms.untracked.vstring('cerr'), cerr = cms.untracked.PSet( threshold = cms.untracked.string('WARNING') ) ) - - # import of standard configurations + +# import of standard configurations process.load('Configuration.StandardSequences.Services_cff') process.load('FWCore.MessageService.MessageLogger_cfi') process.load('Configuration.EventContent.EventContent_cff') @@ -30,47 +28,31 @@ # raw data source process.source = cms.Source("PoolSource", - # replace '*.root',',' with the source file you want to use fileNames = cms.untracked.vstring( - *( -'/store/data/Run2017C/ZeroBias/AOD/PromptReco-v2/000/300/088/00000/469D8C89-1477-E711-A6A4-02163E01190C.root', - ) +'/store/data/Run2018D/ZeroBias/AOD/12Nov2019_UL2018_rsb-v1/280000/FE61A0D8-CEDC-2142-81AA-06301F452792.root', ), ) - from Configuration.AlCa.GlobalTag import GlobalTag -process.GlobalTag = GlobalTag(process.GlobalTag, 'auto:run2_hlt_relval', '') +#process.GlobalTag = GlobalTag(process.GlobalTag, 'auto:run2_hlt_relval', '') +process.GlobalTag = GlobalTag(process.GlobalTag, '120X_dataRun2_v2', '') # raw-to-digi conversion process.load("EventFilter.CTPPSRawToDigi.ctppsRawToDigi_cff") # local RP reconstruction chain with standard settings process.load("RecoPPS.Configuration.recoCTPPS_cff") - -# rechits production -process.load('RecoPPS.Local.ctppsDiamondRecHits_cfi') - -# local tracks fitter -process.load('RecoPPS.Local.ctppsDiamondLocalTracks_cfi') - -# pixel -process.load('RecoPPS.Local.ctppsPixelLocalTracks_cfi') - +process.load('Geometry.VeryForwardGeometry.geometryRPFromDD_2021_cfi') # CTPPS DQM modules process.load("DQM.CTPPS.ctppsDQM_cff") -process.ctppsDiamondDQMSource.excludeMultipleHits = cms.bool(True); - +process.ctppsDiamondDQMSource.excludeMultipleHits = cms.bool(True) +process.ctppsDiamondDQMSource.plotOnline = cms.untracked.bool(True) +process.ctppsDiamondDQMSource.plotOffline = cms.untracked.bool(False) process.path = cms.Path( - #process.ctppsRawToDigi * - process.recoCTPPS * - #process.ctppsDiamondRawToDigi * - process.ctppsDiamondRecHits * - process.ctppsDiamondLocalTracks * - process.ctppsPixelLocalTracks * - process.ctppsDQM - ) - + process.recoCTPPS* + process.ctppsDQMOnlineSource* + process.ctppsDQMOnlineHarvest +) process.end_path = cms.EndPath( process.dqmEnv + diff --git a/DQM/DTMonitorClient/src/DTChamberEfficiencyTest.cc b/DQM/DTMonitorClient/src/DTChamberEfficiencyTest.cc index 5b0d6fb3dde56..251ded98820c6 100644 --- a/DQM/DTMonitorClient/src/DTChamberEfficiencyTest.cc +++ b/DQM/DTMonitorClient/src/DTChamberEfficiencyTest.cc @@ -25,7 +25,8 @@ using namespace edm; using namespace std; -DTChamberEfficiencyTest::DTChamberEfficiencyTest(const edm::ParameterSet& ps) : muonGeomToken_(esConsumes()) { +DTChamberEfficiencyTest::DTChamberEfficiencyTest(const edm::ParameterSet& ps) + : muonGeomToken_(esConsumes()) { edm::LogVerbatim("DTDQM|DTMonitorClient|DTChamberEfficiencyTest") << "[DTChamberEfficiencyTest]: Constructor"; parameters = ps; diff --git a/DQM/EcalMonitorTasks/interface/TimingTask.h b/DQM/EcalMonitorTasks/interface/TimingTask.h index e0fa74d96034c..a4f289593199c 100644 --- a/DQM/EcalMonitorTasks/interface/TimingTask.h +++ b/DQM/EcalMonitorTasks/interface/TimingTask.h @@ -33,6 +33,7 @@ namespace ecaldqm { float energyThresholdEEFwd_; float timingVsBXThreshold_; float timeErrorThreshold_; + bool splashSwitch_; MESet* meTimeMapByLS; }; diff --git a/DQM/EcalMonitorTasks/python/TimingTask_cfi.py b/DQM/EcalMonitorTasks/python/TimingTask_cfi.py index 4815849b5c0e7..07fb36bf3c791 100644 --- a/DQM/EcalMonitorTasks/python/TimingTask_cfi.py +++ b/DQM/EcalMonitorTasks/python/TimingTask_cfi.py @@ -46,7 +46,8 @@ energyThresholdEEFwd = cms.untracked.double(energyThresholdEEFwd), energyThresholdEB = cms.untracked.double(energyThresholdEB), timingVsBXThreshold = cms.untracked.double(timingVsBXThreshold), - timeErrorThreshold = cms.untracked.double(timeErrorThreshold) + timeErrorThreshold = cms.untracked.double(timeErrorThreshold), + splashSwitch = cms.untracked.bool(False) ), MEs = cms.untracked.PSet( TimeMap = cms.untracked.PSet( diff --git a/DQM/EcalMonitorTasks/src/RawDataTask.cc b/DQM/EcalMonitorTasks/src/RawDataTask.cc index e15adf4b56d69..859e9f72233c6 100644 --- a/DQM/EcalMonitorTasks/src/RawDataTask.cc +++ b/DQM/EcalMonitorTasks/src/RawDataTask.cc @@ -8,6 +8,7 @@ #include "DQM/EcalCommon/interface/FEFlags.h" #include "DataFormats/EcalDetId/interface/EcalElectronicsId.h" +#include "DataFormats/Luminosity/interface/LumiConstants.h" namespace ecaldqm { @@ -22,7 +23,15 @@ namespace ecaldqm { void RawDataTask::beginEvent(edm::Event const& _evt, edm::EventSetup const&, bool const& ByLumiResetSwitch, bool&) { orbit_ = _evt.orbitNumber() & 0xffffffff; + bx_ = _evt.bunchCrossing() & 0xfff; + // There's no agreement in CMS on how to label the last/first BX + // TCDS calls it always 3564, but some subsystems call it 0. + // From testing: bx_ is labeled 0, dccBX and FEBxs[iFE] labeled 3564 + // Setting bx_ to 0 to match the other two + if (bx_ == LumiConstants::numBX) // 3564 + bx_ = 0; + triggerType_ = _evt.experimentType() & 0xf; l1A_ = 0; feL1Offset_ = _evt.isRealData() ? 1 : 0; diff --git a/DQM/EcalMonitorTasks/src/TimingTask.cc b/DQM/EcalMonitorTasks/src/TimingTask.cc index 1287b2e5d26e7..bb00f7d266dae 100644 --- a/DQM/EcalMonitorTasks/src/TimingTask.cc +++ b/DQM/EcalMonitorTasks/src/TimingTask.cc @@ -33,6 +33,7 @@ namespace ecaldqm { energyThresholdEEFwd_ = _params.getUntrackedParameter("energyThresholdEEFwd"); timingVsBXThreshold_ = _params.getUntrackedParameter("timingVsBXThreshold"); timeErrorThreshold_ = _params.getUntrackedParameter("timeErrorThreshold"); + splashSwitch_ = _params.getUntrackedParameter("splashSwitch", false); } bool TimingTask::filterRunType(short const* _runType) { @@ -80,18 +81,12 @@ namespace ecaldqm { float time(hit.time()); float energy(hit.energy()); - float chi2Threshold, energyThreshold; + float energyThreshold; if (id.subdetId() == EcalBarrel) { - chi2Threshold = chi2ThresholdEB_; energyThreshold = energyThresholdEB_; + signedSubdet = EcalBarrel; } else { - chi2Threshold = chi2ThresholdEE_; energyThreshold = (isForward(id)) ? energyThresholdEEFwd_ : energyThresholdEE_; - } - - if (id.subdetId() == EcalBarrel) - signedSubdet = EcalBarrel; - else { EEDetId eeId(hit.id()); if (eeId.zside() < 0) signedSubdet = -EcalEndcap; @@ -102,10 +97,17 @@ namespace ecaldqm { if (energy > energyThreshold) meChi2.fill(getEcalDQMSetupObjects(), signedSubdet, hit.chi2()); - // Apply cut on chi2 of pulse shape fit - if (hit.chi2() > chi2Threshold) - return; + if (!splashSwitch_) { //Not applied for splash events + float chi2Threshold; + if (id.subdetId() == EcalBarrel) + chi2Threshold = chi2ThresholdEB_; + else + chi2Threshold = chi2ThresholdEE_; + //Apply cut on chi2 of pulse shape fit + if (hit.chi2() > chi2Threshold) + return; + } // Apply cut based on timing error of rechit if (hit.timeError() > timeErrorThreshold_) return; diff --git a/DQM/GEM/interface/GEMDAQStatusSource.h b/DQM/GEM/interface/GEMDAQStatusSource.h index ae01da86d0660..2b448ba1acd20 100644 --- a/DQM/GEM/interface/GEMDAQStatusSource.h +++ b/DQM/GEM/interface/GEMDAQStatusSource.h @@ -69,6 +69,7 @@ class GEMDAQStatusSource : public GEMDQMBase { MEMap3Inf mapStatusErrVFATPerLayer_; MEMap4Inf mapStatusVFATPerCh_; + MonitorElement *h2SummaryStatusAll; MonitorElement *h2SummaryStatusWarning; MonitorElement *h2SummaryStatusError; diff --git a/DQM/GEM/plugins/GEMDAQStatusSource.cc b/DQM/GEM/plugins/GEMDAQStatusSource.cc index 0cf50109c125c..e20cf95c57bc0 100644 --- a/DQM/GEM/plugins/GEMDAQStatusSource.cc +++ b/DQM/GEM/plugins/GEMDAQStatusSource.cc @@ -38,7 +38,7 @@ void GEMDAQStatusSource::SetLabelAMC13Status(MonitorElement *h2Status) { h2Status->setBinLabel(unBinPos++, "S-link error", 2); h2Status->setBinLabel(unBinPos++, "Wrong FED ID", 2); - h2Status->setBinLabel(1, "GE11-N", 1); + h2Status->setBinLabel(1, "GE11-M", 1); h2Status->setBinLabel(2, "GE11-P", 1); } @@ -107,8 +107,8 @@ void GEMDAQStatusSource::bookHistograms(DQMStore::IBooker &ibooker, edm::Run con h2AMC13Status_ = ibooker.book2D("amc13_status", "AMC13 Status;AMC13;", 2, 0.5, 2.5, nBitAMC13_, 0.5, nBitAMC13_ + 0.5); - h2AMCStatusNeg_ = ibooker.book2D("amc_status_GE11-N", - "AMC Status GE11-N;AMC slot;", + h2AMCStatusNeg_ = ibooker.book2D("amc_status_GE11-M", + "AMC Status GE11-M;AMC slot;", nAMCSlots_, -0.5, nAMCSlots_ - 0.5, @@ -142,9 +142,11 @@ void GEMDAQStatusSource::bookHistograms(DQMStore::IBooker &ibooker, edm::Run con GenerateMEPerChamber(ibooker); + h2SummaryStatusAll = CreateSummaryHist(ibooker, "chamberAllStatus"); h2SummaryStatusWarning = CreateSummaryHist(ibooker, "chamberWarnings"); h2SummaryStatusError = CreateSummaryHist(ibooker, "chamberErrors"); + h2SummaryStatusAll->setTitle("Summary of all number of OH or VFAT status of each chambers"); h2SummaryStatusWarning->setTitle("Summary of OH or VFAT warnings of each chambers"); h2SummaryStatusError->setTitle("Summary of OH or VFAT errors of each chambers"); } @@ -302,6 +304,7 @@ void GEMDAQStatusSource::analyze(edm::Event const &event, edm::EventSetup const } // WARNING: ME4IdsKey for region, station, layer, chamber (not iEta) + std::map mapChamberAll; std::map mapChamberWarning; std::map mapChamberError; @@ -356,6 +359,7 @@ void GEMDAQStatusSource::analyze(edm::Event const &event, edm::EventSetup const mapChamberWarning[key4] = false; if (bErr) mapChamberError[key4] = false; + mapChamberAll[key4] = true; } } @@ -410,11 +414,21 @@ void GEMDAQStatusSource::analyze(edm::Event const &event, edm::EventSetup const mapStatusWarnVFATPerLayer_.Fill(key3, gid.chamber(), nIdxVFAT); if (bErr) mapStatusErrVFATPerLayer_.Fill(key3, gid.chamber(), nIdxVFAT); + mapChamberAll[key4Ch] = true; } } + // Summarizing all presence of status of each chamber + for (auto const &[key4, bErr] : mapChamberAll) { + ME3IdsKey key3 = key4Tokey3(key4); + Int_t nChamber = keyToChamber(key4); + h2SummaryStatusAll->Fill(nChamber, mapStationToIdx_[key3]); + } + // Summarizing the warning occupancy for (auto const &[key4, bWarning] : mapChamberWarning) { + if (mapChamberError.find(key4) != mapChamberError.end()) // Avoiding any double-counting + continue; ME3IdsKey key3 = key4Tokey3(key4); Int_t nChamber = keyToChamber(key4); h2SummaryStatusWarning->Fill(nChamber, mapStationToIdx_[key3]); diff --git a/DQM/GEM/plugins/GEMDQMHarvester.cc b/DQM/GEM/plugins/GEMDQMHarvester.cc index ed001a5589204..8ba55f9603bb0 100644 --- a/DQM/GEM/plugins/GEMDQMHarvester.cc +++ b/DQM/GEM/plugins/GEMDQMHarvester.cc @@ -46,9 +46,14 @@ class GEMDQMHarvester : public DQMEDHarvester { MonitorElement *&h2Sum); Float_t refineSummaryHistogram(MonitorElement *h2Sum, MonitorElement *h2SrcOcc, + MonitorElement *h2SrcAllNum, MonitorElement *h2SrcStatusE, - MonitorElement *h2SrcStatusW = nullptr, - Bool_t bVarXBin = false); + MonitorElement *h2SrcStatusW); + Int_t refineSummaryVFAT(MonitorElement *h2Sum, + MonitorElement *h2SrcOcc, + MonitorElement *h2SrcStatusE, + MonitorElement *h2SrcStatusW); + Int_t assessOneBin(Float_t fAll, Float_t fNumOcc, Float_t fNumWarn, Float_t fNumErr); Float_t fReportSummary_; std::string strOutFile_; @@ -84,6 +89,7 @@ void GEMDQMHarvester::dqmEndLuminosityBlock(DQMStore::IBooker &, void GEMDQMHarvester::drawSummaryHistogram(edm::Service &store) { std::string strSrcDigiOcc = "GEM/Digis/summaryOccDigi"; + std::string strSrcStatusA = "GEM/DAQStatus/chamberAllStatus"; std::string strSrcStatusW = "GEM/DAQStatus/chamberWarnings"; std::string strSrcStatusE = "GEM/DAQStatus/chamberErrors"; @@ -94,13 +100,14 @@ void GEMDQMHarvester::drawSummaryHistogram(edm::Service &store) { store->setCurrentFolder(strDirSummary_); MonitorElement *h2SrcDigiOcc = store->get(strSrcDigiOcc); + MonitorElement *h2SrcStatusA = store->get(strSrcStatusA); MonitorElement *h2SrcStatusW = store->get(strSrcStatusW); MonitorElement *h2SrcStatusE = store->get(strSrcStatusE); - if (h2SrcDigiOcc != nullptr && h2SrcStatusW != nullptr && h2SrcStatusE != nullptr) { + if (h2SrcDigiOcc != nullptr && h2SrcStatusA != nullptr && h2SrcStatusW != nullptr && h2SrcStatusE != nullptr) { MonitorElement *h2Sum = nullptr; createSummaryHist(store, h2SrcStatusE, h2Sum, listLayer_); - fReportSummary_ = refineSummaryHistogram(h2Sum, h2SrcDigiOcc, h2SrcStatusE, h2SrcStatusW, true); + fReportSummary_ = refineSummaryHistogram(h2Sum, h2SrcDigiOcc, h2SrcStatusA, h2SrcStatusE, h2SrcStatusW); for (const auto &strSuffix : listLayer_) { MonitorElement *h2SrcVFATOcc = store->get(strSrcVFATOcc + strSuffix); @@ -110,7 +117,7 @@ void GEMDQMHarvester::drawSummaryHistogram(edm::Service &store) { continue; MonitorElement *h2SumVFAT = nullptr; createSummaryVFAT(store, h2SrcVFATStatusE, strSuffix, h2SumVFAT); - refineSummaryHistogram(h2SumVFAT, h2SrcVFATOcc, h2SrcVFATStatusE, h2SrcVFATStatusW); + refineSummaryVFAT(h2SumVFAT, h2SrcVFATOcc, h2SrcVFATStatusE, h2SrcVFATStatusW); TString strNewTitle = h2SrcVFATStatusE->getTitle(); h2SumVFAT->setTitle((const char *)strNewTitle.ReplaceAll("errors", "errors/warnings")); h2SumVFAT->setXTitle(h2SrcVFATStatusE->getAxisTitle(1)); @@ -171,36 +178,40 @@ void GEMDQMHarvester::createSummaryVFAT(edm::Service &store, copyLabels(h2Src, h2Sum); } +Int_t GEMDQMHarvester::assessOneBin(Float_t fAll, Float_t fNumOcc, Float_t fNumWarn, Float_t fNumErr) { + if (fNumErr > 0.05 * fAll) // The error status criterion + return 2; + else if (fNumErr > 0.00 * fAll || fNumWarn > 0.05 * fAll) // The warning status criterion + return 3; + else if (fNumOcc > 0) + return 1; + + return 0; +} + // FIXME: Need more study about how to summarize Float_t GEMDQMHarvester::refineSummaryHistogram(MonitorElement *h2Sum, MonitorElement *h2SrcOcc, + MonitorElement *h2SrcStatusA, MonitorElement *h2SrcStatusE, - MonitorElement *h2SrcStatusW, - Bool_t bVarXBin) { + MonitorElement *h2SrcStatusW) { Int_t nBinY = h2Sum->getNbinsY(); Int_t nAllBin = 0, nFineBin = 0; for (Int_t j = 1; j <= nBinY; j++) { Int_t nBinX = h2Sum->getNbinsX(); - if (bVarXBin) { - nBinX = (Int_t)(h2SrcOcc->getBinContent(0, j) + 0.5); - h2Sum->setBinContent(0, j, nBinX); - } + nBinX = (Int_t)(h2SrcOcc->getBinContent(0, j) + 0.5); + h2Sum->setBinContent(0, j, nBinX); for (Int_t i = 1; i <= nBinX; i++) { Float_t fOcc = h2SrcOcc->getBinContent(i, j); - Float_t fStatusWarn = (h2SrcStatusW != nullptr ? h2SrcStatusW->getBinContent(i, j) : 0.0); + Float_t fStatusAll = h2SrcStatusA->getBinContent(i, j); + Float_t fStatusWarn = h2SrcStatusW->getBinContent(i, j); Float_t fStatusErr = h2SrcStatusE->getBinContent(i, j); - Float_t fRes = 0; - if (fStatusErr > 0) - fRes = 2; - else if (fStatusWarn > 0) - fRes = 3; - else if (fOcc > 0) { - fRes = 1; + Int_t nRes = assessOneBin(fStatusAll, fOcc, fStatusWarn, fStatusErr); + if (nRes == 1) nFineBin++; - } - h2Sum->setBinContent(i, j, fRes); + h2Sum->setBinContent(i, j, (Float_t)nRes); nAllBin++; } } @@ -208,4 +219,24 @@ Float_t GEMDQMHarvester::refineSummaryHistogram(MonitorElement *h2Sum, return ((Float_t)nFineBin) / nAllBin; } +Int_t GEMDQMHarvester::refineSummaryVFAT(MonitorElement *h2Sum, + MonitorElement *h2SrcOcc, + MonitorElement *h2SrcStatusE, + MonitorElement *h2SrcStatusW) { + Int_t nBinY = h2Sum->getNbinsY(); + for (Int_t j = 1; j <= nBinY; j++) { + Int_t nBinX = h2Sum->getNbinsX(); + for (Int_t i = 1; i <= nBinX; i++) { + Float_t fOcc = h2SrcOcc->getBinContent(i, j); + Float_t fStatusWarn = h2SrcStatusW->getBinContent(i, j); + Float_t fStatusErr = h2SrcStatusE->getBinContent(i, j); + Float_t fStatusAll = fOcc + fStatusWarn + fStatusErr; + Int_t nRes = assessOneBin(fStatusAll, fOcc, fStatusWarn, fStatusErr); + h2Sum->setBinContent(i, j, (Float_t)nRes); + } + } + + return 0; +} + DEFINE_FWK_MODULE(GEMDQMHarvester); diff --git a/DQM/GEM/plugins/GEMDigiSource.cc b/DQM/GEM/plugins/GEMDigiSource.cc index 34ae5d5d6e4d2..fda09495c3c4d 100644 --- a/DQM/GEM/plugins/GEMDigiSource.cc +++ b/DQM/GEM/plugins/GEMDigiSource.cc @@ -107,7 +107,7 @@ int GEMDigiSource::ProcessWithMEMap3WithChamber(BookingHelper& bh, ME4IdsKey key int nNumVFATPerEta = stationInfo.nMaxVFAT_ / stationInfo.nNumEtaPartitions_; int nNumCh = stationInfo.nNumDigi_; - mapDigiOccPerCh_.SetBinConfX(nNumCh * nNumVFATPerEta); + mapDigiOccPerCh_.SetBinConfX(nNumCh * nNumVFATPerEta, -0.5); mapDigiOccPerCh_.SetBinConfY(stationInfo.nNumEtaPartitions_); mapDigiOccPerCh_.bookND(bh, key); mapDigiOccPerCh_.SetLabelForIEta(key, 2); diff --git a/DQM/GEM/plugins/GEMRecHitSource.cc b/DQM/GEM/plugins/GEMRecHitSource.cc index a359167cbb0bd..72442bdd92492 100644 --- a/DQM/GEM/plugins/GEMRecHitSource.cc +++ b/DQM/GEM/plugins/GEMRecHitSource.cc @@ -50,17 +50,17 @@ void GEMRecHitSource::bookHistograms(DQMStore::IBooker& ibooker, edm::Run const& mapTotalRecHitPerEvtLayer_ = MEMap3Inf(this, "rechits_per_layer", "Total number of RecHits per event for each layers", - 50, + 2000, -0.5, - 99.5, + 2000 - 0.5, "Number of RecHits", "Events"); mapTotalRecHitPerEvtIEta_ = MEMap3Inf(this, "rechits_per_ieta", "Total number of RecHits per event for each eta partitions", - 50, + 300, -0.5, - 99.5, + 300 - 0.5, "Number of RecHits", "Events"); mapCLSRecHit_ieta_ = MEMap3Inf( diff --git a/DQM/HcalCommon/interface/Constants.h b/DQM/HcalCommon/interface/Constants.h index d91541b65851c..c9494a31c5409 100644 --- a/DQM/HcalCommon/interface/Constants.h +++ b/DQM/HcalCommon/interface/Constants.h @@ -25,6 +25,7 @@ namespace hcaldqm { // use conversion functions in Utilities.h // For fast look up // This is for uTCA Crates/FEDs only - no other way... + // As of 2021: https://cmshcal.docs.cern.ch/hcos/crateFedMap/ std::map const crate2fed_map = { {24, 1100}, {20, 1102}, @@ -38,7 +39,6 @@ namespace hcaldqm { {22, 1118}, {29, 1120}, {32, 1122}, - //{38, 1134}, {3, 724}, {7, 726}, {6, 728}, @@ -48,7 +48,7 @@ namespace hcaldqm { {23, 1124}, {27, 1126}, {26, 1128}, - {38, 1130}, + {38, 1134}, }; std::map const fed2crate_map = { @@ -56,16 +56,18 @@ namespace hcaldqm { {1101, 24}, {1102, 20}, {1103, 20}, {1104, 21}, {1105, 21}, {1106, 25}, {1107, 25}, {1108, 31}, {1109, 31}, {1110, 35}, {1111, 35}, {1112, 37}, {1113, 37}, {1114, 34}, {1115, 34}, {1116, 30}, {1117, 30}, {1118, 22}, {1119, 22}, {1120, 29}, {1121, 29}, {1122, 32}, {1123, 32}, {1124, 23}, {1125, 23}, {1126, 27}, {1127, 27}, - {1128, 26}, {1129, 26}, {1130, 38}, {1131, 38}, {1134, 38}, {1135, 38}, + {1128, 26}, {1129, 26}, {1134, 38}, {1135, 38}, {1140, 24}, {1141, 20}, {1142, 21}, {1143, 25}, {1144, 31}, + {1145, 35}, {1146, 37}, {1147, 34}, {1148, 30}, }; - std::vector const fedList = {724, 725, 726, 727, 728, 729, 730, 731, 1100, 1101, 1102, - 1103, 1104, 1105, 1106, 1107, 1108, 1109, 1110, 1111, 1112, 1113, - 1114, 1115, 1116, 1117, 1118, 1119, 1120, 1121, 1122, 1123, 1124, - 1125, 1126, 1127, 1128, 1129, 1130, 1131, 1134, 1135}; - std::vector const fedListuTCA = { - 1100, 1101, 1102, 1103, 1104, 1105, 1106, 1107, 1108, 1109, 1110, 1111, 1112, 1113, 1114, 1115, 1116, - 1117, 1118, 1119, 1120, 1121, 1122, 1123, 1124, 1125, 1126, 1127, 1128, 1129, 1130, 1131, 1134, 1135}; + std::vector const fedList = { + 724, 725, 726, 727, 728, 729, 730, 731, 1100, 1101, 1102, 1103, 1104, 1105, 1106, 1107, 1108, + 1109, 1110, 1111, 1112, 1113, 1114, 1115, 1116, 1117, 1118, 1119, 1120, 1121, 1122, 1123, 1124, 1125, + 1126, 1127, 1128, 1129, 1134, 1135, 1140, 1141, 1142, 1143, 1144, 1145, 1146, 1147, 1148}; + std::vector const fedListuTCA = {1100, 1101, 1102, 1103, 1104, 1105, 1106, 1107, 1108, 1109, 1110, + 1111, 1112, 1113, 1114, 1115, 1116, 1117, 1118, 1119, 1120, 1121, + 1122, 1123, 1124, 1125, 1126, 1127, 1128, 1129, 1134, 1135, 1140, + 1141, 1142, 1143, 1144, 1145, 1146, 1147, 1148}; std::vector const fedListVME = {724, 725, 726, 727, 728, 729, 730, 731}; std::vector const crateList = {3, 6, 7, 13, 20, 21, 22, 23, 24, 25, 26, 27, 29, 30, 31, 32, 34, 35, 37, 38}; diff --git a/DQM/HcalCommon/src/HashFunctions.cc b/DQM/HcalCommon/src/HashFunctions.cc index 9b78ea8cddd7c..52a7c834e384e 100644 --- a/DQM/HcalCommon/src/HashFunctions.cc +++ b/DQM/HcalCommon/src/HashFunctions.cc @@ -243,10 +243,15 @@ namespace hcaldqm { if (eid.isVMEid()) return utilities::hash(HcalElectronicsId(FIBERCH_MIN, FIBER_VME_MIN, SPIGOT_MIN, eid.dccid())); else { - // tmp - we need to hash HF's FEDs with slot in mind - // bool isHF = eid.crateId()==22 || eid.crateId()==29 || eid.crateId()==32; + // HO and HO are dual-FED + bool isHF = eid.crateId() == 22 || eid.crateId() == 29 || eid.crateId() == 32; + bool isHO = eid.crateId() == 23 || eid.crateId() == 27 || eid.crateId() == 26 || eid.crateId() == 38; // for HF, slot number is either - int slotToUse = eid.slot() > 6 ? SLOT_uTCA_MIN + 6 : SLOT_uTCA_MIN; + int slotToUse = 1; + if (isHF || isHO) + slotToUse = eid.slot() > 6 ? SLOT_uTCA_MIN + 6 : SLOT_uTCA_MIN; + else + slotToUse = eid.slot() > 8 ? SLOT_uTCA_MIN + 8 : (eid.slot() > 4 ? SLOT_uTCA_MIN + 4 : SLOT_uTCA_MIN); return utilities::hash(HcalElectronicsId(eid.crateId(), slotToUse, FIBER_uTCA_MIN1, FIBERCH_MIN, false)); } } diff --git a/DQM/HcalCommon/src/Utilities.cc b/DQM/HcalCommon/src/Utilities.cc index 486cb3e2ae823..1bbce43e525b1 100644 --- a/DQM/HcalCommon/src/Utilities.cc +++ b/DQM/HcalCommon/src/Utilities.cc @@ -12,6 +12,8 @@ namespace hcaldqm { uint16_t slot = 0; if (fed <= FED_VME_MAX) { slot = fed % 2 == 0 ? SLOT_uTCA_MIN : SLOT_uTCA_MIN + 6; + } else if ((fed >= 1100 && fed <= 1117) || (fed >= 1140 && fed <= 1148)) { + slot = fed >= 1140 ? SLOT_uTCA_MIN + 8 : fed % 2 == 0 ? SLOT_uTCA_MIN : SLOT_uTCA_MIN + 4; } else { slot = fed % 2 == 0 ? SLOT_uTCA_MIN : SLOT_uTCA_MIN + 6; } @@ -36,9 +38,21 @@ namespace hcaldqm { ++fed; } } else { - if (slot > 6 && (std::find(constants::crateListuTCA.begin(), constants::crateListuTCA.end(), crate) != - constants::crateListuTCA.end())) { // needed to handle dual fed readout - ++fed; + if (crate == 22 || crate == 29 || crate == 32 || crate == 23 || crate == 27 || crate == 26 || + crate == 38) { // needed to handle dual fed readout for HF and HO + if (slot > 6 && (std::find(constants::crateListuTCA.begin(), constants::crateListuTCA.end(), crate) != + constants::crateListuTCA.end())) { + ++fed; // hard coded mid slot FED numbering + } + } else { // needed to handle 3-FED readout for HBHE + if (slot > 8 && (std::find(constants::crateListuTCA.begin(), constants::crateListuTCA.end(), crate) != + constants::crateListuTCA.end())) { + fed = (fed + 1100) / 2 + 40; // hard coded right slot FED numbering, no better way + } else if (slot > 4 && + (std::find(constants::crateListuTCA.begin(), constants::crateListuTCA.end(), crate) != + constants::crateListuTCA.end())) { + ++fed; // hard coded mid slot FED numbering + } } } } @@ -144,7 +158,7 @@ namespace hcaldqm { return false; } else { int fed = crate2fed(eid.crateId(), eid.slot()); - if (fed >= 1100 && fed < 1118) + if ((fed >= 1100 && fed < 1118) || (fed >= 1140 && fed <= 1148)) return true; else return false; @@ -154,17 +168,6 @@ namespace hcaldqm { } bool isFEDHF(HcalElectronicsId const &eid) { - /* - if (eid.isVMEid()) - { - int fed = eid.dccid()+FED_VME_MIN; - if (fed>=718 && fed<=723) - return true; - else - return false; - }*/ - // else - // { if (eid.isVMEid()) return false; int fed = crate2fed(eid.crateId(), eid.slot()); @@ -172,17 +175,15 @@ namespace hcaldqm { return true; else return false; - // } return false; } bool isFEDHO(HcalElectronicsId const &eid) { - if (!eid.isVMEid()) + if (eid.isVMEid()) return false; - - int fed = eid.dccid() + FED_VME_MIN; - if (fed >= 724 && fed <= 731) + int fed = crate2fed(eid.crateId(), eid.slot()); + if (fed >= 1124 && fed <= 1135) return true; else return false; diff --git a/DQM/HcalTasks/plugins/PedestalTask.cc b/DQM/HcalTasks/plugins/PedestalTask.cc index 8616f2c8926b5..44edb89c8a497 100644 --- a/DQM/HcalTasks/plugins/PedestalTask.cc +++ b/DQM/HcalTasks/plugins/PedestalTask.cc @@ -884,8 +884,8 @@ PedestalTask::PedestalTask(edm::ParameterSet const& ps) // @cDAQ if (hcaldqm::utilities::isFEDHBHE(eid) || hcaldqm::utilities::isFEDHO(eid) || hcaldqm::utilities::isFEDHF(eid)) { - double frmissing = double(_xNMsn1LS.get(eid)) / double(_xNChs.get(eid)); - double frbadm = _xNBadMean1LS.get(eid) / _xNChs.get(eid); + double frmissing = (_xNChs.get(eid) == 0) ? 0 : double(_xNMsn1LS.get(eid)) / double(_xNChs.get(eid)); + double frbadm = (_xNChs.get(eid) == 0) ? 0 : _xNBadMean1LS.get(eid) / _xNChs.get(eid); //double frbadr = _xNBadRMS1LS.get(eid)/_xNChs.get(eid); if (frmissing >= _thresh_missing_high) diff --git a/DQM/HcalTasks/plugins/RawTask.cc b/DQM/HcalTasks/plugins/RawTask.cc index 9c59f7fceedc1..887ecf08c8008 100644 --- a/DQM/HcalTasks/plugins/RawTask.cc +++ b/DQM/HcalTasks/plugins/RawTask.cc @@ -127,14 +127,14 @@ RawTask::RawTask(edm::ParameterSet const& ps) // Bad Quality _cBadQuality_FEDVME.initialize(_name, "BadQuality", - hcaldqm::hashfunctions::fFED, + hcaldqm::hashfunctions::fCrate, new hcaldqm::quantity::ElectronicsQuantity(hcaldqm::quantity::fSpigot), new hcaldqm::quantity::ElectronicsQuantity(hcaldqm::quantity::fFiberVMEFiberCh), new hcaldqm::quantity::ValueQuantity(hcaldqm::quantity::fN), 0); _cBadQuality_FEDuTCA.initialize(_name, "BadQuality", - hcaldqm::hashfunctions::fFED, + hcaldqm::hashfunctions::fCrate, new hcaldqm::quantity::ElectronicsQuantity(hcaldqm::quantity::fSlotuTCA), new hcaldqm::quantity::ElectronicsQuantity(hcaldqm::quantity::fFiberuTCAFiberCh), new hcaldqm::quantity::ValueQuantity(hcaldqm::quantity::fN), diff --git a/DQM/Integration/python/clients/beam_dqm_sourceclient-live_cfg.py b/DQM/Integration/python/clients/beam_dqm_sourceclient-live_cfg.py index 863cb3a5d712d..0e2fcf55a9737 100644 --- a/DQM/Integration/python/clients/beam_dqm_sourceclient-live_cfg.py +++ b/DQM/Integration/python/clients/beam_dqm_sourceclient-live_cfg.py @@ -4,16 +4,14 @@ # Define here the BeamSpotOnline record name, # it will be used both in BeamMonitor setup and in payload creation/upload BSOnlineRecordName = 'BeamSpotOnlineLegacyObjectsRcd' -BSOnlineTag = 'BeamSpotOnlinetLegacy' +BSOnlineTag = 'BeamSpotOnlineLegacy' BSOnlineJobName = 'BeamSpotOnlineLegacy' BSOnlineOmsServiceUrl = 'http://cmsoms-services.cms:9949/urn:xdaq-application:lid=100/getRunAndLumiSection' useLockRecords = True -#from Configuration.Eras.Era_Run2_2018_cff import Run2_2018 -#process = cms.Process("BeamMonitor", Run2_2018) FIXME import sys -from Configuration.Eras.Era_Run2_2018_pp_on_AA_cff import Run2_2018_pp_on_AA -process = cms.Process("BeamMonitor", Run2_2018_pp_on_AA) +from Configuration.Eras.Era_Run3_cff import Run3 +process = cms.Process("BeamMonitor", Run3) # Configure tag and jobName if running Playback system if "dqm_cmssw/playback" in str(sys.argv[1]): @@ -83,6 +81,13 @@ # you may need to set manually the GT in the line below #process.GlobalTag.globaltag = '100X_upgrade2018_realistic_v10' +#-------------------------------------------------------- +# Swap offline <-> online BeamSpot as in Express and HLT +import RecoVertex.BeamSpotProducer.onlineBeamSpotESProducer_cfi as _mod +process.BeamSpotESProducer = _mod.onlineBeamSpotESProducer.clone() +import RecoVertex.BeamSpotProducer.BeamSpotOnline_cfi +process.offlineBeamSpot = RecoVertex.BeamSpotProducer.BeamSpotOnline_cfi.onlineBeamSpotProducer.clone() + #---------------------------- # BeamMonitor process.load("DQM.BeamMonitor.BeamMonitor_Pixel_cff") @@ -166,7 +171,7 @@ import DQM.TrackingMonitor.TrackerCollisionTrackingMonitor_cfi process.pixelTracksMonitor = DQM.TrackingMonitor.TrackerCollisionTrackingMonitor_cfi.TrackerCollisionTrackMon.clone( - FolderName = 'BeamMonitor/Tracking/pixelTracks', + FolderName = 'BeamMonitorLegacy/Tracking/pixelTracks', TrackProducer = 'pixelTracks', allTrackProducer = 'pixelTracks', beamSpot = "offlineBeamSpot", @@ -213,7 +218,7 @@ # process.selectedPixelTracksMonitor = process.pixelTracksMonitor.clone( - FolderName = 'BeamMonitor/Tracking/selectedPixelTracks', + FolderName = 'BeamMonitorLegacy/Tracking/selectedPixelTracks', TrackProducer = 'tracks2monitor', allTrackProducer = 'tracks2monitor' ) @@ -248,7 +253,7 @@ # BeamSpotProblemMonitor # -process.dqmBeamSpotProblemMonitor.monitorName = "BeamMonitor/BeamSpotProblemMonitor" +process.dqmBeamSpotProblemMonitor.monitorName = "BeamMonitorLegacy/BeamSpotProblemMonitor" process.dqmBeamSpotProblemMonitor.AlarmONThreshold = 15 # was 10 process.dqmBeamSpotProblemMonitor.AlarmOFFThreshold = 17 # was 12 process.dqmBeamSpotProblemMonitor.nCosmicTrk = 10 @@ -304,6 +309,7 @@ process.load("RecoVertex.BeamSpotProducer.BeamSpot_cfi") process.dqmBeamMonitor.OnlineMode = True +process.dqmBeamMonitor.monitorName = "BeamMonitorLegacy" process.dqmBeamMonitor.recordName = BSOnlineRecordName process.dqmBeamMonitor.useLockRecords = useLockRecords @@ -321,11 +327,13 @@ process.pixelVertices = pixelVertices.clone( TkFilterParameters = dict( minPt = process.pixelTracksTrackingRegions.RegionPSet.ptMin) ) -process.pixelTracksTrackingRegions.RegionPSet.originRadius = 0.4 -process.pixelTracksTrackingRegions.RegionPSet.originHalfLength = 12 -process.pixelTracksTrackingRegions.RegionPSet.originXPos = 0.08 -process.pixelTracksTrackingRegions.RegionPSet.originYPos = -0.03 -process.pixelTracksTrackingRegions.RegionPSet.originZPos = 0. +#process.pixelTracksTrackingRegions.RegionPSet.ptMin = 0.1 # used in PilotBeam 2021, but not ok for standard collisions +process.pixelTracksTrackingRegions.RegionPSet.originRadius = 0.4 # used in PilotBeam 2021, to be checked again for standard collisions +# The following parameters were used in 2018 HI: +#process.pixelTracksTrackingRegions.RegionPSet.originHalfLength = 12 +#process.pixelTracksTrackingRegions.RegionPSet.originXPos = 0.08 +#process.pixelTracksTrackingRegions.RegionPSet.originYPos = -0.03 +#process.pixelTracksTrackingRegions.RegionPSet.originZPos = 0. process.tracking_FirstStep = cms.Sequence( process.siPixelDigis @@ -338,11 +346,12 @@ * process.recopixelvertexing) # triggerName for selecting pv for DIP publication, no wildcard needed here -# it will pick all triggers which has these strings in theri name +# it will pick all triggers which have these strings in their name process.dqmBeamMonitor.jetTrigger = [ "HLT_PAZeroBias_v", "HLT_ZeroBias_v", "HLT_QuadJet", "HLT_ZeroBias_", - "HLT_HI"] + "HLT_HI", + "HLT_PixelClusters"] # for HI only: select events based on the pixel cluster multiplicity if (process.runType.getRunType() == process.runType.hi_run): @@ -436,3 +445,5 @@ * process.monitor * process.BeamSpotProblemModule) +print("Final Source settings:", process.source) + diff --git a/DQM/Integration/python/clients/beamfake_dqm_sourceclient-live_cfg.py b/DQM/Integration/python/clients/beamfake_dqm_sourceclient-live_cfg.py index 04a7e29e5b94f..29a851aed72dc 100644 --- a/DQM/Integration/python/clients/beamfake_dqm_sourceclient-live_cfg.py +++ b/DQM/Integration/python/clients/beamfake_dqm_sourceclient-live_cfg.py @@ -10,8 +10,8 @@ BSOnlineOmsServiceUrl = 'http://cmsoms-services.cms:9949/urn:xdaq-application:lid=100/getRunAndLumiSection' useLockRecords = True import sys -from Configuration.Eras.Era_Run2_2018_cff import Run2_2018 -process = cms.Process("FakeBeamMonitor", Run2_2018) +from Configuration.Eras.Era_Run3_cff import Run3 +process = cms.Process("FakeBeamMonitor", Run3) # Configure tag and jobName if running Playback system if "dqm_cmssw/playback" in str(sys.argv[1]): diff --git a/DQM/Integration/python/clients/beamhlt_dqm_sourceclient-live_cfg.py b/DQM/Integration/python/clients/beamhlt_dqm_sourceclient-live_cfg.py index 7041223f56cc3..362d557b14954 100644 --- a/DQM/Integration/python/clients/beamhlt_dqm_sourceclient-live_cfg.py +++ b/DQM/Integration/python/clients/beamhlt_dqm_sourceclient-live_cfg.py @@ -12,8 +12,8 @@ #from Configuration.Eras.Era_Run2_2018_cff import Run2_2018 #process = cms.Process("BeamMonitor", Run2_2018) # FIMXE import sys -from Configuration.Eras.Era_Run2_2018_pp_on_AA_cff import Run2_2018_pp_on_AA -process = cms.Process("BeamMonitor", Run2_2018_pp_on_AA) +from Configuration.Eras.Era_Run3_cff import Run3 +process = cms.Process("BeamMonitor", Run3) # Configure tag and jobName if running Playback system if "dqm_cmssw/playback" in str(sys.argv[1]): @@ -120,22 +120,28 @@ from DQM.Integration.config.online_customizations_cfi import * process = customise(process) +#----------------------------------------------------------- +# Swap offline <-> online BeamSpot as in Express and HLT +import RecoVertex.BeamSpotProducer.onlineBeamSpotESProducer_cfi as _mod +process.BeamSpotESProducer = _mod.onlineBeamSpotESProducer.clone() +import RecoVertex.BeamSpotProducer.BeamSpotOnline_cfi +process.offlineBeamSpot = RecoVertex.BeamSpotProducer.BeamSpotOnline_cfi.onlineBeamSpotProducer.clone() + #-------------------------- # Proton-Proton Stuff #-------------------------- if (process.runType.getRunType() == process.runType.pp_run or process.runType.getRunType() == process.runType.pp_run_stage1 or - process.runType.getRunType() == process.runType.cosmic_run or - process.runType.getRunType() == process.runType.cosmic_run_stage1 or process.runType.getRunType() == process.runType.hpu_run or - process.runType.getRunType() == process.runType.hi_run): + process.runType.getRunType() == process.runType.hi_run or + process.runType.getRunType() == process.runType.commissioning_run): print("[beamhlt_dqm_sourceclient-live_cfg]:: Running pp") process.load("RecoVertex.BeamSpotProducer.BeamSpot_cfi") - process.dqmBeamMonitor.monitorName = 'BeamMonitor' + process.dqmBeamMonitor.monitorName = 'BeamMonitorHLT' process.dqmBeamMonitor.OnlineMode = True process.dqmBeamMonitor.recordName = BSOnlineRecordName @@ -160,11 +166,12 @@ process.dqmBeamMonitor.PVFitter.errorScale = 0.95 #TriggerName for selecting pv for DIP publication, NO wildcard needed here - #it will pick all triggers which has these strings in theri name + #it will pick all triggers which have these strings in their name process.dqmBeamMonitor.jetTrigger = cms.untracked.vstring( "HLT_HT300_Beamspot", "HLT_HT300_Beamspot", "HLT_PAZeroBias_v", "HLT_ZeroBias_", "HLT_QuadJet", - "HLT_HI") + "HLT_HI", + "HLT_PixelClusters") process.dqmBeamMonitor.hltResults = "TriggerResults::HLT" @@ -227,3 +234,5 @@ * process.offlineBeamSpot * process.monitor ) +print("Final Source settings:", process.source) + diff --git a/DQM/Integration/python/clients/beamhltfake_dqm_sourceclient-live_cfg.py b/DQM/Integration/python/clients/beamhltfake_dqm_sourceclient-live_cfg.py index c93032d5031ce..5efd2fac34e5c 100644 --- a/DQM/Integration/python/clients/beamhltfake_dqm_sourceclient-live_cfg.py +++ b/DQM/Integration/python/clients/beamhltfake_dqm_sourceclient-live_cfg.py @@ -10,8 +10,8 @@ useLockRecords = True import sys -from Configuration.Eras.Era_Run2_2018_cff import Run2_2018 -process = cms.Process("FakeBeamMonitor", Run2_2018) +from Configuration.Eras.Era_Run3_cff import Run3 +process = cms.Process("FakeBeamMonitor", Run3) # Configure tag and jobName if running Playback system if "dqm_cmssw/playback" in str(sys.argv[1]): diff --git a/DQM/Integration/python/clients/beampixel_dqm_sourceclient-live_cfg.py b/DQM/Integration/python/clients/beampixel_dqm_sourceclient-live_cfg.py index e5dab578f1b0e..8dc976ec53832 100644 --- a/DQM/Integration/python/clients/beampixel_dqm_sourceclient-live_cfg.py +++ b/DQM/Integration/python/clients/beampixel_dqm_sourceclient-live_cfg.py @@ -2,8 +2,8 @@ import FWCore.ParameterSet.Config as cms import sys -from Configuration.Eras.Era_Run2_2018_cff import Run2_2018 -process = cms.Process("BeamPixel", Run2_2018) +from Configuration.Eras.Era_Run3_cff import Run3 +process = cms.Process("BeamMonitor", Run3) unitTest = False if 'unitTest=True' in sys.argv: @@ -107,7 +107,7 @@ #---------------------------- if (process.runType.getRunType() == process.runType.pp_run or process.runType.getRunType() == process.runType.pp_run_stage1 or process.runType.getRunType() == process.runType.cosmic_run or process.runType.getRunType() == process.runType.cosmic_run_stage1 or - process.runType.getRunType() == process.runType.hpu_run): + process.runType.getRunType() == process.runType.hpu_run or process.runType.getRunType() == process.runType.commissioning_run ): print("[beampixel_dqm_sourceclient-live_cfg]::running pp") diff --git a/DQM/Integration/python/clients/beamspotdip_dqm_sourceclient-live_cfg.py b/DQM/Integration/python/clients/beamspotdip_dqm_sourceclient-live_cfg.py index 0b5b1c4988e63..4cd3f7216595e 100644 --- a/DQM/Integration/python/clients/beamspotdip_dqm_sourceclient-live_cfg.py +++ b/DQM/Integration/python/clients/beamspotdip_dqm_sourceclient-live_cfg.py @@ -1,6 +1,14 @@ from __future__ import print_function import FWCore.ParameterSet.Config as cms +# copy log4cplus.properties from >script directory< to >local< +import sys +import os +from shutil import copy +configFile = os.path.dirname(sys.argv[1]) + "/log4cplus.properties" +print("copying " + configFile + " to local") +copy(configFile,".") + # process = cms.Process("BeamSpotDipServer") process.load("DQMServices.Core.DQM_cfg") @@ -30,5 +38,10 @@ from DQM.Integration.config.online_customizations_cfi import * process = customise(process) +# monitoring +process.DQMMonitoringService = cms.Service("DQMMonitoringService") + # path process.p = cms.Path( process.beamSpotDipServer ) +print("Final Source settings:", process.source) + diff --git a/DQM/Integration/python/clients/ecal_dqm_sourceclient-live_cfg.py b/DQM/Integration/python/clients/ecal_dqm_sourceclient-live_cfg.py index 350732160fbb1..5f9b35d4a5552 100644 --- a/DQM/Integration/python/clients/ecal_dqm_sourceclient-live_cfg.py +++ b/DQM/Integration/python/clients/ecal_dqm_sourceclient-live_cfg.py @@ -16,7 +16,7 @@ from DQM.Integration.config.unittestinputsource_cfi import options else: process.load("DQM.Integration.config.inputsource_cfi") - from DQM.Integration.config.inputsource_cfi import options + from DQM.Integration.config.inputsource_cfi import options, set_BeamSplashRun_settings process.load("DQM.Integration.config.environment_cfi") process.load("DQM.Integration.config.FrontierCondition_GT_cfi") @@ -87,6 +87,34 @@ process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) ) +if not unitTest: + if options.BeamSplashRun: + set_BeamSplashRun_settings( process.source ) + process.ecalMonitorTask.workerParameters.TimingTask.params.splashSwitch = True + process.ecalMonitorTask.workerParameters.TimingTask.MEs.TimeMap.zaxis.high = cms.untracked.double(30.) + process.ecalMonitorTask.workerParameters.TimingTask.MEs.TimeMap.zaxis.low = cms.untracked.double(-30.) + process.ecalMonitorTask.workerParameters.TimingTask.MEs.TimeMapByLS.zaxis.high = cms.untracked.double(30.) + process.ecalMonitorTask.workerParameters.TimingTask.MEs.TimeMapByLS.zaxis.low = cms.untracked.double(-30.) + process.ecalMonitorTask.workerParameters.TimingTask.MEs.TimeAll.xaxis.high = cms.untracked.double(30.) + process.ecalMonitorTask.workerParameters.TimingTask.MEs.TimeAll.xaxis.low = cms.untracked.double(-30.) + process.ecalMonitorTask.workerParameters.TimingTask.MEs.Time1D.xaxis.high = cms.untracked.double(30.) + process.ecalMonitorTask.workerParameters.TimingTask.MEs.Time1D.xaxis.low = cms.untracked.double(-30.) + process.ecalMonitorTask.workerParameters.TimingTask.MEs.TimeAllMap.zaxis.high = cms.untracked.double(25.) + process.ecalMonitorTask.workerParameters.TimingTask.MEs.TimeAllMap.zaxis.low = cms.untracked.double(-25.) + process.ecalMonitorTask.workerParameters.TimingTask.params.chi2ThresholdEE = cms.untracked.double(1000.) + process.ecalMonitorTask.workerParameters.TimingTask.params.chi2ThresholdEB = cms.untracked.double(1000.) + + process.ecalMonitorClient.workerParameters.TimingClient.MEs.FwdvBkwd.yaxis.high = cms.untracked.double(30.) + process.ecalMonitorClient.workerParameters.TimingClient.MEs.FwdvBkwd.yaxis.low = cms.untracked.double(-30.) + process.ecalMonitorClient.workerParameters.TimingClient.MEs.FwdvBkwd.xaxis.high = cms.untracked.double(30.) + process.ecalMonitorClient.workerParameters.TimingClient.MEs.FwdvBkwd.xaxis.low = cms.untracked.double(-30.) + process.ecalMonitorClient.workerParameters.TimingClient.MEs.FwdBkwdDiff.xaxis.high = cms.untracked.double(25.) + process.ecalMonitorClient.workerParameters.TimingClient.MEs.FwdBkwdDiff.xaxis.low = cms.untracked.double(-25.) + process.ecalMonitorClient.workerParameters.TimingClient.MEs.MeanSM.xaxis.high = cms.untracked.double(30.) + process.ecalMonitorClient.workerParameters.TimingClient.MEs.MeanSM.xaxis.low = cms.untracked.double(-30.) + process.ecalMonitorClient.workerParameters.TimingClient.MEs.MeanAll.xaxis.high = cms.untracked.double(30.) + process.ecalMonitorClient.workerParameters.TimingClient.MEs.MeanAll.xaxis.low = cms.untracked.double(-30.) + process.ecalMonitorClient.workerParameters.TimingClient.params.minChannelEntries = cms.untracked.int32(0) process.ecalMonitorClient.verbosity = 0 process.ecalMonitorClient.workers = ['IntegrityClient', 'OccupancyClient', 'PresampleClient', 'RawDataClient', 'TimingClient', 'SelectiveReadoutClient', 'TrigPrimClient', 'SummaryClient'] diff --git a/DQM/Integration/python/clients/log4cplus.properties b/DQM/Integration/python/clients/log4cplus.properties new file mode 100644 index 0000000000000..f59034a2aba66 --- /dev/null +++ b/DQM/Integration/python/clients/log4cplus.properties @@ -0,0 +1,14 @@ +# Set root logger level to WARN and its only appender to A1. +log4cplus.rootLogger=WARN, A1 + +# A1 is set to be a ConsoleAppender. +log4cplus.appender.A1=log4cplus::ConsoleAppender +log4cplus.appender.A1.ImmediateFlush=true +log4cplus.appender.A1.logToStdErr=false + +# A1 uses PatternLayout. +log4cplus.appender.A1.layout=log4cplus::PatternLayout +log4cplus.appender.A1.layout.ConversionPattern=%d{%m/%d/%y %H:%M:%S} [%t] %-5p %c{2} %%%x%% - %m%n + +#log4cplus.logger.dip.system=INFO +#log4cplus.logger.dip.publication=WARN diff --git a/DQM/Integration/python/clients/onlinebeammonitor_dqm_sourceclient-live_cfg.py b/DQM/Integration/python/clients/onlinebeammonitor_dqm_sourceclient-live_cfg.py index 46e579f65fd74..8ded75cfe036a 100644 --- a/DQM/Integration/python/clients/onlinebeammonitor_dqm_sourceclient-live_cfg.py +++ b/DQM/Integration/python/clients/onlinebeammonitor_dqm_sourceclient-live_cfg.py @@ -4,11 +4,10 @@ # Define once the BeamSpotOnline record name, # will be used both in BeamMonitor setup and in payload creation/upload -#from Configuration.Eras.Era_Run2_2018_cff import Run2_2018 -#process = cms.Process("BeamMonitor", Run2_2018) # FIMXE import sys -from Configuration.Eras.Era_Run2_2018_cff import Run2_2018 -process = cms.Process("OnlineBeamMonitor", Run2_2018) + +from Configuration.Eras.Era_Run3_cff import Run3 +process = cms.Process("OnlineBeamMonitor", Run3) # Message logger #process.load("FWCore.MessageLogger.MessageLogger_cfi") @@ -42,13 +41,13 @@ ) options.register('runNumber', - 336055, + 346508, VarParsing.VarParsing.multiplicity.singleton, VarParsing.VarParsing.varType.int, "Run number. This run number has to be present in the dataset configured with the dataset option.") options.register('dataset', - '/ExpressCosmics/Commissioning2019-Express-v1/FEVT', + '/ExpressPhysics/Commissioning2021-Express-v1/FEVT', VarParsing.VarParsing.multiplicity.singleton, VarParsing.VarParsing.varType.string, "Dataset name like '/ExpressCosmics/Commissioning2019-Express-v1/FEVT'") @@ -102,7 +101,7 @@ process.source = cms.Source("EmptySource") process.source.numberEventsInRun=cms.untracked.uint32(100) process.source.firstRun = cms.untracked.uint32(options.runNumber) - process.source.firstLuminosityBlock = cms.untracked.uint32(49) + process.source.firstLuminosityBlock = cms.untracked.uint32(1) process.source.numberEventsInLuminosityBlock = cms.untracked.uint32(2) process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(100) @@ -123,17 +122,17 @@ # DQM Live Environment #----------------------------- process.load("DQM.Integration.config.environment_cfi") -process.dqmEnv.subSystemFolder = 'TrackingHLTBeamspotStream' -process.dqmSaver.tag = 'TrackingHLTBeamspotStream' +process.dqmEnv.subSystemFolder = 'OnlineBeamMonitor' +process.dqmSaver.tag = 'OnlineBeamMonitor' process.dqmSaver.runNumber = options.runNumber -process.dqmSaverPB.tag = 'TrackingHLTBeamspotStream' +process.dqmSaverPB.tag = 'OnlineBeamMonitor' process.dqmSaverPB.runNumber = options.runNumber #----------------------------- # BeamMonitor #----------------------------- process.dqmOnlineBeamMonitor = cms.EDProducer("OnlineBeamMonitor", -MonitorName = cms.untracked.string("onlineBeamMonitor") +MonitorName = cms.untracked.string("OnlineBeamMonitor") ) #--------------- diff --git a/DQM/Integration/python/clients/visualization-live-secondInstance_cfg.py b/DQM/Integration/python/clients/visualization-live-secondInstance_cfg.py index be6aff821d2e9..42d1e8d3a16ad 100644 --- a/DQM/Integration/python/clients/visualization-live-secondInstance_cfg.py +++ b/DQM/Integration/python/clients/visualization-live-secondInstance_cfg.py @@ -19,7 +19,7 @@ # this is needed to map the names of the run-types chosen by DQM to the scenarios, ideally we could converge to the same names #scenarios = {'pp_run': 'ppEra_Run2_2016','cosmic_run':'cosmicsEra_Run2_2016','hi_run':'HeavyIons'} #scenarios = {'pp_run': 'ppEra_Run2_2016','pp_run_stage1': 'ppEra_Run2_2016','cosmic_run':'cosmicsEra_Run2_2016','cosmic_run_stage1':'cosmicsEra_Run2_2016','hi_run':'HeavyIonsEra_Run2_HI'} -scenarios = {'pp_run': 'ppEra_Run3','cosmic_run':'cosmicsEra_Run3','hi_run':'ppEra_Run2_2016_pA'} +scenarios = {'pp_run': 'ppEra_Run3','cosmic_run':'cosmicsEra_Run3','hi_run':'ppEra_Run2_2016_pA', 'commissioning_run':'cosmicsEra_Run3'} if not runType.getRunTypeName() in scenarios.keys(): msg = "Error getting the scenario out of the 'runkey', no mapping for: %s\n"%runType.getRunTypeName() @@ -29,7 +29,7 @@ if not unitTest : if options.BeamSplashRun : - # scenarioName = 'ppEra_Run3' FIXME + scenarioName = 'ppEra_Run3' pass print("Using scenario:",scenarioName) diff --git a/DQM/Integration/python/clients/visualization-live_cfg.py b/DQM/Integration/python/clients/visualization-live_cfg.py index 698ae619b5aa6..c67e3906cd0df 100644 --- a/DQM/Integration/python/clients/visualization-live_cfg.py +++ b/DQM/Integration/python/clients/visualization-live_cfg.py @@ -19,7 +19,7 @@ # this is needed to map the names of the run-types chosen by DQM to the scenarios, ideally we could converge to the same names #scenarios = {'pp_run': 'ppEra_Run2_2016','cosmic_run':'cosmicsEra_Run2_2016','hi_run':'HeavyIons'} #scenarios = {'pp_run': 'ppEra_Run2_2016','pp_run_stage1': 'ppEra_Run2_2016','cosmic_run':'cosmicsEra_Run2_2016','cosmic_run_stage1':'cosmicsEra_Run2_2016','hi_run':'HeavyIonsEra_Run2_HI'} -scenarios = {'pp_run': 'ppEra_Run3','cosmic_run':'cosmicsEra_Run3','hi_run':'ppEra_Run2_2016_pA'} +scenarios = {'pp_run': 'ppEra_Run3','cosmic_run':'cosmicsEra_Run3','hi_run':'ppEra_Run2_2016_pA', 'commissioning_run':'cosmicsEra_Run3'} if not runType.getRunTypeName() in scenarios.keys(): msg = "Error getting the scenario out of the 'runkey', no mapping for: %s\n"%runType.getRunTypeName() @@ -29,7 +29,7 @@ if not unitTest : if options.BeamSplashRun : - # scenarioName = 'ppEra_Run3' #FIXME + scenarioName = 'ppEra_Run3' pass print("Using scenario:",scenarioName) diff --git a/DQM/Integration/python/config/FrontierCondition_GT_cfi.py b/DQM/Integration/python/config/FrontierCondition_GT_cfi.py index 977d6c93c8e2a..5845afa34bb65 100644 --- a/DQM/Integration/python/config/FrontierCondition_GT_cfi.py +++ b/DQM/Integration/python/config/FrontierCondition_GT_cfi.py @@ -2,3 +2,21 @@ from Configuration.StandardSequences.FrontierConditions_GlobalTag_cff import * from Configuration.AlCa.autoCond import autoCond GlobalTag.globaltag = autoCond['run3_hlt'] + +############################################# +# +# DO NOT REMOVE +# +# This GlobalTag customization is necessary to +# refresh the online BeamSpot ESProducer inputs +# used by the online DQM clients at every LS +# (as it done in the HLT menu). +############################################## +GlobalTag.toGet = cms.VPSet( + cms.PSet( record = cms.string( "BeamSpotOnlineLegacyObjectsRcd" ), + refreshTime = cms.uint64( 1 ), + ), + cms.PSet( record = cms.string( "BeamSpotOnlineHLTObjectsRcd" ), + refreshTime = cms.uint64( 1 ) + ) +) diff --git a/DQM/Integration/scripts/fileregistration/fileTransfer.py b/DQM/Integration/scripts/fileregistration/fileTransfer.py index 898acbb2aa5c6..307528ab7bc2e 100755 --- a/DQM/Integration/scripts/fileregistration/fileTransfer.py +++ b/DQM/Integration/scripts/fileregistration/fileTransfer.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 from __future__ import print_function -import os, time, sys, shutil, glob, smtplib, re, commands +import os, time, sys, shutil, glob, smtplib, re, subprocess import getopt as gop import zipfile as zp from datetime import datetime @@ -56,13 +56,13 @@ def injectFile(f,renotify=False): "--appname dqmArchive", "--appversion dqmArchive_1_0"] cmd="%s %s" % (INJECTIONSCRIPT," ".join(parameters)) - result = commands.getstatusoutput(cmd) + result = subprocess.getstatusoutput(cmd) if result[0] >= 1: output = result[1] print("Error injecting file %s to transfer system checking if it exists" % f) chkparameters=["--check","--filename %s" % fname,"--config %s" % CONFIGFILE] cmd="%s %s" % (INJECTIONSCRIPT," ".join(chkparameters)) - result = commands.getstatusoutput(cmd) + result = subprocess.getstatusoutput(cmd) if result[0]==1: if "File not found in database" in result[1]: print("Error: file %s not found in transfer database, check configuration" % f) diff --git a/DQM/Integration/scripts/harvesting_tools/cmsHarvester.py b/DQM/Integration/scripts/harvesting_tools/cmsHarvester.py index 0b8417747ed5c..a2a1d14837692 100755 --- a/DQM/Integration/scripts/harvesting_tools/cmsHarvester.py +++ b/DQM/Integration/scripts/harvesting_tools/cmsHarvester.py @@ -90,7 +90,7 @@ import os import sys -import commands +import subprocess import re import logging import optparse @@ -1470,7 +1470,7 @@ def create_and_check_castor_dirs(self): self.logger.debug("Checking if path `%s' is empty" % \ castor_dir) cmd = "rfdir %s" % castor_dir - (status, output) = commands.getstatusoutput(cmd) + (status, output) = subprocess.getstatusoutput(cmd) if status != 0: msg = "Could not access directory `%s'" \ " !!! This is bad since I should have just" \ @@ -1630,18 +1630,18 @@ def extract_permissions(rfstat_output): self.logger.debug("Checking if path `%s' exists" % \ path) cmd = "rfstat %s" % path - (status, output) = commands.getstatusoutput(cmd) + (status, output) = subprocess.getstatusoutput(cmd) if status != 0: # Path does not exist, let's try and create it. self.logger.debug("Creating path `%s'" % path) cmd = "nsmkdir -m 775 %s" % path - (status, output) = commands.getstatusoutput(cmd) + (status, output) = subprocess.getstatusoutput(cmd) if status != 0: msg = "Could not create directory `%s'" % path self.logger.fatal(msg) raise Error(msg) cmd = "rfstat %s" % path - (status, output) = commands.getstatusoutput(cmd) + (status, output) = subprocess.getstatusoutput(cmd) # Now check that it looks like a directory. If I'm not # mistaken one can deduce this from the fact that the # (octal) permissions string starts with `40' (instead @@ -1656,7 +1656,7 @@ def extract_permissions(rfstat_output): # (partial) path. self.logger.debug("Checking permissions for path `%s'" % path) cmd = "rfstat %s" % path - (status, output) = commands.getstatusoutput(cmd) + (status, output) = subprocess.getstatusoutput(cmd) if status != 0: msg = "Could not obtain permissions for directory `%s'" % \ path @@ -1690,7 +1690,7 @@ def extract_permissions(rfstat_output): "to %s (were %s)" % \ (path, permissions_new, permissions)) cmd = "rfchmod %s %s" % (permissions_new, path) - (status, output) = commands.getstatusoutput(cmd) + (status, output) = subprocess.getstatusoutput(cmd) if status != 0: msg = "Could not change permissions for path `%s' " \ "to %s" % (path, permissions_new) @@ -1830,7 +1830,7 @@ def pick_a_site(self, sites, cmssw_version): "CEStatus=Production," \ "CloseSE=%s'" % \ (cmssw_version, se_name) - (status, output) = commands.getstatusoutput(cmd) + (status, output) = subprocess.getstatusoutput(cmd) if status != 0: self.logger.error("Could not check site information " \ "for site `%s'" % se_name) @@ -2373,7 +2373,7 @@ def check_dbs(self): ## # NOTE: Not ideal, I know, but it reduces the amount of ## # complaints I get... ## cmd = "dbs search --query=\"find dataset where dataset = impossible\"" -## (status, output) = commands.getstatusoutput(cmd) +## (status, output) = subprocess.getstatusoutput(cmd) ## pdb.set_trace() ## if status != 0 or \ ## output.lower().find("unsupported api call") > -1: @@ -3664,7 +3664,7 @@ def process_runs_use_and_ignore_lists(self): runs_todo = [] print("Reading runs from file /afs/cern.ch/cms/CAF/CMSCOMM/COMM_DQM/harvesting/%s" %self.todofile) cmd="grep %s /afs/cern.ch/cms/CAF/CMSCOMM/COMM_DQM/harvesting/%s | cut -f5 -d' '" %(dataset_name,self.todofile) - (status, output)=commands.getstatusoutput(cmd) + (status, output)=subprocess.getstatusoutput(cmd) for run in runs: run_str="%s" %run if run_str in output: @@ -4326,7 +4326,7 @@ def create_multicrab_config(self): """ cmd="who i am | cut -f1 -d' '" - (status, output)=commands.getstatusoutput(cmd) + (status, output)=subprocess.getstatusoutput(cmd) UserName = output if self.caf_access == True: @@ -4355,7 +4355,7 @@ def create_multicrab_config(self): ["castor_path"][run] cmd = "rfdir %s" % castor_dir - (status, output) = commands.getstatusoutput(cmd) + (status, output) = subprocess.getstatusoutput(cmd) if len(output) <= 0: @@ -4564,7 +4564,7 @@ def check_globaltag_exists(self, globaltag, connect_name): cmd = "cmscond_tagtree_list -c %s -T %s" % \ (connect_name, globaltag) - (status, output) = commands.getstatusoutput(cmd) + (status, output) = subprocess.getstatusoutput(cmd) if status != 0 or \ output.find("error") > -1: msg = "Could not check existence of GlobalTag `%s' in `%s'" % \ @@ -4609,7 +4609,7 @@ def check_globaltag_contains_ref_hist_key(self, globaltag, connect_name): connect_name) cmd = "cmscond_tagtree_list -c %s -T %s -n %s" % \ (connect_name, globaltag, ref_hist_key) - (status, output) = commands.getstatusoutput(cmd) + (status, output) = subprocess.getstatusoutput(cmd) if status != 0 or \ output.find("error") > -1: msg = "Could not check existence of key `%s'" % \ @@ -4658,7 +4658,7 @@ def check_ref_hist_tag(self, tag_name): cmd = "cmscond_list_iov -c %s" % \ connect_name - (status, output) = commands.getstatusoutput(cmd) + (status, output) = subprocess.getstatusoutput(cmd) if status != 0: msg = "Could not check existence of tag `%s' in `%s'" % \ (tag_name, connect_name) @@ -4872,11 +4872,11 @@ def create_harvesting_config(self, dataset_name): ## # To be removed in production version. ## customisations.append("import pdb") ## # BUG BUG BUG end -## customisations.append("import commands") +## customisations.append("import subprocess") ## customisations.append("import os") ## customisations.append("castor_dir = \"%s\"" % castor_dir) ## customisations.append("cmd = \"rfdir %s\" % castor_dir") -## customisations.append("(status, output) = commands.getstatusoutput(cmd)") +## customisations.append("(status, output) = subprocess.getstatusoutput(cmd)") ## customisations.append("if status != 0:") ## customisations.append(" print \"ERROR\"") ## customisations.append(" raise Exception, \"ERROR\"") diff --git a/DQM/Integration/test/BuildFile.xml b/DQM/Integration/test/BuildFile.xml index 890e4833e4ab5..157ab636e88b7 100644 --- a/DQM/Integration/test/BuildFile.xml +++ b/DQM/Integration/test/BuildFile.xml @@ -29,6 +29,5 @@ - - - + + diff --git a/DQM/L1TMonitor/interface/L1ExtraDQM.h b/DQM/L1TMonitor/interface/L1ExtraDQM.h index ca298444d70fd..41b95bf8b1c86 100644 --- a/DQM/L1TMonitor/interface/L1ExtraDQM.h +++ b/DQM/L1TMonitor/interface/L1ExtraDQM.h @@ -24,8 +24,6 @@ #include // user include files -// base classes -#include "FWCore/Framework/interface/EDAnalyzer.h" // #include "FWCore/Framework/interface/Frameworkfwd.h" @@ -83,7 +81,7 @@ class L1ExtraDQM : public DQMOneEDAnalyzer<> { class L1ExtraMonElement { public: // constructor - L1ExtraMonElement(const edm::EventSetup&, const int); + L1ExtraMonElement(const L1GetHistLimits::Tokens&, const int); // destructor virtual ~L1ExtraMonElement(); @@ -138,6 +136,7 @@ class L1ExtraDQM : public DQMOneEDAnalyzer<> { const int bxInEvent); private: + L1GetHistLimits::Tokens m_tokens; std::vector m_monElement; /// histogram index for each quantity, set during histogram booking @@ -174,7 +173,6 @@ class L1ExtraDQM : public DQMOneEDAnalyzer<> { private: /// input parameters - L1RetrieveL1Extra m_retrieveL1Extra; edm::InputTag L1ExtraIsoTauJetSource; /// directory name for L1Extra plots @@ -197,6 +195,8 @@ class L1ExtraDQM : public DQMOneEDAnalyzer<> { private: edm::EDGetTokenT m_tagL1ExtraIsoTauJetTok; + L1GetHistLimits::Tokens m_histTokens; + /// pointers to L1ExtraMonElement for each sub-analysis std::vector*> m_meAnalysisL1ExtraMuon; diff --git a/DQM/L1TMonitor/interface/L1TdeGEMTPG.h b/DQM/L1TMonitor/interface/L1TdeGEMTPG.h index 2a0969bda547d..10ff17ddc0b3e 100644 --- a/DQM/L1TMonitor/interface/L1TdeGEMTPG.h +++ b/DQM/L1TMonitor/interface/L1TdeGEMTPG.h @@ -33,6 +33,8 @@ class L1TdeGEMTPG : public DQMEDAnalyzer { std::vector clusterMinBin_; std::vector clusterMaxBin_; + bool useDataClustersOnlyInBX0_; + // first key is the chamber number // second key is the variable std::map > chamberHistos; diff --git a/DQM/L1TMonitor/python/L1TdeGEMTPG_cfi.py b/DQM/L1TMonitor/python/L1TdeGEMTPG_cfi.py index 78a0f0babae1f..20a4a24ea995d 100644 --- a/DQM/L1TMonitor/python/L1TdeGEMTPG_cfi.py +++ b/DQM/L1TMonitor/python/L1TdeGEMTPG_cfi.py @@ -8,8 +8,11 @@ dataEmul = cms.vstring("data","emul"), clusterVars = cms.vstring("size", "pad", "bx"), clusterNBin = cms.vuint32(20,384,10), - clusterMinBin = cms.vdouble(-0.5,-0.5,-4.5), - clusterMaxBin = cms.vdouble(19.5,383.5,5.5), + clusterMinBin = cms.vdouble(0,0,-5), + clusterMaxBin = cms.vdouble(20,384,5), + ## GEM VFAT data is not captured in BX's other than BX0 + ## For a good comparison, leave out those data clusters + useDataClustersOnlyInBX0 = cms.bool(True), B904Setup = cms.bool(False), ) @@ -17,6 +20,6 @@ l1tdeGEMTPG = DQMEDAnalyzer( "L1TdeGEMTPG", l1tdeGEMTPGCommon, - data = cms.InputTag("valMuonGEMPadDigiClusters"), + data = cms.InputTag("emtfStage2Digis"), emul = cms.InputTag("valMuonGEMPadDigiClusters"), ) diff --git a/DQM/L1TMonitor/src/L1ExtraDQM.cc b/DQM/L1TMonitor/src/L1ExtraDQM.cc index b85cc572372ab..bdb59100f36fd 100644 --- a/DQM/L1TMonitor/src/L1ExtraDQM.cc +++ b/DQM/L1TMonitor/src/L1ExtraDQM.cc @@ -36,9 +36,9 @@ L1ExtraDQM::L1ExtraDQM(const edm::ParameterSet& paramSet) m_currentRun(-99), // m_nrEvJob(0), - m_nrEvRun(0) - -{ + m_nrEvRun(0), + // + m_histTokens(consumesCollector(), true) { // if ((m_nrBxInEventGmt > 0) && ((m_nrBxInEventGmt % 2) == 0)) { m_nrBxInEventGmt = m_nrBxInEventGmt - 1; @@ -348,7 +348,7 @@ void L1ExtraDQM::bookHistograms(DQMStore::IBooker& ibooker, edm::Run const&, edm for (int iBxInEvent = 0; iBxInEvent < m_nrBxInEventGmt; ++iBxInEvent) { m_meAnalysisL1ExtraMuon.push_back( - new L1ExtraDQM::L1ExtraMonElement(evSetup, nrMonElements)); + new L1ExtraDQM::L1ExtraMonElement(m_histTokens, nrMonElements)); int bxInEvent = iBxInEvent + (m_nrBxInEventGct + 1) / 2 - m_nrBxInEventGct; int bxInEventHex = (bxInEvent + 16) % 16; @@ -370,7 +370,7 @@ void L1ExtraDQM::bookHistograms(DQMStore::IBooker& ibooker, edm::Run const&, edm for (int iBxInEvent = 0; iBxInEvent < m_nrBxInEventGct; ++iBxInEvent) { m_meAnalysisL1ExtraIsoEG.push_back( - new L1ExtraDQM::L1ExtraMonElement(evSetup, nrMonElements)); + new L1ExtraDQM::L1ExtraMonElement(m_histTokens, nrMonElements)); int bxInEvent = iBxInEvent + (m_nrBxInEventGct + 1) / 2 - m_nrBxInEventGct; int bxInEventHex = (bxInEvent + 16) % 16; @@ -392,7 +392,7 @@ void L1ExtraDQM::bookHistograms(DQMStore::IBooker& ibooker, edm::Run const&, edm for (int iBxInEvent = 0; iBxInEvent < m_nrBxInEventGct; ++iBxInEvent) { m_meAnalysisL1ExtraNoIsoEG.push_back( - new L1ExtraDQM::L1ExtraMonElement(evSetup, nrMonElements)); + new L1ExtraDQM::L1ExtraMonElement(m_histTokens, nrMonElements)); int bxInEvent = iBxInEvent + (m_nrBxInEventGct + 1) / 2 - m_nrBxInEventGct; int bxInEventHex = (bxInEvent + 16) % 16; @@ -416,7 +416,7 @@ void L1ExtraDQM::bookHistograms(DQMStore::IBooker& ibooker, edm::Run const&, edm for (int iBxInEvent = 0; iBxInEvent < m_nrBxInEventGct; ++iBxInEvent) { m_meAnalysisL1ExtraCenJet.push_back( - new L1ExtraDQM::L1ExtraMonElement(evSetup, nrMonElements)); + new L1ExtraDQM::L1ExtraMonElement(m_histTokens, nrMonElements)); int bxInEvent = iBxInEvent + (m_nrBxInEventGct + 1) / 2 - m_nrBxInEventGct; int bxInEventHex = (bxInEvent + 16) % 16; @@ -437,7 +437,7 @@ void L1ExtraDQM::bookHistograms(DQMStore::IBooker& ibooker, edm::Run const&, edm for (int iBxInEvent = 0; iBxInEvent < m_nrBxInEventGct; ++iBxInEvent) { m_meAnalysisL1ExtraForJet.push_back( - new L1ExtraDQM::L1ExtraMonElement(evSetup, nrMonElements)); + new L1ExtraDQM::L1ExtraMonElement(m_histTokens, nrMonElements)); int bxInEvent = iBxInEvent + (m_nrBxInEventGct + 1) / 2 - m_nrBxInEventGct; int bxInEventHex = (bxInEvent + 16) % 16; @@ -458,7 +458,7 @@ void L1ExtraDQM::bookHistograms(DQMStore::IBooker& ibooker, edm::Run const&, edm for (int iBxInEvent = 0; iBxInEvent < m_nrBxInEventGct; ++iBxInEvent) { m_meAnalysisL1ExtraTauJet.push_back( - new L1ExtraDQM::L1ExtraMonElement(evSetup, nrMonElements)); + new L1ExtraDQM::L1ExtraMonElement(m_histTokens, nrMonElements)); int bxInEvent = iBxInEvent + (m_nrBxInEventGct + 1) / 2 - m_nrBxInEventGct; int bxInEventHex = (bxInEvent + 16) % 16; @@ -480,7 +480,7 @@ void L1ExtraDQM::bookHistograms(DQMStore::IBooker& ibooker, edm::Run const&, edm for (int iBxInEvent = 0; iBxInEvent < m_nrBxInEventGct; ++iBxInEvent) { m_meAnalysisL1ExtraIsoTauJet.push_back( - new L1ExtraDQM::L1ExtraMonElement(evSetup, nrMonElements)); + new L1ExtraDQM::L1ExtraMonElement(m_histTokens, nrMonElements)); int bxInEvent = iBxInEvent + (m_nrBxInEventGct + 1) / 2 - m_nrBxInEventGct; int bxInEventHex = (bxInEvent + 16) % 16; @@ -506,7 +506,7 @@ void L1ExtraDQM::bookHistograms(DQMStore::IBooker& ibooker, edm::Run const&, edm for (int iBxInEvent = 0; iBxInEvent < m_nrBxInEventGct; ++iBxInEvent) { m_meAnalysisL1ExtraETT.push_back( - new L1ExtraDQM::L1ExtraMonElement(evSetup, nrMonElements)); + new L1ExtraDQM::L1ExtraMonElement(m_histTokens, nrMonElements)); int bxInEvent = iBxInEvent + (m_nrBxInEventGct + 1) / 2 - m_nrBxInEventGct; int bxInEventHex = (bxInEvent + 16) % 16; @@ -531,7 +531,7 @@ void L1ExtraDQM::bookHistograms(DQMStore::IBooker& ibooker, edm::Run const&, edm for (int iBxInEvent = 0; iBxInEvent < m_nrBxInEventGct; ++iBxInEvent) { m_meAnalysisL1ExtraETM.push_back( - new L1ExtraDQM::L1ExtraMonElement(evSetup, nrMonElements)); + new L1ExtraDQM::L1ExtraMonElement(m_histTokens, nrMonElements)); int bxInEvent = iBxInEvent + (m_nrBxInEventGct + 1) / 2 - m_nrBxInEventGct; int bxInEventHex = (bxInEvent + 16) % 16; @@ -555,7 +555,7 @@ void L1ExtraDQM::bookHistograms(DQMStore::IBooker& ibooker, edm::Run const&, edm for (int iBxInEvent = 0; iBxInEvent < m_nrBxInEventGct; ++iBxInEvent) { m_meAnalysisL1ExtraHTT.push_back( - new L1ExtraDQM::L1ExtraMonElement(evSetup, nrMonElements)); + new L1ExtraDQM::L1ExtraMonElement(m_histTokens, nrMonElements)); int bxInEvent = iBxInEvent + (m_nrBxInEventGct + 1) / 2 - m_nrBxInEventGct; int bxInEventHex = (bxInEvent + 16) % 16; @@ -579,7 +579,7 @@ void L1ExtraDQM::bookHistograms(DQMStore::IBooker& ibooker, edm::Run const&, edm for (int iBxInEvent = 0; iBxInEvent < m_nrBxInEventGct; ++iBxInEvent) { m_meAnalysisL1ExtraHTM.push_back( - new L1ExtraDQM::L1ExtraMonElement(evSetup, nrMonElements)); + new L1ExtraDQM::L1ExtraMonElement(m_histTokens, nrMonElements)); int bxInEvent = iBxInEvent + (m_nrBxInEventGct + 1) / 2 - m_nrBxInEventGct; int bxInEventHex = (bxInEvent + 16) % 16; @@ -607,7 +607,7 @@ void L1ExtraDQM::bookHistograms(DQMStore::IBooker& ibooker, edm::Run const&, edm for (int iBxInEvent = 0; iBxInEvent < m_nrBxInEventGct; ++iBxInEvent) { m_meAnalysisL1ExtraHfBitCounts.push_back( - new L1ExtraDQM::L1ExtraMonElement(evSetup, nrMonElements)); + new L1ExtraDQM::L1ExtraMonElement(m_histTokens, nrMonElements)); int bxInEvent = iBxInEvent + (m_nrBxInEventGct + 1) / 2 - m_nrBxInEventGct; int bxInEventHex = (bxInEvent + 16) % 16; @@ -632,7 +632,7 @@ void L1ExtraDQM::bookHistograms(DQMStore::IBooker& ibooker, edm::Run const&, edm for (int iBxInEvent = 0; iBxInEvent < m_nrBxInEventGct; ++iBxInEvent) { m_meAnalysisL1ExtraHfRingEtSums.push_back( - new L1ExtraDQM::L1ExtraMonElement(evSetup, nrMonElements)); + new L1ExtraDQM::L1ExtraMonElement(m_histTokens, nrMonElements)); int bxInEvent = iBxInEvent + (m_nrBxInEventGct + 1) / 2 - m_nrBxInEventGct; int bxInEventHex = (bxInEvent + 16) % 16; @@ -786,8 +786,10 @@ void L1ExtraDQM::dqmEndRun(const edm::Run& run, const edm::EventSetup& evSetup) // constructor L1ExtraMonElement template -L1ExtraDQM::L1ExtraMonElement::L1ExtraMonElement(const edm::EventSetup& evSetup, const int nrElements) - : m_indexNrObjects(-1), +L1ExtraDQM::L1ExtraMonElement::L1ExtraMonElement(const L1GetHistLimits::Tokens& tokens, + const int nrElements) + : m_tokens(tokens), + m_indexNrObjects(-1), m_indexPt(-1), m_indexEt(-1), m_indexPhi(-1), @@ -826,7 +828,7 @@ void L1ExtraDQM::L1ExtraMonElement::bookhistograms(const edm::Ev int indexHistogram = -1; if (gtObj == HfBitCounts) { - L1GetHistLimits l1GetHistLimits(evSetup); + L1GetHistLimits l1GetHistLimits(m_tokens, evSetup); const L1GetHistLimits::L1HistLimits& histLimits = l1GetHistLimits.l1HistLimits(gtObj, quantity); const int histNrBins = histLimits.nrBins; @@ -855,7 +857,7 @@ void L1ExtraDQM::L1ExtraMonElement::bookhistograms(const edm::Ev (gtObj == TauJet)) { quantity = "NrObjects"; - L1GetHistLimits l1GetHistLimits(evSetup); + L1GetHistLimits l1GetHistLimits(m_tokens, evSetup); const L1GetHistLimits::L1HistLimits& histLimits = l1GetHistLimits.l1HistLimits(gtObj, quantity); const int histNrBins = histLimits.nrBins; @@ -885,7 +887,7 @@ void L1ExtraDQM::L1ExtraMonElement::bookhistograms(const edm::Ev quantityLongName = " transverse momentum "; } - L1GetHistLimits l1GetHistLimits(evSetup); + L1GetHistLimits l1GetHistLimits(m_tokens, evSetup); const L1GetHistLimits::L1HistLimits& histLimits = l1GetHistLimits.l1HistLimits(gtObj, quantity); const int histNrBinsET = histLimits.nrBins; @@ -946,7 +948,7 @@ void L1ExtraDQM::L1ExtraMonElement::bookhistograms(const edm::Ev quantity = "phi"; // get limits and binning from L1Extra - L1GetHistLimits l1GetHistLimits(evSetup); + L1GetHistLimits l1GetHistLimits(m_tokens, evSetup); const L1GetHistLimits::L1HistLimits& histLimits = l1GetHistLimits.l1HistLimits(gtObj, quantity); const int histNrBinsPhi = histLimits.nrBins; @@ -987,7 +989,7 @@ void L1ExtraDQM::L1ExtraMonElement::bookhistograms(const edm::Ev quantity = "eta"; // get limits and binning from L1Extra - L1GetHistLimits l1GetHistLimits(evSetup); + L1GetHistLimits l1GetHistLimits(m_tokens, evSetup); const L1GetHistLimits::L1HistLimits& histLimits = l1GetHistLimits.l1HistLimits(gtObj, quantity); const int histNrBinsEta = histLimits.nrBins; diff --git a/DQM/L1TMonitor/src/L1TdeGEMTPG.cc b/DQM/L1TMonitor/src/L1TdeGEMTPG.cc index 8a391de1bf62e..15ced5f2512b3 100644 --- a/DQM/L1TMonitor/src/L1TdeGEMTPG.cc +++ b/DQM/L1TMonitor/src/L1TdeGEMTPG.cc @@ -17,7 +17,8 @@ L1TdeGEMTPG::L1TdeGEMTPG(const edm::ParameterSet& ps) // binning clusterNBin_(ps.getParameter>("clusterNBin")), clusterMinBin_(ps.getParameter>("clusterMinBin")), - clusterMaxBin_(ps.getParameter>("clusterMaxBin")) {} + clusterMaxBin_(ps.getParameter>("clusterMaxBin")), + useDataClustersOnlyInBX0_(ps.getParameter("useDataClustersOnlyInBX0")) {} L1TdeGEMTPG::~L1TdeGEMTPG() {} @@ -57,6 +58,10 @@ void L1TdeGEMTPG::analyze(const edm::Event& e, const edm::EventSetup& c) { const int type = ((*it).first).station() - 1; for (auto cluster = range.first; cluster != range.second; cluster++) { if (cluster->isValid()) { + // ignore data clusters in BX's other than BX0 + if (useDataClustersOnlyInBX0_ and cluster->bx() != 0) + continue; + chamberHistos[type]["cluster_size_data"]->Fill(cluster->pads().size()); chamberHistos[type]["cluster_pad_data"]->Fill(cluster->pads().front()); chamberHistos[type]["cluster_bx_data"]->Fill(cluster->bx()); diff --git a/DQM/SiPixelPhase1Summary/interface/SiPixelPhase1Summary.h b/DQM/SiPixelPhase1Summary/interface/SiPixelPhase1Summary.h index 244b46f8dfd1e..064b2b8909606 100644 --- a/DQM/SiPixelPhase1Summary/interface/SiPixelPhase1Summary.h +++ b/DQM/SiPixelPhase1Summary/interface/SiPixelPhase1Summary.h @@ -78,6 +78,7 @@ class SiPixelPhase1Summary : public DQMEDHarvester { //Error thresholds for the dead ROC plots std::vector deadRocThresholds_; + std::vector deadRocWarnThresholds_; //book the summary plots void bookSummaries(DQMStore::IBooker& iBooker); diff --git a/DQM/SiPixelPhase1Summary/python/SiPixelPhase1Summary_cfi.py b/DQM/SiPixelPhase1Summary/python/SiPixelPhase1Summary_cfi.py index bd28caa06393a..d2a64c74b5646 100644 --- a/DQM/SiPixelPhase1Summary/python/SiPixelPhase1Summary_cfi.py +++ b/DQM/SiPixelPhase1Summary/python/SiPixelPhase1Summary_cfi.py @@ -35,7 +35,8 @@ ) ), # Number of dead ROCs required to generate an error. Order must be layers 1-4, ring1, ring2. - DeadROCErrorThreshold = cms.vdouble(0.2,0.2,0.2,0.2,0.2,0.2) + DeadROCErrorThreshold = cms.vdouble(0.2,0.2,0.2,0.2,0.2,0.2), + DeadROCWarningThreshold = cms.vdouble(0.1,0.1,0.1,0.1,0.1,0.1) ) SiPixelPhase1SummaryOffline = DQMEDHarvester("SiPixelPhase1Summary", @@ -67,8 +68,8 @@ MapHist = cms.string("mean_charge") ) ), - DeadROCErrorThreshold = cms.vdouble(0.2,0.2,0.2,0.2,0.2,0.2) - + DeadROCErrorThreshold = cms.vdouble(0.2,0.2,0.2,0.2,0.2,0.2), + DeadROCWarningThreshold = cms.vdouble(0.1,0.1,0.1,0.1,0.1,0.1) ) SiPixelPhase1SummaryCosmics = DQMEDHarvester("SiPixelPhase1Summary", @@ -92,7 +93,8 @@ MapHist = cms.string("mean_charge") ) ), - DeadROCErrorThreshold = cms.vdouble(0.2,0.2,0.2,0.2,0.2,0.2) + DeadROCErrorThreshold = cms.vdouble(0.2,0.2,0.2,0.2,0.2,0.2), + DeadROCWarningThreshold = cms.vdouble(0.1,0.1,0.1,0.1,0.1,0.1) ) from DQMServices.Core.DQMQualityTester import DQMQualityTester diff --git a/DQM/SiPixelPhase1Summary/src/SiPixelPhase1Summary.cc b/DQM/SiPixelPhase1Summary/src/SiPixelPhase1Summary.cc index 505dfc36b75d9..0f0176b8e3fa6 100644 --- a/DQM/SiPixelPhase1Summary/src/SiPixelPhase1Summary.cc +++ b/DQM/SiPixelPhase1Summary/src/SiPixelPhase1Summary.cc @@ -60,6 +60,7 @@ SiPixelPhase1Summary::SiPixelPhase1Summary(const edm::ParameterSet& iConfig) summaryPlotName_[mapPSet.getParameter("MapName")] = mapPSet.getParameter("MapHist"); } deadRocThresholds_ = conf_.getParameter >("DeadROCErrorThreshold"); + deadRocWarnThresholds_ = conf_.getParameter >("DeadROCWarningThreshold"); } SiPixelPhase1Summary::~SiPixelPhase1Summary() { @@ -282,6 +283,8 @@ void SiPixelPhase1Summary::fillSummaries(DQMStore::IBooker& iBooker, DQMStore::I nROCs = tempProfile->GetBinContent(i + 1); } deadROCSummary->setBinContent(xBin, yBin, nROCs / nRocsPerTrend[i]); + deadROCSummary->setBinContent(2, 3, -1); + deadROCSummary->setBinContent(2, 4, -1); } //Sum of non-negative bins for the reportSummary @@ -325,20 +328,25 @@ void SiPixelPhase1Summary::fillSummaries(DQMStore::IBooker& iBooker, DQMStore::I } for (int j = 0; j < 4; j++) { // !??!?!? yAxisLabels_.size() ?!?!?! //Ignore the bins without detectors in them - if (i == 1 && j > 1) - continue; - summaryMap_["Grand"]->setBinContent( - i + 1, - j + 1, - 1); // This resets the map to be good. We only then set it to 0 if there has been a problem in one of the other summaries. - if (deadROCSummary->getBinContent(i + 1, j + 1) > deadRocThresholds_[i * 4 + j]) - summaryMap_["Grand"]->setBinContent(i + 1, j + 1, 0); - sumOfNonNegBins += summaryMap_["Grand"]->getBinContent(i + 1, j + 1); + if (i == 1 && j > 1) { + summaryMap_["Grand"]->setBinContent(i + 1, j + 1, -1); + } else { + if (deadROCSummary->getBinContent(i + 1, j + 1) < deadRocWarnThresholds_[i * 4 + j]) + summaryMap_["Grand"]->setBinContent(i + 1, j + 1, 1); + + else if (deadROCSummary->getBinContent(i + 1, j + 1) > deadRocWarnThresholds_[i * 4 + j] && + deadROCSummary->getBinContent(i + 1, j + 1) < deadRocThresholds_[i * 4 + j]) + summaryMap_["Grand"]->setBinContent(i + 1, j + 1, 0.8); + + else + summaryMap_["Grand"]->setBinContent(i + 1, j + 1, 0); + + sumOfNonNegBins += summaryMap_["Grand"]->getBinContent(i + 1, j + 1); + } } } } } - //------------------------------------------------------------------ // Fill the trend plots //------------------------------------------------------------------ diff --git a/DQM/SiStripMonitorClient/python/SiStripSourceConfigP5_cff.py b/DQM/SiStripMonitorClient/python/SiStripSourceConfigP5_cff.py index ab39bcf8e9c8d..578690d270f7a 100644 --- a/DQM/SiStripMonitorClient/python/SiStripSourceConfigP5_cff.py +++ b/DQM/SiStripMonitorClient/python/SiStripSourceConfigP5_cff.py @@ -93,19 +93,19 @@ import DQM.SiStripMonitorTrack.SiStripMonitorTrack_cfi SiStripMonitorTrack_cosmicTk = DQM.SiStripMonitorTrack.SiStripMonitorTrack_cfi.SiStripMonitorTrack.clone( TrackProducer = 'cosmictrackfinderP5', - Mod_On = False + Mod_On = False, ) # Clone for CKF Tracks SiStripMonitorTrack_ckf = DQM.SiStripMonitorTrack.SiStripMonitorTrack_cfi.SiStripMonitorTrack.clone( TrackProducer = 'ctfWithMaterialTracksP5', - Mod_On = False + Mod_On = False, ) # Clone fir Road Search Tracks # SiStripMonitorTrack_rs = DQM.SiStripMonitorTrack.SiStripMonitorTrack_cfi.SiStripMonitorTrack.clone( # TrackProducer = 'rsWithMaterialTracksP5', -# Mod_On = True +# Mod_On = True, # ) # Clone for General Tracks (for Collision) @@ -126,7 +126,8 @@ # MonitorTrackResiduals_cosmicTk = DQM.TrackerMonitorTrack.MonitorTrackResiduals_cfi.MonitorTrackResiduals.clone( # Tracks = 'cosmictrackfinderP5', # trajectoryInput = 'cosmictrackfinderP5', -# Mod_On = False +# Mod_On = False, +# VertexCut = False # ) # Clone for CKF Tracks @@ -135,6 +136,7 @@ # Tracks = 'ctfWithMaterialTracksP5', # trajectoryInput = 'ctfWithMaterialTracksP5', # Mod_On = False +# VertexCut = False # ) # Clone for Road Search Tracks @@ -142,7 +144,8 @@ # MonitorTrackResiduals_rs = DQM.TrackerMonitorTrack.MonitorTrackResiduals_cfi.MonitorTrackResiduals.clone( # Tracks = 'rsWithMaterialTracksP5', # trajectoryInput = 'rsWithMaterialTracksP5', -# Mod_On = False +# Mod_On = False, +# VertexCut = False # ) # Clone for General Track (for Collision data) diff --git a/DQM/SiStripMonitorClient/python/SiStripSourceConfigTier0_Cosmic_cff.py b/DQM/SiStripMonitorClient/python/SiStripSourceConfigTier0_Cosmic_cff.py index efa0cf94a924b..d2cc69c0ee50d 100644 --- a/DQM/SiStripMonitorClient/python/SiStripSourceConfigTier0_Cosmic_cff.py +++ b/DQM/SiStripMonitorClient/python/SiStripSourceConfigTier0_Cosmic_cff.py @@ -87,19 +87,22 @@ MonitorTrackResiduals_cosmicTk = MonitorTrackResiduals.clone( trajectoryInput = 'cosmictrackfinderP5', Tracks = 'cosmictrackfinderP5', - Mod_On = False + Mod_On = False, + VertexCut = False ) # Clone for CKF Tracks MonitorTrackResiduals_ckf = MonitorTrackResiduals.clone( trajectoryInput = 'ctfWithMaterialTracksP5', Tracks = 'ctfWithMaterialTracksP5', - Mod_On = False + Mod_On = False, + VertexCut = False ) # Clone for Road Search Tracks # MonitorTrackResiduals_rs = MonitorTrackResiduals.clone( # trajectoryInput = 'rsWithMaterialTracksP5', # Tracks = 'rsWithMaterialTracksP5', -# Mod_On = False +# Mod_On = False, +# VertexCut = False # ) # DQM Services diff --git a/DQM/SiStripMonitorClient/scripts/submitDQMOfflineCAF.py b/DQM/SiStripMonitorClient/scripts/submitDQMOfflineCAF.py index 1565665fb07fb..c7b138308ff55 100755 --- a/DQM/SiStripMonitorClient/scripts/submitDQMOfflineCAF.py +++ b/DQM/SiStripMonitorClient/scripts/submitDQMOfflineCAF.py @@ -14,7 +14,7 @@ import sys import os import os.path -import commands +import subprocess import shutil import string import math @@ -459,7 +459,7 @@ def Func_MagConfig(float_magFieldMeasured): # on use CRAB if Bool_CRAB: - str_buffer = commands.getoutput('which crab') + str_buffer = subprocess.getoutput('which crab') if str_buffer.find('which: no crab in') >= 0: str_suffixShell = 'csh' if not os.getenv('SHELL')[-3:] == str_suffixShell: diff --git a/DQM/TrackerCommon/plugins/BuildFile.xml b/DQM/TrackerCommon/plugins/BuildFile.xml index 04a13b10beecc..3108aeeedd474 100644 --- a/DQM/TrackerCommon/plugins/BuildFile.xml +++ b/DQM/TrackerCommon/plugins/BuildFile.xml @@ -1,4 +1,5 @@ + diff --git a/DQM/TrackerCommon/plugins/DetectorStateFilter.cc b/DQM/TrackerCommon/plugins/DetectorStateFilter.cc index 77ae01a2088e8..04d0e6431243a 100644 --- a/DQM/TrackerCommon/plugins/DetectorStateFilter.cc +++ b/DQM/TrackerCommon/plugins/DetectorStateFilter.cc @@ -1,72 +1,187 @@ -#include "DQM/TrackerCommon/plugins/DetectorStateFilter.h" #include "DataFormats/Common/interface/Handle.h" -#include "FWCore/Framework/interface/Event.h" -#include "FWCore/MessageLogger/interface/MessageLogger.h" - #include "DataFormats/FEDRawData/interface/FEDNumbering.h" #include "DataFormats/FEDRawData/interface/FEDRawData.h" #include "DataFormats/FEDRawData/interface/FEDRawDataCollection.h" +#include "DataFormats/Scalers/interface/DcsStatus.h" +#include "DataFormats/OnlineMetaData/interface/DCSRecord.h" +#include "FWCore/Framework/interface/Event.h" +#include "FWCore/Framework/interface/stream/EDFilter.h" +#include "FWCore/MessageLogger/interface/MessageLogger.h" +#include "FWCore/ParameterSet/interface/ParameterSet.h" +#include "FWCore/ParameterSet/interface/ConfigurationDescriptions.h" +#include "FWCore/ParameterSet/interface/ParameterSetDescription.h" + +#include // for std::is_same + +class DetectorStateFilter : public edm::stream::EDFilter<> { +public: + DetectorStateFilter(const edm::ParameterSet&); + ~DetectorStateFilter() override; + + static void fillDescriptions(edm::ConfigurationDescriptions& descriptions); + +private: + bool filter(edm::Event&, edm::EventSetup const&) override; + + const bool verbose_; + uint64_t nEvents_, nSelectedEvents_; + bool detectorOn_; + const std::string detectorType_; + const edm::EDGetTokenT dcsStatusLabel_; + const edm::EDGetTokenT dcsRecordToken_; + + template + bool checkSubdet(const T& DCS, const int index); + template + bool checkDCS(const T& DCS); + + bool checkDCSStatus(const DcsStatusCollection& dcsStatus); + bool checkDCSRecord(const DCSRecord& dcsRecord); +}; + +// +// auxilliary enum +// +namespace DetStateFilter { + enum parts { BPix = 0, FPix = 1, TIBTID = 2, TOB = 3, TECp = 4, TECm = 5, Invalid }; +} + // // -- Constructor // -DetectorStateFilter::DetectorStateFilter(const edm::ParameterSet &pset) +DetectorStateFilter::DetectorStateFilter(const edm::ParameterSet& pset) : verbose_(pset.getUntrackedParameter("DebugOn", false)), detectorType_(pset.getUntrackedParameter("DetectorType", "sistrip")), dcsStatusLabel_(consumes( - pset.getUntrackedParameter("DcsStatusLabel", edm::InputTag("scalersRawToDigi")))) { + pset.getUntrackedParameter("DcsStatusLabel", edm::InputTag("scalersRawToDigi")))), + dcsRecordToken_(consumes( + pset.getUntrackedParameter("DCSRecordLabel", edm::InputTag("onlineMetaDataDigis")))) { nEvents_ = 0; nSelectedEvents_ = 0; detectorOn_ = false; } + // // -- Destructor // -DetectorStateFilter::~DetectorStateFilter() {} +DetectorStateFilter::~DetectorStateFilter() = default; + +template +//*********************************************************************// +bool DetectorStateFilter::checkSubdet(const T& DCS, const int index) +//*********************************************************************// +{ + std::vector dcsStatusParts = { + DcsStatus::BPIX, DcsStatus::FPIX, DcsStatus::TIBTID, DcsStatus::TOB, DcsStatus::TECp, DcsStatus::TECm}; -bool DetectorStateFilter::filter(edm::Event &evt, edm::EventSetup const &es) { + std::vector dcsRecordParts = {DCSRecord::Partition::BPIX, + DCSRecord::Partition::FPIX, + DCSRecord::Partition::TIBTID, + DCSRecord::Partition::TOB, + DCSRecord::Partition::TECp, + DCSRecord::Partition::TECm}; + + if constexpr (std::is_same_v) { + return (DCS)[0].ready(dcsStatusParts[index]); + } else if constexpr (std::is_same_v) { + return DCS.highVoltageReady(dcsRecordParts[index]); + } else { + edm::LogError("DetectorStatusFilter") + << __FILE__ << " " << __LINE__ << " passed a wrong object type, cannot deduce DCS information.\n" + << " returning true" << std::endl; + return true; + } +} + +template +bool +//*********************************************************************// +DetectorStateFilter::checkDCS(const T& DCS) +//*********************************************************************// +{ + bool accepted = false; + if (detectorType_ == "pixel") { + if (checkSubdet(DCS, DetStateFilter::BPix) && checkSubdet(DCS, DetStateFilter::FPix)) { + accepted = true; + nSelectedEvents_++; + } else { + accepted = false; + } + if (verbose_) { + edm::LogInfo("DetectorStatusFilter") + << " Total Events " << nEvents_ << " Selected Events " << nSelectedEvents_ << " DCS States : " + << " BPix " << checkSubdet(DCS, DetStateFilter::BPix) << " FPix " << checkSubdet(DCS, DetStateFilter::FPix) + << " Detector State " << accepted << std::endl; + } + } else if (detectorType_ == "sistrip") { + if (checkSubdet(DCS, DetStateFilter::TIBTID) && checkSubdet(DCS, DetStateFilter::TOB) && + checkSubdet(DCS, DetStateFilter::TECp) && checkSubdet(DCS, DetStateFilter::TECm)) { + accepted = true; + nSelectedEvents_++; + } else { + accepted = false; + } + if (verbose_) { + edm::LogInfo("DetectorStatusFilter") + << " Total Events " << nEvents_ << " Selected Events " << nSelectedEvents_ << " DCS States : " + << " TEC- " << checkSubdet(DCS, DetStateFilter::TECm) << " TEC+ " << checkSubdet(DCS, DetStateFilter::TECp) + << " TIB/TID " << checkSubdet(DCS, DetStateFilter::TIBTID) << " TOB " << checkSubdet(DCS, DetStateFilter::TOB) + << " Detector States " << accepted << std::endl; + } + } else { + throw cms::Exception("Wrong Configuration") + << "Stated DetectorType '" << detectorType_ + << "' is neither 'pixel' or 'sistrip', please check your configuration!"; + } + return accepted; +} + +//*********************************************************************// +bool DetectorStateFilter::filter(edm::Event& evt, edm::EventSetup const& es) +//*********************************************************************// +{ nEvents_++; // Check Detector state Only for Real Data and return true for MC if (evt.isRealData()) { edm::Handle dcsStatus; evt.getByToken(dcsStatusLabel_, dcsStatus); - if (dcsStatus.isValid()) { - if (detectorType_ == "pixel" && !dcsStatus->empty()) { - if ((*dcsStatus)[0].ready(DcsStatus::BPIX) && (*dcsStatus)[0].ready(DcsStatus::FPIX)) { - detectorOn_ = true; - nSelectedEvents_++; - } else - detectorOn_ = false; - //if (verbose_) - edm::LogInfo("DetectorStatusFilter") - << " Total Events " << nEvents_ << " Selected Events " << nSelectedEvents_ << " DCS States : " - << " BPix " << (*dcsStatus)[0].ready(DcsStatus::BPIX) << " FPix " << (*dcsStatus)[0].ready(DcsStatus::FPIX) - << " Detector State " << detectorOn_ << std::endl; - } else if (detectorType_ == "sistrip" && !dcsStatus->empty()) { - if ((*dcsStatus)[0].ready(DcsStatus::TIBTID) && (*dcsStatus)[0].ready(DcsStatus::TOB) && - (*dcsStatus)[0].ready(DcsStatus::TECp) && (*dcsStatus)[0].ready(DcsStatus::TECm)) { - detectorOn_ = true; - nSelectedEvents_++; - } else - detectorOn_ = false; - //if (verbose_) - edm::LogInfo("DetectorStatusFilter") - << " Total Events " << nEvents_ << " Selected Events " << nSelectedEvents_ << " DCS States : " - << " TEC- " << (*dcsStatus)[0].ready(DcsStatus::TECm) << " TEC+ " << (*dcsStatus)[0].ready(DcsStatus::TECp) - << " TIB/TID " << (*dcsStatus)[0].ready(DcsStatus::TIBTID) << " TOB " - << (*dcsStatus)[0].ready(DcsStatus::TOB) << " Detector States " << detectorOn_ << std::endl; - } + edm::Handle dcsRecord; + evt.getByToken(dcsRecordToken_, dcsRecord); + + if (dcsStatus.isValid() && !dcsStatus->empty()) { + // if the old style DCS status is valid (Run1 + Run2) + detectorOn_ = checkDCS(*dcsStatus); + } else if (dcsRecord.isValid()) { + // in case of real data check for DCSRecord content (Run >=3) + detectorOn_ = checkDCS(*dcsRecord); } else { - edm::LogError("DetectorStatusFilter") << "ERROR: DcsStatusCollection not found !"; + edm::LogError("DetectorStatusFilter") + << "Error! can't get the products, neither DCSRecord, nor scalersRawToDigi: accept in any case!"; + detectorOn_ = true; } } else { detectorOn_ = true; nSelectedEvents_++; - //if (verbose_) - edm::LogInfo("DetectorStatusFilter") << "Total MC Events " << nEvents_ << " Selected Events " << nSelectedEvents_ - << " Detector States " << detectorOn_ << std::endl; + if (verbose_) { + edm::LogInfo("DetectorStatusFilter") << "Total MC Events " << nEvents_ << " Selected Events " << nSelectedEvents_ + << " Detector States " << detectorOn_ << std::endl; + } } return detectorOn_; } +// ------------ method fills 'descriptions' with the allowed parameters for the module ------------ +void DetectorStateFilter::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { + edm::ParameterSetDescription desc; + desc.setComment("filters on the HV status of the Tracker (either pixels or strips)"); + desc.addUntracked("DebugOn", false)->setComment("activates debugging"); + desc.addUntracked("DetectorType", "sistrip")->setComment("either strips or pixels"); + desc.addUntracked("DcsStatusLabel", edm::InputTag("scalersRawToDigi")) + ->setComment("event data for DCS (Run2)"); + desc.addUntracked("DCSRecordLabel", edm::InputTag("onlineMetaDataDigis")) + ->setComment("event data for DCS (Run3)"); + descriptions.add("_detectorStateFilter", desc); +} + #include "FWCore/Framework/interface/MakerMacros.h" DEFINE_FWK_MODULE(DetectorStateFilter); diff --git a/DQM/TrackerCommon/plugins/DetectorStateFilter.h b/DQM/TrackerCommon/plugins/DetectorStateFilter.h deleted file mode 100644 index 2a7827cea245b..0000000000000 --- a/DQM/TrackerCommon/plugins/DetectorStateFilter.h +++ /dev/null @@ -1,23 +0,0 @@ -#ifndef DetectorStateFilter_H -#define DetectorStateFilter_H - -#include "DataFormats/Scalers/interface/DcsStatus.h" -#include "FWCore/Framework/interface/stream/EDFilter.h" -#include "FWCore/ParameterSet/interface/ParameterSet.h" - -class DetectorStateFilter : public edm::stream::EDFilter<> { -public: - DetectorStateFilter(const edm::ParameterSet &); - ~DetectorStateFilter() override; - -private: - bool filter(edm::Event &, edm::EventSetup const &) override; - - const bool verbose_; - uint64_t nEvents_, nSelectedEvents_; - bool detectorOn_; - const std::string detectorType_; - const edm::EDGetTokenT dcsStatusLabel_; -}; - -#endif diff --git a/DQM/TrackerCommon/plugins/SimpleEventFilter.cc b/DQM/TrackerCommon/plugins/SimpleEventFilter.cc index 010ceed1e044a..763fdddbc8a5e 100644 --- a/DQM/TrackerCommon/plugins/SimpleEventFilter.cc +++ b/DQM/TrackerCommon/plugins/SimpleEventFilter.cc @@ -1,5 +1,23 @@ -#include "DQM/TrackerCommon/plugins/SimpleEventFilter.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" +#include "FWCore/Framework/interface/stream/EDFilter.h" +#include "FWCore/ParameterSet/interface/ParameterSet.h" +#include "FWCore/ParameterSet/interface/ConfigurationDescriptions.h" +#include "FWCore/ParameterSet/interface/ParameterSetDescription.h" + +class SimpleEventFilter : public edm::stream::EDFilter<> { +public: + SimpleEventFilter(const edm::ParameterSet &); + ~SimpleEventFilter() override; + + static void fillDescriptions(edm::ConfigurationDescriptions &descriptions); + +private: + bool filter(edm::Event &, edm::EventSetup const &) override; + int nEvent_; + int nInterval_; + bool verbose_; +}; + // // -- Constructor // @@ -8,10 +26,11 @@ SimpleEventFilter::SimpleEventFilter(const edm::ParameterSet &pset) { verbose_ = pset.getUntrackedParameter("DebugOn", false); nEvent_ = 0; } + // // -- Destructor // -SimpleEventFilter::~SimpleEventFilter() {} +SimpleEventFilter::~SimpleEventFilter() = default; bool SimpleEventFilter::filter(edm::Event &, edm::EventSetup const &) { nEvent_++; @@ -24,5 +43,14 @@ bool SimpleEventFilter::filter(edm::Event &, edm::EventSetup const &) { return ret; } +// ------------ method fills 'descriptions' with the allowed parameters for the module ------------ +void SimpleEventFilter::fillDescriptions(edm::ConfigurationDescriptions &descriptions) { + edm::ParameterSetDescription desc; + desc.setComment("filters one event every N"); + desc.addUntracked("DebugOn", false)->setComment("activates debugging"); + desc.addUntracked("EventsToSkip", 10)->setComment("events to skip"); + descriptions.add("_simpleEventFilter", desc); +} + #include "FWCore/Framework/interface/MakerMacros.h" DEFINE_FWK_MODULE(SimpleEventFilter); diff --git a/DQM/TrackerCommon/plugins/SimpleEventFilter.h b/DQM/TrackerCommon/plugins/SimpleEventFilter.h deleted file mode 100644 index 44694aebfdef0..0000000000000 --- a/DQM/TrackerCommon/plugins/SimpleEventFilter.h +++ /dev/null @@ -1,19 +0,0 @@ -#ifndef SimpleEventFilter_H -#define SimpleEventFilter_H - -#include "FWCore/Framework/interface/stream/EDFilter.h" -#include "FWCore/ParameterSet/interface/ParameterSet.h" - -class SimpleEventFilter : public edm::stream::EDFilter<> { -public: - SimpleEventFilter(const edm::ParameterSet &); - ~SimpleEventFilter() override; - -private: - bool filter(edm::Event &, edm::EventSetup const &) override; - int nEvent_; - int nInterval_; - bool verbose_; -}; - -#endif diff --git a/DQM/TrackerCommon/python/TrackerFilterConfiguration_cfi.py b/DQM/TrackerCommon/python/TrackerFilterConfiguration_cfi.py index 2b0f43a8da7c0..29090e8c6ca17 100644 --- a/DQM/TrackerCommon/python/TrackerFilterConfiguration_cfi.py +++ b/DQM/TrackerCommon/python/TrackerFilterConfiguration_cfi.py @@ -2,16 +2,10 @@ #----------------------------------- # Detector State Filter #----------------------------------- -detectorStateFilter = cms.EDFilter("DetectorStateFilter", - DetectorType = cms.untracked.string('sistrip'), - DebugOn = cms.untracked.bool(False), - DcsStatusLabel = cms.untracked.InputTag('scalersRawToDigi') -) +import DQM.TrackerCommon._detectorStateFilter_cfi as _dcs +detectorStateFilter = _dcs._detectorStateFilter.clone() #----------------------------------- # Simple Event Filter #----------------------------------- -simpleEventFilter = cms.EDFilter("SimpleEventFilter", - EventsToSkip = cms.untracked.int32(10), - DebugOn = cms.untracked.bool(True) - -) +import DQM.TrackerCommon._simpleEventFilter_cfi as _sef +simpleEventFilter = _sef._simpleEventFilter.clone() diff --git a/DQM/TrackerCommon/test/BuildFile.xml b/DQM/TrackerCommon/test/BuildFile.xml new file mode 100644 index 0000000000000..9d5be9741b38c --- /dev/null +++ b/DQM/TrackerCommon/test/BuildFile.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/DQM/TrackerCommon/test/test_DetectorStateFilter.cpp b/DQM/TrackerCommon/test/test_DetectorStateFilter.cpp new file mode 100644 index 0000000000000..2f0e0c40064da --- /dev/null +++ b/DQM/TrackerCommon/test/test_DetectorStateFilter.cpp @@ -0,0 +1,2 @@ +#include "FWCore/Utilities/interface/TestHelper.h" +RUNTEST() diff --git a/DQM/TrackerCommon/test/test_DetectorStateFilter.sh b/DQM/TrackerCommon/test/test_DetectorStateFilter.sh new file mode 100755 index 0000000000000..2aa6a205d7532 --- /dev/null +++ b/DQM/TrackerCommon/test/test_DetectorStateFilter.sh @@ -0,0 +1,55 @@ +#!/bin/sh + +function die { echo $1: status $2 ; exit $2; } + +function countEvents() { + local FILE="$1" + NUMBER=$(echo `edmFileUtil $FILE | grep events` | awk '{print $6}') + echo $NUMBER +} + +echo "TESTING detectorStateFilter ..." + +# Take as input file an express FEVT file from 2021 commissioning, Run 343498 +# https://cmsoms.cern.ch/cms/runs/report/fullscreen/4637?cms_run=343498&cms_run_sequence=GLOBAL-RUN +# It has Pixels and Strips HV ON +# Also used to feed RelVal Matrix wfs 138.1, 138.2 + +### LS2 - MWGR 2021 - CSC, DAQ, DCS, DQM, DT, ECAL, GEM, HCAL, L1SCOUT, PIXEL, RPC, TCDS, TRACKER, TRG ### +#INPUTFILE="/store/express/Commissioning2021/ExpressCosmics/FEVT/Express-v1/000/343/498/00000/004179ae-ac29-438a-bd2d-ea98139c21a7.root" + +# Take as input file an express FEVT file from 2021 commissioning, Run 338714 +# https://cmsoms.cern.ch/cms/runs/report/fullscreen/4637?cms_run=338714&cms_run_sequence=GLOBAL-RUN +# It has Pixels HV OFF but Strips HV ON +# It was used to feed RelVal Matrix wfs 138.1, 138.2 + + ### LS2 - MWGR#5 2020 - CSC, DAQ, DCS, DQM, DT, ECAL, GEM, HCAL, RPC, TCDS, TRACKER, TRG ### +INPUTFILE="/store/express/Commissioning2020/ExpressCosmics/FEVT/Express-v1/000/338/714/00000/515CD930-9BBA-1945-87C3-AD555E25F301.root" + +# test Pixel +printf "TESTING Pixels ...\n\n" +cmsRun ${LOCAL_TEST_DIR}/test_DetectorStateFilter_cfg.py maxEvents=10 isStrip=False inputFiles=$INPUTFILE outputFile=outPixels.root || die "Failure filtering on pixels" $? + +# test Strips +printf "TESTING Strips ...\n\n" +cmsRun ${LOCAL_TEST_DIR}/test_DetectorStateFilter_cfg.py maxEvents=10 isStrip=True inputFiles=$INPUTFILE outputFile=outStrips.root || die "Failure filtering on strips" $? + +# count events +pixelCounts=`countEvents outPixels_numEvent10.root` +stripCounts=`countEvents outStrips_numEvent10.root` + +if [[ $pixelCounts -eq 0 ]] +then + echo "The number of events in the pixel filter file matches expectations ($pixelCounts)." +else + echo "WARNING!!! The number of events in the pixel filter file ($pixelCounts) does NOT match expectations (0)." + exit 1 +fi + +if [[ $stripCounts -eq 10 ]] +then + echo "The number of events in the strip filter file matches expectations ($stripCounts)." +else + echo "WARNING!!! The number of events in the strip filter file ($stripCounts) does NOT match expectations (10)." + exit 1 +fi diff --git a/DQM/TrackerCommon/test/test_DetectorStateFilter_cfg.py b/DQM/TrackerCommon/test/test_DetectorStateFilter_cfg.py new file mode 100644 index 0000000000000..9476c52dc49c1 --- /dev/null +++ b/DQM/TrackerCommon/test/test_DetectorStateFilter_cfg.py @@ -0,0 +1,86 @@ +import FWCore.ParameterSet.Config as cms +import FWCore.ParameterSet.VarParsing as VarParsing + +from Configuration.Eras.Era_Run3_cff import Run3 + +process = cms.Process('reRECO',Run3) + +options = VarParsing.VarParsing('analysis') +options.register('globalTag', + "auto:run3_data_prompt", # default value + VarParsing.VarParsing.multiplicity.singleton, # singleton or list + VarParsing.VarParsing.varType.string, # string, int, or float + "input file name") +options.register('isStrip', + True, # default value + VarParsing.VarParsing.multiplicity.singleton, # singleton or list + VarParsing.VarParsing.varType.bool, # string, int, or float + "true filters on Strips, false filters on Pixels") +options.parseArguments() + +# import of standard configurations +process.load('Configuration.StandardSequences.Services_cff') + +process.load('FWCore.MessageService.MessageLogger_cfi') +process.MessageLogger.cerr.enable = False +process.MessageLogger.DetectorStatusFilter=dict() +process.MessageLogger.cout = cms.untracked.PSet( + enable = cms.untracked.bool(True), + threshold = cms.untracked.string("INFO"), + default = cms.untracked.PSet(limit = cms.untracked.int32(0)), + FwkReport = cms.untracked.PSet(limit = cms.untracked.int32(-1), + reportEvery = cms.untracked.int32(1) + ), + DetectorStatusFilter = cms.untracked.PSet( limit = cms.untracked.int32(-1)), + enableStatistics = cms.untracked.bool(True) + ) + +process.load('Configuration.StandardSequences.GeometryRecoDB_cff') +process.load('Configuration.StandardSequences.MagneticField_cff') +process.load('Configuration.StandardSequences.RawToDigi_Data_cff') +process.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_cff') + +process.maxEvents = cms.untracked.PSet( + input = cms.untracked.int32(options.maxEvents), + output = cms.optional.untracked.allowed(cms.int32,cms.PSet) +) + +# Input source +process.source = cms.Source("PoolSource", + #fileNames = cms.untracked.vstring("/store/express/Commissioning2021/ExpressCosmics/FEVT/Express-v1/000/343/498/00000/004179ae-ac29-438a-bd2d-ea98139c21a7.root") # default value + fileNames = cms.untracked.vstring(options.inputFiles) + ) +# Other statements +from Configuration.AlCa.GlobalTag import GlobalTag +process.GlobalTag = GlobalTag(process.GlobalTag, options.globalTag, '') + +# Path and EndPath definitions +process.raw2digi_step = cms.Path(process.RawToDigi) + +process.OUT = cms.OutputModule("PoolOutputModule", + outputCommands = cms.untracked.vstring('drop *', + 'keep *_onlineMetaDataDigis_*_*', + 'keep *_scalersRawToDigi_*_*'), + SelectEvents = cms.untracked.PSet(SelectEvents = cms.vstring('analysis_step')), + fileName = cms.untracked.string(options.outputFile) + ) + +# the module to be tested +from DQM.TrackerCommon.TrackerFilterConfiguration_cfi import detectorStateFilter +process.SiPixelFilter = detectorStateFilter.clone(DetectorType = 'pixel', + DebugOn = True) + +process.SiStripFilter = detectorStateFilter.clone(DetectorType = 'sistrip', + DebugOn = True) + +#process.analysis_step = cms.Path(process.detectorStateFilter) +if(options.isStrip) : + process.analysis_step = cms.Path(process.SiStripFilter) +else: + process.analysis_step = cms.Path(process.SiPixelFilter) + +# end path +process.printEventNumber = cms.OutputModule("AsciiOutputModule") +process.this_is_the_end = cms.EndPath(process.OUT*process.printEventNumber) + +process.schedule = cms.Schedule(process.raw2digi_step,process.analysis_step,process.this_is_the_end) diff --git a/DQM/TrackerMonitorTrack/interface/MonitorTrackResiduals.h b/DQM/TrackerMonitorTrack/interface/MonitorTrackResiduals.h index ee90830338ecd..efb81679ca3f6 100644 --- a/DQM/TrackerMonitorTrack/interface/MonitorTrackResiduals.h +++ b/DQM/TrackerMonitorTrack/interface/MonitorTrackResiduals.h @@ -85,6 +85,7 @@ class MonitorTrackResidualsBase : public DQMEDAnalyzer { unsigned long long m_cacheID_; bool ModOn; + bool applyVertexCut_; GenericTriggerEventFlag *genTriggerEventFlag_; TrackerValidationVariables avalidator_; diff --git a/DQM/TrackerMonitorTrack/python/MonitorTrackResiduals_cfi.py b/DQM/TrackerMonitorTrack/python/MonitorTrackResiduals_cfi.py index 8d5d487b36fd5..4fbc571a443bb 100644 --- a/DQM/TrackerMonitorTrack/python/MonitorTrackResiduals_cfi.py +++ b/DQM/TrackerMonitorTrack/python/MonitorTrackResiduals_cfi.py @@ -6,6 +6,7 @@ OutputMEsInRootFile = cms.bool(False), # should histogramms on module level be booked and filled? Mod_On = cms.bool(True), + VertexCut = cms.untracked.bool(True), OutputFileName = cms.string('test_monitortracks.root'), genericTriggerEventPSet = cms.PSet(), # bining and range for absolute and normalized residual histogramms diff --git a/DQM/TrackerMonitorTrack/python/SiPixelMonitorTrackResiduals_cfi.py b/DQM/TrackerMonitorTrack/python/SiPixelMonitorTrackResiduals_cfi.py index 806c8d5ef38b7..d3e6675697920 100644 --- a/DQM/TrackerMonitorTrack/python/SiPixelMonitorTrackResiduals_cfi.py +++ b/DQM/TrackerMonitorTrack/python/SiPixelMonitorTrackResiduals_cfi.py @@ -6,6 +6,7 @@ OutputMEsInRootFile = cms.bool(False), # should histogramms on module level be booked and filled? Mod_On = cms.bool(False), + VertexCut = cms.untracked.bool(True), OutputFileName = cms.string('test_monitortracks.root'), genericTriggerEventPSet = cms.PSet(), # bining and range for absolute and normalized residual histogramms diff --git a/DQM/TrackerMonitorTrack/src/MonitorTrackResiduals.cc b/DQM/TrackerMonitorTrack/src/MonitorTrackResiduals.cc index 74b6e7c62fa92..bb58285028f83 100644 --- a/DQM/TrackerMonitorTrack/src/MonitorTrackResiduals.cc +++ b/DQM/TrackerMonitorTrack/src/MonitorTrackResiduals.cc @@ -22,6 +22,7 @@ MonitorTrackResidualsBase::MonitorTrackResidualsBase(const edm:: genTriggerEventFlag_(new GenericTriggerEventFlag( iConfig.getParameter("genericTriggerEventPSet"), consumesCollector(), *this)), avalidator_(iConfig, consumesCollector()) { + applyVertexCut_ = conf_.getUntrackedParameter("VertexCut", true); ModOn = conf_.getParameter("Mod_On"); offlinePrimaryVerticesToken_ = consumes(std::string("offlinePrimaryVertices")); } @@ -235,10 +236,11 @@ void MonitorTrackResidualsBase::analyze(const edm::Event &iEvent return; edm::Handle vertices; - iEvent.getByToken(offlinePrimaryVerticesToken_, vertices); - if (!vertices.isValid() || vertices->empty()) - return; - const auto primaryVertex = vertices->at(0); + if (applyVertexCut_) { + iEvent.getByToken(offlinePrimaryVerticesToken_, vertices); + if (!vertices.isValid() || vertices->empty()) + return; + } // Retrieve tracker topology from geometry const TrackerTopology *const tTopo = &iSetup.getData(trackerTopologyEventToken_); @@ -248,7 +250,8 @@ void MonitorTrackResidualsBase::analyze(const edm::Event &iEvent iSetup, // tell the validator to only look at good tracks [&](const reco::Track &track) -> bool { - return track.pt() > 0.75 && abs(track.dxy(primaryVertex.position())) < 5 * track.dxyError(); + return (!applyVertexCut_ || + (track.pt() > 0.75 && abs(track.dxy(vertices->at(0).position())) < 5 * track.dxyError())); }, vtracks); diff --git a/DQM/TrackingMonitor/src/TrackingRecoMaterialAnalyser.cc b/DQM/TrackingMonitor/src/TrackingRecoMaterialAnalyser.cc index 7b9cfdef9bd8c..c87e8fa5d6a7e 100644 --- a/DQM/TrackingMonitor/src/TrackingRecoMaterialAnalyser.cc +++ b/DQM/TrackingMonitor/src/TrackingRecoMaterialAnalyser.cc @@ -17,7 +17,6 @@ #include "DQMServices/Core/interface/DQMEDAnalyzer.h" #include "DQMServices/Core/interface/DQMStore.h" #include "FWCore/Framework/interface/ConsumesCollector.h" -#include "FWCore/Framework/interface/EDAnalyzer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/EventSetup.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" diff --git a/DQMOffline/Configuration/python/DQMOffline_SecondStep_cff.py b/DQMOffline/Configuration/python/DQMOffline_SecondStep_cff.py index 29bf311c474d4..f16d0889589ce 100644 --- a/DQMOffline/Configuration/python/DQMOffline_SecondStep_cff.py +++ b/DQMOffline/Configuration/python/DQMOffline_SecondStep_cff.py @@ -43,6 +43,8 @@ DQMOffline_SecondStepL1T = cms.Sequence( l1TriggerDqmOfflineClient ) +DQMOffline_SecondStepL1TPhase2 = cms.Sequence( Phase2l1TriggerDqmOfflineClient ) + DQMOffline_SecondStep_PreDPG = cms.Sequence( DQMOffline_SecondStepEcal * DQMOffline_SecondStepTrackerStrip * @@ -145,6 +147,8 @@ DQMHarvestL1TMuon = cms.Sequence( l1TriggerMuonDqmOfflineClient ) +DQMHarvestL1TPhase2 = cms.Sequence( Phase2l1TriggerDqmOfflineClient ) + DQMHarvestCommon = cms.Sequence( DQMMessageLoggerClientSeq * DQMHarvestTrackerStrip * DQMHarvestTrack * diff --git a/DQMOffline/Configuration/python/DQMOffline_cff.py b/DQMOffline/Configuration/python/DQMOffline_cff.py index ac28700d4eaf4..70c2b24d6202c 100644 --- a/DQMOffline/Configuration/python/DQMOffline_cff.py +++ b/DQMOffline/Configuration/python/DQMOffline_cff.py @@ -34,6 +34,8 @@ DQMOfflineL1TMuon = cms.Sequence( l1TriggerMuonDqmOffline ) +DQMOfflineL1TPhase2 = cms.Sequence( Phase2l1TriggerDqmOffline ) + #DPGs DQMOfflineEcalOnly = cms.Sequence( ecalOnly_dqm_source_offline + diff --git a/DQMOffline/Configuration/python/autoDQM.py b/DQMOffline/Configuration/python/autoDQM.py index beffb3c556a9f..589212f117267 100644 --- a/DQMOffline/Configuration/python/autoDQM.py +++ b/DQMOffline/Configuration/python/autoDQM.py @@ -154,6 +154,10 @@ 'PostDQMOffline', 'DQMHarvestL1TMuon'], + 'L1TMonPhase2': ['DQMOfflineL1TPhase2', + 'PostDQMOffline', + 'DQMHarvestL1TPhase2'], + 'HLTMon': ['HLTMonitoring', 'PostDQMOffline', 'HLTMonitoringClient'], @@ -233,7 +237,7 @@ 'DQMNone'], } -_phase2_allowed = ['trackingOnlyDQM','outerTracker', 'trackerPhase2', 'muon','hcal','hcal2','egamma'] +_phase2_allowed = ['trackingOnlyDQM','outerTracker', 'trackerPhase2', 'muon','hcal','hcal2','egamma','L1TMonPhase2'] autoDQM['phase2'] = ['','',''] for i in [0,2]: autoDQM['phase2'][i] = '+'.join([autoDQM[m][i] for m in _phase2_allowed]) diff --git a/DQMOffline/L1Trigger/BuildFile.xml b/DQMOffline/L1Trigger/BuildFile.xml index 70b7e5b1fc211..ff1e4a7e7d51e 100644 --- a/DQMOffline/L1Trigger/BuildFile.xml +++ b/DQMOffline/L1Trigger/BuildFile.xml @@ -10,6 +10,8 @@ + + diff --git a/DQMOffline/L1Trigger/interface/L1TPhase2CorrelatorOffline.h b/DQMOffline/L1Trigger/interface/L1TPhase2CorrelatorOffline.h new file mode 100644 index 0000000000000..264749a0bb03d --- /dev/null +++ b/DQMOffline/L1Trigger/interface/L1TPhase2CorrelatorOffline.h @@ -0,0 +1,349 @@ +#ifndef DQMOFFLINE_L1TRIGGER_L1TPHASE2CORRELATOROFFLINE_H +#define DQMOFFLINE_L1TRIGGER_L1TPHASE2CORRELATOROFFLINE_H + +// DataFormats +#include "DataFormats/Common/interface/View.h" +#include "DataFormats/Candidate/interface/Candidate.h" +#include "DataFormats/HepMCCandidate/interface/GenParticle.h" +#include "DataFormats/JetReco/interface/GenJet.h" +#include "DataFormats/Math/interface/deltaR.h" +#include "DataFormats/L1TParticleFlow/interface/PFCandidate.h" + +// FWCore +#include "FWCore/Common/interface/Provenance.h" +#include "FWCore/Framework/interface/Frameworkfwd.h" +#include "FWCore/Framework/interface/EDAnalyzer.h" +#include "FWCore/Framework/interface/ESHandle.h" +#include "FWCore/Framework/interface/Event.h" +#include "FWCore/Framework/interface/LuminosityBlock.h" +#include "FWCore/Framework/interface/MakerMacros.h" +#include "FWCore/ParameterSet/interface/ParameterSet.h" +#include "FWCore/Framework/interface/ConsumesCollector.h" +#include "FWCore/Utilities/interface/InputTag.h" +#include "FWCore/ServiceRegistry/interface/Service.h" + +// DQMServices +#include "DQMServices/Core/interface/DQMOneEDAnalyzer.h" +#include "DQMServices/Core/interface/DQMStore.h" +#include "DQMOffline/L1Trigger/interface/HistDefinition.h" + +// MagneticField +#include "MagneticField/Engine/interface/MagneticField.h" +#include "MagneticField/Records/interface/IdealMagneticFieldRecord.h" + +// HLTrigger +#include "HLTrigger/HLTcore/interface/HLTConfigProvider.h" + +// L1Trigger +#include "L1Trigger/Phase2L1ParticleFlow/interface/L1TPFUtils.h" + +// CommonTools +#include "CommonTools/Utils/interface/StringCutObjectSelector.h" + +#include +#include +#include +#include +#include +#include +#include + +class L1TPhase2CorrelatorOffline : public DQMOneEDAnalyzer<> { +public: + L1TPhase2CorrelatorOffline(const edm::ParameterSet& ps); + ~L1TPhase2CorrelatorOffline() override; + + enum PlotConfig { resVsPt, resVsEta, ptDist, etaDist }; + + static const std::map PlotConfigNames; + +protected: + void dqmBeginRun(const edm::Run& run, const edm::EventSetup& iSetup) override; + void bookHistograms(DQMStore::IBooker&, edm::Run const&, edm::EventSetup const&) override; + void analyze(edm::Event const& e, edm::EventSetup const& eSetup) override; + void dqmEndRun(const edm::Run& run, const edm::EventSetup& iSetup) override; + + // Cut and Matching + +private: + void bookPhase2CorrelatorHistos(DQMStore::IBooker&); + + // other functions + double Distance(const reco::Candidate& c1, const reco::Candidate& c2); + double DistancePhi(const reco::Candidate& c1, const reco::Candidate& c2); + double calcDeltaPhi(double phi1, double phi2); + + void computeResponseResolution(); + + void medianResponseCorrResolution(MonitorElement* in2D, MonitorElement* response, MonitorElement* resolution); + void medianResponse(MonitorElement* in2D, MonitorElement* response); + + struct SimpleObject { + float pt, eta, phi; + SimpleObject(float apt, float aneta, float aphi) : pt(apt), eta(aneta), phi(aphi) {} + bool operator<(const SimpleObject& other) const { return eta < other.eta; } + bool operator<(const float& other) const { return eta < other; } + }; + class MultiCollection { + public: + MultiCollection(const edm::ParameterSet& iConfig, const std::string& name, edm::ConsumesCollector&& coll) + : name_(name), prop_(false), sel_("") { + if (name.find("Ecal") != std::string::npos) + prop_ = true; + else if (name.find("Hcal") != std::string::npos) + prop_ = true; + else if (name.find("Calo") != std::string::npos) + prop_ = true; + const std::vector& tags = iConfig.getParameter>(name); + for (const auto& tag : tags) + tokens_.push_back(coll.consumes(tag)); + if (iConfig.existsAs(name + "_sel")) { + sel_ = StringCutObjectSelector(iConfig.getParameter(name + "_sel"), true); + } + } + const std::string& name() const { return name_; } + bool prop() const { return prop_; } + void get(const edm::Event& iEvent) { + edm::Handle handle; + for (const auto& token : tokens_) { + iEvent.getByToken(token, handle); + for (const reco::Candidate& c : *handle) { + if (sel_(c)) + objects_.emplace_back(c.pt(), c.eta(), c.phi()); + } + } + std::sort(objects_.begin(), objects_.end()); + } + const std::vector& objects() const { return objects_; } + void clear() { objects_.clear(); } + + private: + std::string name_; + bool prop_; + std::vector> tokens_; + StringCutObjectSelector sel_; + std::vector objects_; + }; + class InCone { + public: + InCone(const std::vector& objects, float eta, float phi, float dr) { + auto first = + std::lower_bound(objects.begin(), objects.end(), eta - dr - 0.01f); // small offset to avoid dealing with == + auto end = std::lower_bound(objects.begin(), objects.end(), eta + dr + 0.01f); + float dr2 = dr * dr; + sum04_ = 0; + for (auto it = first; it < end; ++it) { + float mydr2 = ::deltaR2(eta, phi, it->eta, it->phi); + if (mydr2 < dr2) + ptdr2_.emplace_back(it->pt, mydr2); + if (mydr2 < 0.16f) + sum04_ += it->pt; + } + } + float sum(float dr = 0.4) const { + if (dr == 0.4f) + return sum04_; + float dr2 = dr * dr; + float mysum = 0; + for (const auto& part : ptdr2_) { + if (part.second < dr2) + mysum += part.first; + } + return mysum; + } + int number(float dr, float threshold) const { + float dr2 = dr * dr, absthreshold = sum() * threshold; + int mysum = 0; + for (const auto& part : ptdr2_) { + if (part.second < dr2 && part.first > absthreshold) + mysum++; + } + return mysum; + } + float mindr(float threshold) const { + float best = 9999, absthreshold = sum() * threshold; + for (const auto& part : ptdr2_) { + if (part.second < best && part.first > absthreshold) + best = part.second; + } + return std::sqrt(best); + } + float nearest() const { + std::pair best(0, 9999); + for (const auto& part : ptdr2_) { + if (part.second < best.second) + best = part; + } + return best.first; + } + float max(float dr = 0.4) const { + float best = 0, dr2 = dr * dr; + for (const auto& part : ptdr2_) { + if (part.first > best && part.second < dr2) + best = part.first; + } + return best; + } + + private: + std::vector> ptdr2_; + float sum04_; + }; + + // variables from config file + edm::EDGetTokenT> genJetToken_; + edm::EDGetTokenT> genParticleToken_; + edm::ESGetToken BFieldTag_; + edm::ParameterSet objs_; + bool isParticleGun_; + std::string histFolder_; + std::string respresolFolder_; + dqmoffline::l1t::HistDefinitions histDefinitions_; + + std::vector>> phase2PFToken_; + std::vector>> phase2PuppiToken_; + + // config params + struct McVars { + float pt, pt02, eta, phi, iso02, iso04, iso08; + int charge; + float caloeta, calophi; + int id; + void fillP4(const reco::Candidate& cand) { + pt = cand.pt(); + eta = cand.eta(); + phi = cand.phi(); + caloeta = eta; + calophi = phi; + charge = 0; + } + void fillPropagated(const reco::Candidate& cand, float bz) { + if (cand.charge() != 0) { + math::XYZTLorentzVector vertex(cand.vx(), cand.vy(), cand.vz(), 0.); + auto caloetaphi = l1tpf::propagateToCalo(cand.p4(), vertex, cand.charge(), bz); + caloeta = caloetaphi.first; + calophi = caloetaphi.second; + } + } + + } mc_; + struct RecoVars { + float pt, pt02, pt08, ptbest, pthighest, mindr025; + int n025, n010; + void fill(const std::vector& objects, float eta, float phi) { + InCone incone(objects, eta, phi, 0.8); + pt = incone.sum(); + pt02 = incone.sum(0.2); + pt08 = incone.sum(0.8); + ptbest = incone.nearest(); + pthighest = incone.max(); + mindr025 = incone.mindr(0.25); + n025 = incone.number(0.2, 0.25); + n010 = incone.number(0.2, 0.10); + } + void clear() { + pt = 0.; + pt02 = 0.; + pt08 = 0.; + ptbest = 0.; + pthighest = 0.; + mindr025 = 0.; + n025 = -1; + n010 = -1; + } + }; + std::vector> reco_; + float bZ_; + + // Histograms + MonitorElement* h_L1PF_pt_; + MonitorElement* h_L1PF_eta_; + MonitorElement* h_L1Puppi_pt_; + MonitorElement* h_L1Puppi_eta_; + + MonitorElement* h_L1PF_pt_mu_; + MonitorElement* h_L1PF_eta_mu_; + MonitorElement* h_L1Puppi_pt_mu_; + MonitorElement* h_L1Puppi_eta_mu_; + + MonitorElement* h_L1PF_pt_el_; + MonitorElement* h_L1PF_eta_el_; + MonitorElement* h_L1Puppi_pt_el_; + MonitorElement* h_L1Puppi_eta_el_; + + MonitorElement* h_L1PF_pt_pho_; + MonitorElement* h_L1PF_eta_pho_; + MonitorElement* h_L1Puppi_pt_pho_; + MonitorElement* h_L1Puppi_eta_pho_; + + MonitorElement* h_L1PF_pt_ch_; + MonitorElement* h_L1PF_eta_ch_; + MonitorElement* h_L1Puppi_pt_ch_; + MonitorElement* h_L1Puppi_eta_ch_; + + MonitorElement* h_L1PF_pt_nh_; + MonitorElement* h_L1PF_eta_nh_; + MonitorElement* h_L1Puppi_pt_nh_; + MonitorElement* h_L1Puppi_eta_nh_; + + MonitorElement* h_L1PF_part_ptratio_0p2_vs_pt_barrel_; + MonitorElement* h_L1PF_part_ptratio_0p2_vs_pt_endcap_; + MonitorElement* h_L1PF_part_ptratio_0p2_vs_pt_ecnotk_; + MonitorElement* h_L1PF_part_ptratio_0p2_vs_pt_hf_; + MonitorElement* h_L1PF_part_ptratio_0p2_vs_eta_; + MonitorElement* h_L1Puppi_part_ptratio_0p2_vs_pt_barrel_; + MonitorElement* h_L1Puppi_part_ptratio_0p2_vs_pt_endcap_; + MonitorElement* h_L1Puppi_part_ptratio_0p2_vs_pt_ecnotk_; + MonitorElement* h_L1Puppi_part_ptratio_0p2_vs_pt_hf_; + MonitorElement* h_L1Puppi_part_ptratio_0p2_vs_eta_; + MonitorElement* h_L1PF_jet_ptratio_vs_pt_barrel_; + MonitorElement* h_L1PF_jet_ptratio_vs_pt_endcap_; + MonitorElement* h_L1PF_jet_ptratio_vs_pt_ecnotk_; + MonitorElement* h_L1PF_jet_ptratio_vs_pt_hf_; + MonitorElement* h_L1PF_jet_ptratio_vs_eta_; + MonitorElement* h_L1Puppi_jet_ptratio_vs_pt_barrel_; + MonitorElement* h_L1Puppi_jet_ptratio_vs_pt_endcap_; + MonitorElement* h_L1Puppi_jet_ptratio_vs_pt_ecnotk_; + MonitorElement* h_L1Puppi_jet_ptratio_vs_pt_hf_; + MonitorElement* h_L1Puppi_jet_ptratio_vs_eta_; + + MonitorElement* h_L1PF_part_response_0p2_pt_barrel_; + MonitorElement* h_L1PF_part_response_0p2_pt_endcap_; + MonitorElement* h_L1PF_part_response_0p2_pt_ecnotk_; + MonitorElement* h_L1PF_part_response_0p2_pt_hf_; + MonitorElement* h_L1PF_part_response_0p2_eta_; + MonitorElement* h_L1Puppi_part_response_0p2_pt_barrel_; + MonitorElement* h_L1Puppi_part_response_0p2_pt_endcap_; + MonitorElement* h_L1Puppi_part_response_0p2_pt_ecnotk_; + MonitorElement* h_L1Puppi_part_response_0p2_pt_hf_; + MonitorElement* h_L1Puppi_part_response_0p2_eta_; + MonitorElement* h_L1PF_jet_response_pt_barrel_; + MonitorElement* h_L1PF_jet_response_pt_endcap_; + MonitorElement* h_L1PF_jet_response_pt_ecnotk_; + MonitorElement* h_L1PF_jet_response_pt_hf_; + MonitorElement* h_L1PF_jet_response_eta_; + MonitorElement* h_L1Puppi_jet_response_pt_barrel_; + MonitorElement* h_L1Puppi_jet_response_pt_endcap_; + MonitorElement* h_L1Puppi_jet_response_pt_ecnotk_; + MonitorElement* h_L1Puppi_jet_response_pt_hf_; + MonitorElement* h_L1Puppi_jet_response_eta_; + + MonitorElement* h_L1PF_part_resolution_0p2_pt_barrel_; + MonitorElement* h_L1PF_part_resolution_0p2_pt_endcap_; + MonitorElement* h_L1PF_part_resolution_0p2_pt_ecnotk_; + MonitorElement* h_L1PF_part_resolution_0p2_pt_hf_; + MonitorElement* h_L1Puppi_part_resolution_0p2_pt_barrel_; + MonitorElement* h_L1Puppi_part_resolution_0p2_pt_endcap_; + MonitorElement* h_L1Puppi_part_resolution_0p2_pt_ecnotk_; + MonitorElement* h_L1Puppi_part_resolution_0p2_pt_hf_; + MonitorElement* h_L1PF_jet_resolution_pt_barrel_; + MonitorElement* h_L1PF_jet_resolution_pt_endcap_; + MonitorElement* h_L1PF_jet_resolution_pt_ecnotk_; + MonitorElement* h_L1PF_jet_resolution_pt_hf_; + MonitorElement* h_L1Puppi_jet_resolution_pt_barrel_; + MonitorElement* h_L1Puppi_jet_resolution_pt_endcap_; + MonitorElement* h_L1Puppi_jet_resolution_pt_ecnotk_; + MonitorElement* h_L1Puppi_jet_resolution_pt_hf_; +}; + +#endif diff --git a/DQMOffline/L1Trigger/interface/L1TPhase2OuterTrackerTkMET.h b/DQMOffline/L1Trigger/interface/L1TPhase2OuterTrackerTkMET.h new file mode 100644 index 0000000000000..55aaf5c4279dc --- /dev/null +++ b/DQMOffline/L1Trigger/interface/L1TPhase2OuterTrackerTkMET.h @@ -0,0 +1,60 @@ +#ifndef L1TPhase2_OuterTrackerTkMET_h +#define L1TPhase2_OuterTrackerTkMET_h + +#include +#include +#include +#include "FWCore/Utilities/interface/EDGetToken.h" +#include "FWCore/Framework/interface/Frameworkfwd.h" +#include "FWCore/Framework/interface/EDAnalyzer.h" +#include "DQMServices/Core/interface/MonitorElement.h" +#include "DQMServices/Core/interface/DQMEDAnalyzer.h" +#include "FWCore/ParameterSet/interface/ParameterSet.h" +#include "FWCore/Framework/interface/Event.h" +#include "FWCore/Framework/interface/MakerMacros.h" +#include "FWCore/Framework/interface/ESHandle.h" +#include "DataFormats/Common/interface/DetSetVectorNew.h" +#include "DataFormats/L1TrackTrigger/interface/TTTypes.h" +// #include "DataFormats/L1TVertex/interface/Vertex.h" +#include "DataFormats/L1TCorrelator/interface/TkPrimaryVertex.h" + +class DQMStore; +class L1TPhase2OuterTrackerTkMET : public DQMEDAnalyzer { +public: + explicit L1TPhase2OuterTrackerTkMET(const edm::ParameterSet&); + ~L1TPhase2OuterTrackerTkMET() override; + void analyze(const edm::Event&, const edm::EventSetup&) override; + void bookHistograms(DQMStore::IBooker&, edm::Run const&, edm::EventSetup const&) override; + + MonitorElement* Track_N = nullptr; // Number of tracks per event + MonitorElement* Track_Pt = nullptr; // pT distrubtion for tracks + MonitorElement* Track_Eta = nullptr; // eta distrubtion for tracks + MonitorElement* Track_VtxZ = nullptr; // z0 distrubtion for tracks + MonitorElement* Track_Chi2Dof = nullptr; // chi2 distrubtion for tracks + MonitorElement* Track_BendChi2 = nullptr; // bend chi2 distrubtion for tracks + MonitorElement* Track_NStubs = nullptr; // nstubs distrubtion for tracks + MonitorElement* Track_NPSstubs = nullptr; // nPS stubs distrubtion for tracks + + MonitorElement* TkMET_QualityCuts = nullptr; //Matches the quality cuts in the producer + MonitorElement* TkMET_PU = nullptr; + +private: + edm::ParameterSet conf_; + const edm::ESGetToken m_topoToken; + edm::EDGetTokenT pvToken; + edm::EDGetTokenT > > ttTrackToken_; + + float maxZ0; // in cm + float DeltaZ; // in cm + float maxEta; + float chi2dofMax; + float bendchi2Max; + float minPt; // in GeV + int nStubsmin; + int nStubsPSmin; // minimum number of stubs in PS modules + float maxPt; // in GeV + int HighPtTracks; // saturate or truncate + + std::string topFolderName_; +}; +#endif diff --git a/DQMOffline/L1Trigger/interface/L1TTauOffline.h b/DQMOffline/L1Trigger/interface/L1TTauOffline.h index 0e918f54456ed..4ec3b54f5d51e 100644 --- a/DQMOffline/L1Trigger/interface/L1TTauOffline.h +++ b/DQMOffline/L1Trigger/interface/L1TTauOffline.h @@ -22,7 +22,6 @@ // FWCore #include "FWCore/Common/interface/Provenance.h" #include "FWCore/Framework/interface/Frameworkfwd.h" -#include "FWCore/Framework/interface/EDAnalyzer.h" #include "FWCore/Framework/interface/ESHandle.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/LuminosityBlock.h" diff --git a/DQMOffline/L1Trigger/python/L1TPhase2Offline_cfi.py b/DQMOffline/L1Trigger/python/L1TPhase2Offline_cfi.py new file mode 100644 index 0000000000000..ea17998d17ee3 --- /dev/null +++ b/DQMOffline/L1Trigger/python/L1TPhase2Offline_cfi.py @@ -0,0 +1,140 @@ +import FWCore.ParameterSet.Config as cms +import math + +from DQMServices.Core.DQMEDAnalyzer import DQMEDAnalyzer + +OuterTrackerTkMET = DQMEDAnalyzer('L1TPhase2OuterTrackerTkMET', + TopFolderName = cms.string('L1T/L1TPhase2/'), + TTTracksTag = cms.InputTag("TTTracksFromTrackletEmulation", "Level1TTTracks"), + L1VertexInputTag = cms.InputTag("L1TkPrimaryVertex"), + maxZ0 = cms.double ( 15. ) , # in cm + maxEta = cms.double ( 2.4 ) , + chi2dofMax = cms.double( 10. ), + bendchi2Max = cms.double( 2.2 ), + minPt = cms.double( 2. ), # in GeV + DeltaZ = cms.double( 3. ), # in cm + nStubsmin = cms.int32( 4 ), # min number of stubs for the tracks to enter in TrkMET calculation + nStubsPSmin = cms.int32( -1 ), # min number of stubs in the PS Modules + maxPt = cms.double( -10. ), # in GeV. When maxPt > 0, tracks with PT above maxPt are considered as + # mismeasured and are treated according to HighPtTracks below. + # When maxPt < 0, no special treatment is done for high PT tracks. + HighPtTracks = cms.int32( 1 ), # when = 0 : truncation. Tracks with PT above maxPt are ignored + # when = 1 : saturation. Tracks with PT above maxPt are set to PT=maxPt. + # When maxPt < 0, no special treatment is done for high PT tracks. + +# Number of TTTracks + TH1_NTracks = cms.PSet( + Nbinsx = cms.int32(100), + xmax = cms.double(99.5), + xmin = cms.double(-0.5) + ), + +#Pt of the track + TH1_Track_Pt = cms.PSet( + Nbinsx = cms.int32(50), + xmax = cms.double(100), + xmin = cms.double(0) + ), + +#Eta of the track + TH1_Track_Eta = cms.PSet( + Nbinsx = cms.int32(45), + xmax = cms.double(3.0), + xmin = cms.double(-3.0) + ), + +#VtxZ of the track + TH1_Track_VtxZ = cms.PSet( + Nbinsx = cms.int32(51), + xmax = cms.double(25), + xmin = cms.double(-25) + ), + +#Nstubs of the track + TH1_Track_NStubs = cms.PSet( + Nbinsx = cms.int32(6), + xmax = cms.double(9), + xmin = cms.double(3) + ), + +#N PS stubs of the track + TH1_Track_NPSstubs = cms.PSet( + Nbinsx = cms.int32(6), + xmax = cms.double(7), + xmin = cms.double(1) + ), + +#Chi2dof of the track + TH1_Track_Chi2Dof = cms.PSet( + Nbinsx = cms.int32(100), + xmax = cms.double(50), + xmin = cms.double(0) + ), + +#Bendchi2 of the track + TH1_Track_BendChi2 = cms.PSet( + Nbinsx = cms.int32(30), + xmax = cms.double(50), + xmin = cms.double(0) + ), + +#tkMET distribution + TH1_Track_TkMET = cms.PSet( + Nbinsx = cms.int32(100), + xmax = cms.double(500), + xmin = cms.double(0) + ), +) + +l1tPhase2CorrelatorOfflineDQM = DQMEDAnalyzer( + "L1TPhase2CorrelatorOffline", + verbose = cms.untracked.bool(False), + genJetsInputTag = cms.untracked.InputTag("ak4GenJetsNoNu"), + genParticlesInputTag = cms.untracked.InputTag("genParticles"), + isParticleGun = cms.bool(False), + objects = cms.PSet( + L1PF = cms.VInputTag("l1pfCandidates:PF",), + L1PF_sel = cms.string("pt > 0"), + L1Puppi = cms.VInputTag("l1pfCandidates:Puppi",), + L1Puppi_sel = cms.string("pt > 0"), + ), + + histFolder = cms.string('L1T/L1TPhase2/Correlator/'), + + histDefinitions=cms.PSet( + resVsPt=cms.PSet( + name=cms.untracked.string("resVsPt"), + title=cms.untracked.string("resVsPt"), + nbinsX=cms.untracked.uint32(10), + xmin=cms.untracked.double(0.), + xmax=cms.untracked.double(100.), + ), + resVsEta=cms.PSet( + name=cms.untracked.string("resVsEta"), + title=cms.untracked.string("resVsEta"), + nbinsX=cms.untracked.uint32(20), + xmin=cms.untracked.double(-5.), + xmax=cms.untracked.double(5.), + ), + ptDist=cms.PSet( + name=cms.untracked.string("ptDist"), + title=cms.untracked.string("ptDist"), + nbinsX=cms.untracked.uint32(20), + xmin=cms.untracked.double(0.), + xmax=cms.untracked.double(100.), + ), + etaDist=cms.PSet( + name=cms.untracked.string("etaDist"), + title=cms.untracked.string("etaDist"), + nbinsX=cms.untracked.uint32(20), + xmin=cms.untracked.double(-5.), + xmax=cms.untracked.double(5.), + ), + ), + +) + +l1tPhase2OfflineDQM = cms.Sequence( + l1tPhase2CorrelatorOfflineDQM + + OuterTrackerTkMET + ) diff --git a/DQMOffline/L1Trigger/python/L1TriggerDqmOffline_SecondStep_cff.py b/DQMOffline/L1Trigger/python/L1TriggerDqmOffline_SecondStep_cff.py index 7cb0fa37cec2e..ec3c8ddf765a1 100644 --- a/DQMOffline/L1Trigger/python/L1TriggerDqmOffline_SecondStep_cff.py +++ b/DQMOffline/L1Trigger/python/L1TriggerDqmOffline_SecondStep_cff.py @@ -50,3 +50,8 @@ * l1tMuonDQMEmuEfficiency ) +# harvesting sequence for phase 2 +DQMHarvestL1TPhase2 = cms.Sequence( + +) + diff --git a/DQMOffline/L1Trigger/python/L1TriggerDqmOffline_cff.py b/DQMOffline/L1Trigger/python/L1TriggerDqmOffline_cff.py index fb79a5f898d9d..ae8e3923beddd 100644 --- a/DQMOffline/L1Trigger/python/L1TriggerDqmOffline_cff.py +++ b/DQMOffline/L1Trigger/python/L1TriggerDqmOffline_cff.py @@ -431,3 +431,40 @@ stage2L1Trigger.toReplaceWith(l1TriggerMuonDqmOfflineClient, Stage2l1tMuonDqmOfflineClient) stage2L1Trigger.toReplaceWith(l1TriggerDqmOfflineCosmics, Stage2l1TriggerDqmOffline) stage2L1Trigger.toReplaceWith(l1TriggerDqmOfflineCosmicsClient, Stage2l1TriggerDqmOfflineClient) + +############################################################################## +#phase2 +############################################################################## + +from Configuration.Eras.Modifier_phase2_trigger_cff import phase2_trigger + +# +# define sequences +# +from DQMOffline.L1Trigger.L1TPhase2Offline_cfi import * + +############################################################################## +# sequence to run for all datasets +Phase2l1TriggerOffline = cms.Sequence( + dqmEnvL1T + ) + +############################################################################## +# DQM sequences for step 1 + +# DQM Offline sequence +Phase2l1TriggerDqmOffline = cms.Sequence( + l1tPhase2OfflineDQM + ) + +############################################################################## +# DQM sequences for step 2 + +# DQM Offline sequence +Phase2l1TriggerDqmOfflineClient = cms.Sequence( + DQMHarvestL1TPhase2 + ) +#replacements for phase2 +phase2_trigger.toReplaceWith(l1TriggerOffline, Phase2l1TriggerOffline) +phase2_trigger.toReplaceWith(l1TriggerDqmOffline, Phase2l1TriggerDqmOffline) +phase2_trigger.toReplaceWith(l1TriggerDqmOfflineClient, Phase2l1TriggerDqmOfflineClient) diff --git a/DQMOffline/L1Trigger/src/L1TMuonDQMOffline.cc b/DQMOffline/L1Trigger/src/L1TMuonDQMOffline.cc index 949c13d4fe330..51ae121daedee 100644 --- a/DQMOffline/L1Trigger/src/L1TMuonDQMOffline.cc +++ b/DQMOffline/L1Trigger/src/L1TMuonDQMOffline.cc @@ -108,7 +108,7 @@ double MuonGmtPair::getVar(const L1TMuonDQMOffline::EffType type) const { //__________DQM_base_class_______________________________________________ L1TMuonDQMOffline::L1TMuonDQMOffline(const ParameterSet& ps) - : m_propagator(ps.getParameter("muProp")), + : m_propagator(ps.getParameter("muProp"), consumesCollector()), m_effTypes({kEffPt, kEffPhi, kEffEta, kEffVtx}), m_resTypes({kResPt, kResQOverPt, kResPhi, kResEta}), m_etaRegions({kEtaRegionAll, kEtaRegionBmtf, kEtaRegionOmtf, kEtaRegionEmtf}), @@ -179,7 +179,6 @@ void L1TMuonDQMOffline::dqmBeginRun(const edm::Run& run, const edm::EventSetup& cout << "[L1TMuonDQMOffline:] Called beginRun." << endl; bool changed = true; m_hltConfig.init(run, iSetup, m_trigProcess, changed); - m_propagator.init(iSetup); } //_____________________________________________________________________ @@ -211,6 +210,8 @@ void L1TMuonDQMOffline::bookHistograms(DQMStore::IBooker& ibooker, const edm::Ru //_____________________________________________________________________ void L1TMuonDQMOffline::analyze(const Event& iEvent, const EventSetup& eventSetup) { + m_propagator.init(eventSetup); + Handle muons; iEvent.getByToken(m_MuonInputTag, muons); Handle beamSpot; diff --git a/DQMOffline/L1Trigger/src/L1TPhase2CorrelatorOffline.cc b/DQMOffline/L1Trigger/src/L1TPhase2CorrelatorOffline.cc new file mode 100644 index 0000000000000..42ebbd59401d3 --- /dev/null +++ b/DQMOffline/L1Trigger/src/L1TPhase2CorrelatorOffline.cc @@ -0,0 +1,967 @@ +/** + * @file L1TPhase2CorrelatorOffline.cc + * @authors Dylan Rankin (MIT) + * @date 20/10/2020 + * @version 0.1 + * + */ + +#include "DQMOffline/L1Trigger/interface/L1TPhase2CorrelatorOffline.h" + +#include "TLorentzVector.h" +#include "TGraph.h" + +#include +#include +#include +#include +#include +#include + +using namespace reco; +using namespace trigger; +using namespace edm; +using namespace std; + +const std::map L1TPhase2CorrelatorOffline::PlotConfigNames = { + {"resVsPt", PlotConfig::resVsPt}, + {"resVsEta", PlotConfig::resVsEta}, + {"ptDist", PlotConfig::ptDist}, + {"etaDist", PlotConfig::etaDist}}; + +// +// -------------------------------------- Constructor -------------------------------------------- +// +L1TPhase2CorrelatorOffline::L1TPhase2CorrelatorOffline(const edm::ParameterSet& ps) + : genJetToken_(consumes>(ps.getUntrackedParameter("genJetsInputTag"))), + genParticleToken_( + consumes>(ps.getUntrackedParameter("genParticlesInputTag"))), + BFieldTag_{esConsumes()}, + objs_(ps.getParameter("objects")), + isParticleGun_(ps.getParameter("isParticleGun")), + histFolder_(ps.getParameter("histFolder")), + respresolFolder_(histFolder_ + "/respresol_raw"), + histDefinitions_(dqmoffline::l1t::readHistDefinitions(ps.getParameterSet("histDefinitions"), PlotConfigNames)), + h_L1PF_pt_(), + h_L1PF_eta_(), + h_L1Puppi_pt_(), + h_L1Puppi_eta_(), + h_L1PF_pt_mu_(), + h_L1PF_eta_mu_(), + h_L1Puppi_pt_mu_(), + h_L1Puppi_eta_mu_(), + h_L1PF_pt_el_(), + h_L1PF_eta_el_(), + h_L1Puppi_pt_el_(), + h_L1Puppi_eta_el_(), + h_L1PF_pt_pho_(), + h_L1PF_eta_pho_(), + h_L1Puppi_pt_pho_(), + h_L1Puppi_eta_pho_(), + h_L1PF_pt_ch_(), + h_L1PF_eta_ch_(), + h_L1Puppi_pt_ch_(), + h_L1Puppi_eta_ch_(), + h_L1PF_pt_nh_(), + h_L1PF_eta_nh_(), + h_L1Puppi_pt_nh_(), + h_L1Puppi_eta_nh_(), + h_L1PF_part_ptratio_0p2_vs_pt_barrel_(), + h_L1PF_part_ptratio_0p2_vs_pt_endcap_(), + h_L1PF_part_ptratio_0p2_vs_pt_ecnotk_(), + h_L1PF_part_ptratio_0p2_vs_pt_hf_(), + h_L1PF_part_ptratio_0p2_vs_eta_(), + h_L1Puppi_part_ptratio_0p2_vs_pt_barrel_(), + h_L1Puppi_part_ptratio_0p2_vs_pt_endcap_(), + h_L1Puppi_part_ptratio_0p2_vs_pt_ecnotk_(), + h_L1Puppi_part_ptratio_0p2_vs_pt_hf_(), + h_L1Puppi_part_ptratio_0p2_vs_eta_(), + h_L1PF_jet_ptratio_vs_pt_barrel_(), + h_L1PF_jet_ptratio_vs_pt_endcap_(), + h_L1PF_jet_ptratio_vs_pt_ecnotk_(), + h_L1PF_jet_ptratio_vs_pt_hf_(), + h_L1PF_jet_ptratio_vs_eta_(), + h_L1Puppi_jet_ptratio_vs_pt_barrel_(), + h_L1Puppi_jet_ptratio_vs_pt_endcap_(), + h_L1Puppi_jet_ptratio_vs_pt_ecnotk_(), + h_L1Puppi_jet_ptratio_vs_pt_hf_(), + h_L1Puppi_jet_ptratio_vs_eta_() { + edm::LogInfo("L1TPhase2CorrelatorOffline") << "Constructor " + << "L1TPhase2CorrelatorOffline::L1TPhase2CorrelatorOffline " << std::endl; + + auto reconames = objs_.getParameterNamesForType>(); + for (const std::string& name : reconames) { + reco_.emplace_back(L1TPhase2CorrelatorOffline::MultiCollection(objs_, name, consumesCollector()), RecoVars()); + } + for (auto& obj : objs_.getParameter>("L1PF")) { + phase2PFToken_.push_back(consumes>(obj)); + } + for (auto& obj : objs_.getParameter>("L1Puppi")) { + phase2PuppiToken_.push_back(consumes>(obj)); + } +} + +// +// -- Destructor +// +L1TPhase2CorrelatorOffline::~L1TPhase2CorrelatorOffline() { + edm::LogInfo("L1TPhase2CorrelatorOffline") + << "Destructor L1TPhase2CorrelatorOffline::~L1TPhase2CorrelatorOffline " << std::endl; +} + +// +// -------------------------------------- beginRun -------------------------------------------- +// +void L1TPhase2CorrelatorOffline::dqmBeginRun(const edm::Run& run, const edm::EventSetup& iSetup) { + edm::LogInfo("L1TPhase2CorrelatorOffline") << "L1TPhase2CorrelatorOffline::beginRun" << std::endl; + + bZ_ = iSetup.getData(BFieldTag_).inTesla(GlobalPoint(0, 0, 0)).z(); +} + +// +// -------------------------------------- bookHistos -------------------------------------------- +// +void L1TPhase2CorrelatorOffline::bookHistograms(DQMStore::IBooker& ibooker, edm::Run const&, edm::EventSetup const&) { + edm::LogInfo("L1TPhase2CorrelatorOffline") << "L1TPhase2CorrelatorOffline::bookHistograms" << std::endl; + + // book at beginRun + bookPhase2CorrelatorHistos(ibooker); +} + +// +// -------------------------------------- Analyze -------------------------------------------- +// +void L1TPhase2CorrelatorOffline::analyze(edm::Event const& e, edm::EventSetup const& eSetup) { + edm::Handle> genjets; + edm::Handle> genparticles; + e.getByToken(genJetToken_, genjets); + e.getByToken(genParticleToken_, genparticles); + + std::vector prompts, taus; + for (const reco::GenParticle& gen : *genparticles) { + if (isParticleGun_) { + if (gen.statusFlags().isPrompt() == 1) + prompts.push_back(&gen); + continue; + } + if ((gen.isPromptFinalState() || gen.isDirectPromptTauDecayProductFinalState()) && + (std::abs(gen.pdgId()) == 11 || std::abs(gen.pdgId()) == 13) && gen.pt() > 5) { + prompts.push_back(&gen); + } else if (gen.isPromptFinalState() && std::abs(gen.pdgId()) == 22 && gen.pt() > 10) { + prompts.push_back(&gen); + } else if (abs(gen.pdgId()) == 15 && gen.isPromptDecayed()) { + taus.push_back(&gen); + } + } + + for (auto& recopair : reco_) { + recopair.first.get(e); + } + + for (const reco::GenJet& j1 : *genjets) { + bool ok = true; + const reco::Candidate* match = nullptr; + for (const reco::GenParticle* gp : prompts) { + if (::deltaR2(*gp, j1) < 0.16f) { + if (match != nullptr) { + ok = false; + break; + } else { + match = gp; + } + } + } + if (!ok) + continue; + if (!match) { + // look for a tau + for (const reco::GenParticle* gp : taus) { + if (::deltaR2(*gp, j1) < 0.16f) { + if (match != nullptr) { + ok = false; + break; + } else { + match = gp; + } + } + } + if (!ok) + continue; + if (match != nullptr && match->numberOfDaughters() == 2 && + std::abs(match->daughter(0)->pdgId()) + std::abs(match->daughter(1)->pdgId()) == 211 + 16) { + // one-prong tau, consider it a pion + match = (std::abs(match->daughter(0)->pdgId()) == 211 ? match->daughter(0) : match->daughter(1)); + } + } + if (match != nullptr) { + if (std::abs(match->pdgId()) == 15) { + reco::Particle::LorentzVector pvis; + for (unsigned int i = 0, n = match->numberOfDaughters(); i < n; ++i) { + const reco::Candidate* dau = match->daughter(i); + if (std::abs(dau->pdgId()) == 12 || std::abs(dau->pdgId()) == 14 || std::abs(dau->pdgId()) == 16) { + continue; + } + pvis += dau->p4(); + } + mc_.pt = pvis.Pt(); + mc_.eta = pvis.Eta(); + mc_.phi = pvis.Phi(); + } else { + mc_.fillP4(*match); + mc_.fillPropagated(*match, bZ_); + } + mc_.id = std::abs(match->pdgId()); + mc_.iso04 = j1.pt() / mc_.pt - 1; + mc_.iso02 = 0; + for (const auto& dptr : j1.daughterPtrVector()) { + if (::deltaR2(*dptr, *match) < 0.04f) { + mc_.iso02 += dptr->pt(); + } + } + mc_.iso02 = mc_.iso02 / mc_.pt - 1; + } else { + if (j1.pt() < 20) + continue; + mc_.fillP4(j1); + mc_.id = 0; + mc_.iso02 = 0; + mc_.iso04 = 0; + } + mc_.iso08 = mc_.iso04; + for (const reco::GenJet& j2 : *genjets) { + if (&j2 == &j1) + continue; + if (::deltaR2(j1, j2) < 0.64f) + mc_.iso08 += j2.pt() / mc_.pt; + } + for (auto& recopair : reco_) { + recopair.second.fill(recopair.first.objects(), + recopair.first.prop() ? mc_.caloeta : mc_.eta, + recopair.first.prop() ? mc_.calophi : mc_.phi); + + if (abs(mc_.id) != 0 && fabs(mc_.iso04) < 0.05) { + if (recopair.first.name() == "L1PF") { + if (fabs(mc_.eta) < 1.5) { + h_L1PF_part_ptratio_0p2_vs_pt_barrel_->Fill(mc_.pt, recopair.second.pt02 / mc_.pt); + } else if (fabs(mc_.eta) < 2.5) { + h_L1PF_part_ptratio_0p2_vs_pt_endcap_->Fill(mc_.pt, recopair.second.pt02 / mc_.pt); + } else if (fabs(mc_.eta) < 3.) { + h_L1PF_part_ptratio_0p2_vs_pt_ecnotk_->Fill(mc_.pt, recopair.second.pt02 / mc_.pt); + } else if (fabs(mc_.eta) < 5.) { + h_L1PF_part_ptratio_0p2_vs_pt_hf_->Fill(mc_.pt, recopair.second.pt02 / mc_.pt); + } + h_L1PF_part_ptratio_0p2_vs_eta_->Fill(mc_.eta, recopair.second.pt02 / mc_.pt); + } + if (recopair.first.name() == "L1Puppi") { + if (fabs(mc_.eta) < 1.5) { + h_L1Puppi_part_ptratio_0p2_vs_pt_barrel_->Fill(mc_.pt, recopair.second.pt02 / mc_.pt); + } else if (fabs(mc_.eta) < 2.5) { + h_L1Puppi_part_ptratio_0p2_vs_pt_endcap_->Fill(mc_.pt, recopair.second.pt02 / mc_.pt); + } else if (fabs(mc_.eta) < 3.) { + h_L1Puppi_part_ptratio_0p2_vs_pt_ecnotk_->Fill(mc_.pt, recopair.second.pt02 / mc_.pt); + } else if (fabs(mc_.eta) < 5.) { + h_L1Puppi_part_ptratio_0p2_vs_pt_hf_->Fill(mc_.pt, recopair.second.pt02 / mc_.pt); + } + h_L1Puppi_part_ptratio_0p2_vs_eta_->Fill(mc_.eta, recopair.second.pt02 / mc_.pt); + } + } + if (abs(mc_.id) == 0) { + if (recopair.first.name() == "L1PF") { + if (fabs(mc_.eta) < 1.5) { + h_L1PF_jet_ptratio_vs_pt_barrel_->Fill(mc_.pt, recopair.second.pt / mc_.pt); + } else if (fabs(mc_.eta) < 2.5) { + h_L1PF_jet_ptratio_vs_pt_endcap_->Fill(mc_.pt, recopair.second.pt / mc_.pt); + } else if (fabs(mc_.eta) < 3.) { + h_L1PF_jet_ptratio_vs_pt_ecnotk_->Fill(mc_.pt, recopair.second.pt / mc_.pt); + } else if (fabs(mc_.eta) < 5.) { + h_L1PF_jet_ptratio_vs_pt_hf_->Fill(mc_.pt, recopair.second.pt / mc_.pt); + } + h_L1PF_jet_ptratio_vs_eta_->Fill(mc_.eta, recopair.second.pt / mc_.pt); + } + if (recopair.first.name() == "L1Puppi") { + if (fabs(mc_.eta) < 1.5) { + h_L1Puppi_jet_ptratio_vs_pt_barrel_->Fill(mc_.pt, recopair.second.pt / mc_.pt); + } else if (fabs(mc_.eta) < 2.5) { + h_L1Puppi_jet_ptratio_vs_pt_endcap_->Fill(mc_.pt, recopair.second.pt / mc_.pt); + } else if (fabs(mc_.eta) < 3.) { + h_L1Puppi_jet_ptratio_vs_pt_ecnotk_->Fill(mc_.pt, recopair.second.pt / mc_.pt); + } else if (fabs(mc_.eta) < 5.) { + h_L1Puppi_jet_ptratio_vs_pt_hf_->Fill(mc_.pt, recopair.second.pt / mc_.pt); + } + h_L1Puppi_jet_ptratio_vs_eta_->Fill(mc_.eta, recopair.second.pt / mc_.pt); + } + } + } + } + for (auto& recopair : reco_) { + recopair.first.clear(); + recopair.second.clear(); + } + + for (auto& pfToken : phase2PFToken_) { + edm::Handle> l1pfs; + e.getByToken(pfToken, l1pfs); + + for (const auto& pfc : *l1pfs) { + h_L1PF_pt_->Fill(pfc.pt()); + h_L1PF_eta_->Fill(pfc.eta()); + if (abs(pfc.pdgId()) == 13) { + h_L1PF_pt_mu_->Fill(pfc.pt()); + h_L1PF_eta_mu_->Fill(pfc.eta()); + } else if (abs(pfc.pdgId()) == 11) { + h_L1PF_pt_el_->Fill(pfc.pt()); + h_L1PF_eta_el_->Fill(pfc.eta()); + } else if (abs(pfc.pdgId()) == 22) { + h_L1PF_pt_pho_->Fill(pfc.pt()); + h_L1PF_eta_pho_->Fill(pfc.eta()); + } else if (abs(pfc.pdgId()) == 211) { + h_L1PF_pt_ch_->Fill(pfc.pt()); + h_L1PF_eta_ch_->Fill(pfc.eta()); + } else if (abs(pfc.pdgId()) == 130) { + h_L1PF_pt_nh_->Fill(pfc.pt()); + h_L1PF_eta_nh_->Fill(pfc.eta()); + } + } // loop over L1 PF + } + for (auto& pupToken : phase2PuppiToken_) { + edm::Handle> l1pups; + e.getByToken(pupToken, l1pups); + for (const auto& pupc : *l1pups) { + h_L1Puppi_pt_->Fill(pupc.pt()); + h_L1Puppi_eta_->Fill(pupc.eta()); + if (abs(pupc.pdgId()) == 13) { + h_L1Puppi_pt_mu_->Fill(pupc.pt()); + h_L1Puppi_eta_mu_->Fill(pupc.eta()); + } else if (abs(pupc.pdgId()) == 11) { + h_L1Puppi_pt_el_->Fill(pupc.pt()); + h_L1Puppi_eta_el_->Fill(pupc.eta()); + } else if (abs(pupc.pdgId()) == 22) { + h_L1Puppi_pt_pho_->Fill(pupc.pt()); + h_L1Puppi_eta_pho_->Fill(pupc.eta()); + } else if (abs(pupc.pdgId()) == 211) { + h_L1Puppi_pt_ch_->Fill(pupc.pt()); + h_L1Puppi_eta_ch_->Fill(pupc.eta()); + } else if (abs(pupc.pdgId()) == 130) { + h_L1Puppi_pt_nh_->Fill(pupc.pt()); + h_L1Puppi_eta_nh_->Fill(pupc.eta()); + } + } // loop over L1 Puppi + } +} + +// +// -------------------------------------- endRun -------------------------------------------- +// +// +// -------------------------------------- book histograms -------------------------------------------- +// +void L1TPhase2CorrelatorOffline::bookPhase2CorrelatorHistos(DQMStore::IBooker& ibooker) { + ibooker.cd(); + ibooker.setCurrentFolder(histFolder_); + ibooker.setScope(MonitorElementData::Scope::RUN); + + dqmoffline::l1t::HistDefinition resVsPtDef = histDefinitions_[PlotConfig::resVsPt]; + dqmoffline::l1t::HistDefinition resVsEtaDef = histDefinitions_[PlotConfig::resVsEta]; + dqmoffline::l1t::HistDefinition ptDistDef = histDefinitions_[PlotConfig::ptDist]; + dqmoffline::l1t::HistDefinition etaDistDef = histDefinitions_[PlotConfig::etaDist]; + + int ptratio_nbins = 300; + float ptratio_lo = 0.; + float ptratio_hi = 3.; + + h_L1PF_pt_ = ibooker.book1D("PF_pt", "L1 PF p_{T}", ptDistDef.nbinsX, ptDistDef.xmin, ptDistDef.xmax); + h_L1PF_eta_ = ibooker.book1D("PF_eta", "L1 PF #eta", etaDistDef.nbinsX, etaDistDef.xmin, etaDistDef.xmax); + h_L1Puppi_pt_ = ibooker.book1D("Puppi_pt", "L1 PUPPI p_{T}", ptDistDef.nbinsX, ptDistDef.xmin, ptDistDef.xmax); + h_L1Puppi_eta_ = ibooker.book1D("Puppi_eta", "L1 PUPPI #eta", etaDistDef.nbinsX, etaDistDef.xmin, etaDistDef.xmax); + + h_L1PF_pt_mu_ = ibooker.book1D("PF_pt_mu", "L1 PF Muon p_{T}", ptDistDef.nbinsX, ptDistDef.xmin, ptDistDef.xmax); + h_L1PF_eta_mu_ = ibooker.book1D("PF_eta_mu", "L1 PF Muon #eta", etaDistDef.nbinsX, etaDistDef.xmin, etaDistDef.xmax); + h_L1Puppi_pt_mu_ = + ibooker.book1D("Puppi_pt_mu", "L1 PUPPI Muon p_{T}", ptDistDef.nbinsX, ptDistDef.xmin, ptDistDef.xmax); + h_L1Puppi_eta_mu_ = + ibooker.book1D("Puppi_eta_mu", "L1 PUPPI Muon #eta", etaDistDef.nbinsX, etaDistDef.xmin, etaDistDef.xmax); + + h_L1PF_pt_el_ = ibooker.book1D("PF_pt_el", "L1 PF Electron p_{T}", ptDistDef.nbinsX, ptDistDef.xmin, ptDistDef.xmax); + h_L1PF_eta_el_ = + ibooker.book1D("PF_eta_el", "L1 PF Electron #eta", etaDistDef.nbinsX, etaDistDef.xmin, etaDistDef.xmax); + h_L1Puppi_pt_el_ = + ibooker.book1D("Puppi_pt_el", "L1 PUPPI Electron p_{T}", ptDistDef.nbinsX, ptDistDef.xmin, ptDistDef.xmax); + h_L1Puppi_eta_el_ = + ibooker.book1D("Puppi_eta_el", "L1 PUPPI Electron #eta", etaDistDef.nbinsX, etaDistDef.xmin, etaDistDef.xmax); + + h_L1PF_pt_pho_ = ibooker.book1D("PF_pt_pho", "L1 PF Photon p_{T}", ptDistDef.nbinsX, ptDistDef.xmin, ptDistDef.xmax); + h_L1PF_eta_pho_ = + ibooker.book1D("PF_eta_pho", "L1 PF Photon #eta", etaDistDef.nbinsX, etaDistDef.xmin, etaDistDef.xmax); + h_L1Puppi_pt_pho_ = + ibooker.book1D("Puppi_pt_pho", "L1 PUPPI Photon p_{T}", ptDistDef.nbinsX, ptDistDef.xmin, ptDistDef.xmax); + h_L1Puppi_eta_pho_ = + ibooker.book1D("Puppi_eta_pho", "L1 PUPPI Photon #eta", etaDistDef.nbinsX, etaDistDef.xmin, etaDistDef.xmax); + + h_L1PF_pt_ch_ = + ibooker.book1D("PF_pt_ch", "L1 PF Charged Hadron p_{T}", ptDistDef.nbinsX, ptDistDef.xmin, ptDistDef.xmax); + h_L1PF_eta_ch_ = + ibooker.book1D("PF_eta_ch", "L1 PF Charged Hadron #eta", etaDistDef.nbinsX, etaDistDef.xmin, etaDistDef.xmax); + h_L1Puppi_pt_ch_ = + ibooker.book1D("Puppi_pt_ch", "L1 PUPPI Charged Hadron p_{T}", ptDistDef.nbinsX, ptDistDef.xmin, ptDistDef.xmax); + h_L1Puppi_eta_ch_ = ibooker.book1D( + "Puppi_eta_ch", "L1 PUPPI Charged Hadron #eta", etaDistDef.nbinsX, etaDistDef.xmin, etaDistDef.xmax); + + h_L1PF_pt_nh_ = + ibooker.book1D("PF_pt_nh", "L1 PF Neutral Hadron p_{T}", ptDistDef.nbinsX, ptDistDef.xmin, ptDistDef.xmax); + h_L1PF_eta_nh_ = + ibooker.book1D("PF_eta_nh", "L1 PF Neutral Hadron #eta", etaDistDef.nbinsX, etaDistDef.xmin, etaDistDef.xmax); + h_L1Puppi_pt_nh_ = + ibooker.book1D("Puppi_pt_nh", "L1 PUPPI Neutral Hadron p_{T}", ptDistDef.nbinsX, ptDistDef.xmin, ptDistDef.xmax); + h_L1Puppi_eta_nh_ = ibooker.book1D( + "Puppi_eta_nh", "L1 PUPPI Neutral Hadron #eta", etaDistDef.nbinsX, etaDistDef.xmin, etaDistDef.xmax); + + ibooker.setCurrentFolder(respresolFolder_); + + h_L1PF_part_ptratio_0p2_vs_pt_barrel_ = ibooker.book2D("L1PFParticlePtRatio0p2VsPtBarrel", + "L1 PF Particle L1/Gen (#Delta R < 0.2) vs p_{T}, Barrel", + resVsPtDef.nbinsX, + resVsPtDef.xmin, + resVsPtDef.xmax, + ptratio_nbins, + ptratio_lo, + ptratio_hi); + + h_L1PF_part_ptratio_0p2_vs_pt_endcap_ = ibooker.book2D("L1PFParticlePtRatio0p2VsPtEndcap", + "L1 PF Particle L1/Gen (#Delta R < 0.2) vs p_{T}, Endcap", + resVsPtDef.nbinsX, + resVsPtDef.xmin, + resVsPtDef.xmax, + ptratio_nbins, + ptratio_lo, + ptratio_hi); + + h_L1PF_part_ptratio_0p2_vs_pt_ecnotk_ = + ibooker.book2D("L1PFParticlePtRatio0p2VsPtEndcapNoTk", + "L1 PF Particle L1/Gen (#Delta R < 0.2) vs p_{T}, Endcap No Tk", + resVsPtDef.nbinsX, + resVsPtDef.xmin, + resVsPtDef.xmax, + ptratio_nbins, + ptratio_lo, + ptratio_hi); + + h_L1PF_part_ptratio_0p2_vs_pt_hf_ = ibooker.book2D("L1PFParticlePtRatio0p2VsPtHF", + "L1 PF Particle L1/Gen (#Delta R < 0.2) vs p_{T}, HF", + resVsPtDef.nbinsX, + resVsPtDef.xmin, + resVsPtDef.xmax, + ptratio_nbins, + ptratio_lo, + ptratio_hi); + + h_L1PF_part_ptratio_0p2_vs_eta_ = ibooker.book2D("L1PFParticlePtRatio0p2VsEta", + "L1 PF Particle L1/Gen (#Delta R < 0.2) vs #eta", + resVsEtaDef.nbinsX, + resVsEtaDef.xmin, + resVsEtaDef.xmax, + ptratio_nbins, + ptratio_lo, + ptratio_hi); + + h_L1Puppi_part_ptratio_0p2_vs_pt_barrel_ = + ibooker.book2D("L1PUPPIParticlePtRatio0p2VsPtBarrel", + "L1 PUPPI Particle L1/Gen (#Delta R < 0.2) vs p_{T}, Barrel", + resVsPtDef.nbinsX, + resVsPtDef.xmin, + resVsPtDef.xmax, + ptratio_nbins, + ptratio_lo, + ptratio_hi); + + h_L1Puppi_part_ptratio_0p2_vs_pt_endcap_ = + ibooker.book2D("L1PUPPIParticlePtRatio0p2VsPtEndcap", + "L1 PUPPI Particle L1/Gen (#Delta R < 0.2) vs p_{T}, Endcap", + resVsPtDef.nbinsX, + resVsPtDef.xmin, + resVsPtDef.xmax, + ptratio_nbins, + ptratio_lo, + ptratio_hi); + + h_L1Puppi_part_ptratio_0p2_vs_pt_ecnotk_ = + ibooker.book2D("L1PUPPIParticlePtRatio0p2VsPtEndcapNoTk", + "L1 PUPPI Particle L1/Gen (#Delta R < 0.2) vs p_{T}, Endcap No Tk", + resVsPtDef.nbinsX, + resVsPtDef.xmin, + resVsPtDef.xmax, + ptratio_nbins, + ptratio_lo, + ptratio_hi); + + h_L1Puppi_part_ptratio_0p2_vs_pt_hf_ = ibooker.book2D("L1PUPPIParticlePtRatio0p2VsPtHF", + "L1 PUPPI Particle L1/Gen (#Delta R < 0.2) vs p_{T}, HF", + resVsPtDef.nbinsX, + resVsPtDef.xmin, + resVsPtDef.xmax, + ptratio_nbins, + ptratio_lo, + ptratio_hi); + + h_L1Puppi_part_ptratio_0p2_vs_eta_ = ibooker.book2D("L1PUPPIParticlePtRatio0p2VsEta", + "L1 PUPPI Particle L1/Gen (#Delta R < 0.2) vs #eta", + resVsEtaDef.nbinsX, + resVsEtaDef.xmin, + resVsEtaDef.xmax, + ptratio_nbins, + ptratio_lo, + ptratio_hi); + + h_L1PF_jet_ptratio_vs_pt_barrel_ = ibooker.book2D("L1PFJetPtRatioVsPtBarrel", + "L1 PF Jet L1/Gen vs p_{T}, Barrel", + resVsPtDef.nbinsX, + resVsPtDef.xmin, + resVsPtDef.xmax, + ptratio_nbins, + ptratio_lo, + ptratio_hi); + + h_L1PF_jet_ptratio_vs_pt_endcap_ = ibooker.book2D("L1PFJetPtRatioVsPtEndcap", + "L1 PF Jet L1/Gen vs p_{T}, Endcap", + resVsPtDef.nbinsX, + resVsPtDef.xmin, + resVsPtDef.xmax, + ptratio_nbins, + ptratio_lo, + ptratio_hi); + + h_L1PF_jet_ptratio_vs_pt_ecnotk_ = ibooker.book2D("L1PFJetPtRatioVsPtEndcapNoTk", + "L1 PF Jet L1/Gen vs p_{T}, Endcap No Tk", + resVsPtDef.nbinsX, + resVsPtDef.xmin, + resVsPtDef.xmax, + ptratio_nbins, + ptratio_lo, + ptratio_hi); + + h_L1PF_jet_ptratio_vs_pt_hf_ = ibooker.book2D("L1PFJetPtRatioVsPtHF", + "L1 PF Jet L1/Gen vs p_{T}, HF", + resVsPtDef.nbinsX, + resVsPtDef.xmin, + resVsPtDef.xmax, + ptratio_nbins, + ptratio_lo, + ptratio_hi); + + h_L1PF_jet_ptratio_vs_eta_ = ibooker.book2D("L1PFJetPtRatioVsEta", + "L1 PF Jet L1/Gen vs #eta", + resVsEtaDef.nbinsX, + resVsEtaDef.xmin, + resVsEtaDef.xmax, + ptratio_nbins, + ptratio_lo, + ptratio_hi); + + h_L1Puppi_jet_ptratio_vs_pt_barrel_ = ibooker.book2D("L1PUPPIJetPtRatioVsPtBarrel", + "L1 PUPPI Jet L1/Gen vs p_{T}, Barrel", + resVsPtDef.nbinsX, + resVsPtDef.xmin, + resVsPtDef.xmax, + ptratio_nbins, + ptratio_lo, + ptratio_hi); + + h_L1Puppi_jet_ptratio_vs_pt_endcap_ = ibooker.book2D("L1PUPPIJetPtRatioVsPtEndcap", + "L1 PUPPI Jet L1/Gen vs p_{T}, Endcap", + resVsPtDef.nbinsX, + resVsPtDef.xmin, + resVsPtDef.xmax, + ptratio_nbins, + ptratio_lo, + ptratio_hi); + + h_L1Puppi_jet_ptratio_vs_pt_ecnotk_ = ibooker.book2D("L1PUPPIJetPtRatioVsPtEndcapNoTk", + "L1 PUPPI Jet L1/Gen vs p_{T}, EndcapNoTk", + resVsPtDef.nbinsX, + resVsPtDef.xmin, + resVsPtDef.xmax, + ptratio_nbins, + ptratio_lo, + ptratio_hi); + + h_L1Puppi_jet_ptratio_vs_pt_hf_ = ibooker.book2D("L1PUPPIJetPtRatioVsPtHF", + "L1 PUPPI Jet L1/Gen vs p_{T}, HF", + resVsPtDef.nbinsX, + resVsPtDef.xmin, + resVsPtDef.xmax, + ptratio_nbins, + ptratio_lo, + ptratio_hi); + + h_L1Puppi_jet_ptratio_vs_eta_ = ibooker.book2D("L1PUPPIJetPtRatioVsEta", + "L1 PUPPI Jet L1/Gen vs #eta", + resVsEtaDef.nbinsX, + resVsEtaDef.xmin, + resVsEtaDef.xmax, + ptratio_nbins, + ptratio_lo, + ptratio_hi); + + ibooker.setCurrentFolder(histFolder_); + //Response + + h_L1PF_part_response_0p2_pt_barrel_ = ibooker.book1D("L1PFParticleResponse0p2VsPtBarrel", + "L1 PF Particle Response (#Delta R < 0.2) vs p_{T}, Barrel", + resVsPtDef.nbinsX, + resVsPtDef.xmin, + resVsPtDef.xmax); + + h_L1PF_part_response_0p2_pt_endcap_ = ibooker.book1D("L1PFParticleResponse0p2VsPtEndcap", + "L1 PF Particle Response (#Delta R < 0.2) vs p_{T}, Endcap", + resVsPtDef.nbinsX, + resVsPtDef.xmin, + resVsPtDef.xmax); + + h_L1PF_part_response_0p2_pt_ecnotk_ = + ibooker.book1D("L1PFParticleResponse0p2VsPtEndcapNoTk", + "L1 PF Particle Response (#Delta R < 0.2) vs p_{T}, Endcap No Tk", + resVsPtDef.nbinsX, + resVsPtDef.xmin, + resVsPtDef.xmax); + + h_L1PF_part_response_0p2_pt_hf_ = ibooker.book1D("L1PFParticleResponse0p2VsPtHF", + "L1 PF Particle Response (#Delta R < 0.2) vs p_{T}, HF", + resVsPtDef.nbinsX, + resVsPtDef.xmin, + resVsPtDef.xmax); + + h_L1PF_part_response_0p2_eta_ = ibooker.book1D("L1PFParticleResponse0p2VsEta", + "L1 PF Particle Response (#Delta R < 0.2) vs #eta", + resVsEtaDef.nbinsX, + resVsEtaDef.xmin, + resVsEtaDef.xmax); + + h_L1Puppi_part_response_0p2_pt_barrel_ = + ibooker.book1D("L1PUPPIParticleResponse0p2VsPtBarrel", + "L1 PUPPI Particle Response (#Delta R < 0.2) vs p_{T}, Barrel", + resVsPtDef.nbinsX, + resVsPtDef.xmin, + resVsPtDef.xmax); + + h_L1Puppi_part_response_0p2_pt_endcap_ = + ibooker.book1D("L1PUPPIParticleResponse0p2VsPtEndcap", + "L1 PUPPI Particle Response (#Delta R < 0.2) vs p_{T}, Endcap", + resVsPtDef.nbinsX, + resVsPtDef.xmin, + resVsPtDef.xmax); + + h_L1Puppi_part_response_0p2_pt_ecnotk_ = + ibooker.book1D("L1PUPPIParticleResponse0p2VsPtEndcapNoTk", + "L1 PUPPI Particle Response (#Delta R < 0.2) vs p_{T}, Endcap No Tk", + resVsPtDef.nbinsX, + resVsPtDef.xmin, + resVsPtDef.xmax); + + h_L1Puppi_part_response_0p2_pt_hf_ = ibooker.book1D("L1PUPPIParticleResponse0p2VsPtHF", + "L1 PUPPI Particle Response (#Delta R < 0.2) vs p_{T}, HF", + resVsPtDef.nbinsX, + resVsPtDef.xmin, + resVsPtDef.xmax); + + h_L1Puppi_part_response_0p2_eta_ = ibooker.book1D("L1PUPPIParticleResponse0p2VsEta", + "L1 PUPPI Particle Response (#Delta R < 0.2) vs #eta", + resVsEtaDef.nbinsX, + resVsEtaDef.xmin, + resVsEtaDef.xmax); + + h_L1PF_jet_response_pt_barrel_ = ibooker.book1D("L1PFJetResponseVsPtBarrel", + "L1 PF Jet Response vs p_{T}, Barrel", + resVsPtDef.nbinsX, + resVsPtDef.xmin, + resVsPtDef.xmax); + + h_L1PF_jet_response_pt_endcap_ = ibooker.book1D("L1PFJetResponseVsPtEndcap", + "L1 PF Jet Response vs p_{T}, Endcap", + resVsPtDef.nbinsX, + resVsPtDef.xmin, + resVsPtDef.xmax); + + h_L1PF_jet_response_pt_ecnotk_ = ibooker.book1D("L1PFJetResponseVsPtEndcapNoTk", + "L1 PF Jet Response vs p_{T}, Endcap No Tk", + resVsPtDef.nbinsX, + resVsPtDef.xmin, + resVsPtDef.xmax); + + h_L1PF_jet_response_pt_hf_ = ibooker.book1D( + "L1PFJetResponseVsPtHF", "L1 PF Jet Response vs p_{T}, HF", resVsPtDef.nbinsX, resVsPtDef.xmin, resVsPtDef.xmax); + + h_L1PF_jet_response_eta_ = ibooker.book1D( + "L1PFJetResponseVsEta", "L1 PF Jet Response vs #eta", resVsEtaDef.nbinsX, resVsEtaDef.xmin, resVsEtaDef.xmax); + + h_L1Puppi_jet_response_pt_barrel_ = ibooker.book1D("L1PUPPIJetResponseVsPtBarrel", + "L1 PUPPI Jet Response vs p_{T}, Barrel", + resVsPtDef.nbinsX, + resVsPtDef.xmin, + resVsPtDef.xmax); + + h_L1Puppi_jet_response_pt_endcap_ = ibooker.book1D("L1PUPPIJetResponseVsPtEndcap", + "L1 PUPPI Jet Response vs p_{T}, Endcap", + resVsPtDef.nbinsX, + resVsPtDef.xmin, + resVsPtDef.xmax); + + h_L1Puppi_jet_response_pt_ecnotk_ = ibooker.book1D("L1PUPPIJetResponseVsPtEndcapNoTk", + "L1 PUPPI Jet Response vs p_{T}, EndcapNoTk", + resVsPtDef.nbinsX, + resVsPtDef.xmin, + resVsPtDef.xmax); + + h_L1Puppi_jet_response_pt_hf_ = ibooker.book1D("L1PUPPIJetResponseVsPtHF", + "L1 PUPPI Jet Response vs p_{T}, HF", + resVsPtDef.nbinsX, + resVsPtDef.xmin, + resVsPtDef.xmax); + + h_L1Puppi_jet_response_eta_ = ibooker.book1D("L1PUPPIJetResponseVsEta", + "L1 PUPPI Jet Response vs #eta", + resVsEtaDef.nbinsX, + resVsEtaDef.xmin, + resVsEtaDef.xmax); + + //Resolution + + h_L1PF_part_resolution_0p2_pt_barrel_ = ibooker.book1D("L1PFParticleResolution0p2VsPtBarrel", + "L1 PF Particle Resolution (#Delta R < 0.2) vs p_{T}, Barrel", + resVsPtDef.nbinsX, + resVsPtDef.xmin, + resVsPtDef.xmax); + + h_L1PF_part_resolution_0p2_pt_endcap_ = ibooker.book1D("L1PFParticleResolution0p2VsPtEndcap", + "L1 PF Particle Resolution (#Delta R < 0.2) vs p_{T}, Endcap", + resVsPtDef.nbinsX, + resVsPtDef.xmin, + resVsPtDef.xmax); + + h_L1PF_part_resolution_0p2_pt_ecnotk_ = + ibooker.book1D("L1PFParticleResolution0p2VsPtEndcapNoTk", + "L1 PF Particle Resolution (#Delta R < 0.2) vs p_{T}, Endcap No Tk", + resVsPtDef.nbinsX, + resVsPtDef.xmin, + resVsPtDef.xmax); + + h_L1PF_part_resolution_0p2_pt_hf_ = ibooker.book1D("L1PFParticleResolution0p2VsPtHF", + "L1 PF Particle Resolution (#Delta R < 0.2) vs p_{T}, HF", + resVsPtDef.nbinsX, + resVsPtDef.xmin, + resVsPtDef.xmax); + + h_L1Puppi_part_resolution_0p2_pt_barrel_ = + ibooker.book1D("L1PUPPIParticleResolution0p2VsPtBarrel", + "L1 PUPPI Particle Resolution (#Delta R < 0.2) vs p_{T}, Barrel", + resVsPtDef.nbinsX, + resVsPtDef.xmin, + resVsPtDef.xmax); + + h_L1Puppi_part_resolution_0p2_pt_endcap_ = + ibooker.book1D("L1PUPPIParticleResolution0p2VsPtEndcap", + "L1 PUPPI Particle Resolution (#Delta R < 0.2) vs p_{T}, Endcap", + resVsPtDef.nbinsX, + resVsPtDef.xmin, + resVsPtDef.xmax); + + h_L1Puppi_part_resolution_0p2_pt_ecnotk_ = + ibooker.book1D("L1PUPPIParticleResolution0p2VsPtEndcapNoTk", + "L1 PUPPI Particle Resolution (#Delta R < 0.2) vs p_{T}, Endcap No Tk", + resVsPtDef.nbinsX, + resVsPtDef.xmin, + resVsPtDef.xmax); + + h_L1Puppi_part_resolution_0p2_pt_hf_ = ibooker.book1D("L1PUPPIParticleResolution0p2VsPtHF", + "L1 PUPPI Particle Resolution (#Delta R < 0.2) vs p_{T}, HF", + resVsPtDef.nbinsX, + resVsPtDef.xmin, + resVsPtDef.xmax); + + h_L1PF_jet_resolution_pt_barrel_ = ibooker.book1D("L1PFJetResolutionVsPtBarrel", + "L1 PF Jet Resolution vs p_{T}, Barrel", + resVsPtDef.nbinsX, + resVsPtDef.xmin, + resVsPtDef.xmax); + + h_L1PF_jet_resolution_pt_endcap_ = ibooker.book1D("L1PFJetResolutionVsPtEndcap", + "L1 PF Jet Resolution vs p_{T}, Endcap", + resVsPtDef.nbinsX, + resVsPtDef.xmin, + resVsPtDef.xmax); + + h_L1PF_jet_resolution_pt_ecnotk_ = ibooker.book1D("L1PFJetResolutionVsPtEndcapNoTk", + "L1 PF Jet Resolution vs p_{T}, Endcap No Tk", + resVsPtDef.nbinsX, + resVsPtDef.xmin, + resVsPtDef.xmax); + + h_L1PF_jet_resolution_pt_hf_ = ibooker.book1D("L1PFJetResolutionVsPtHF", + "L1 PF Jet Resolution vs p_{T}, HF", + resVsPtDef.nbinsX, + resVsPtDef.xmin, + resVsPtDef.xmax); + + h_L1Puppi_jet_resolution_pt_barrel_ = ibooker.book1D("L1PUPPIJetResolutionVsPtBarrel", + "L1 PUPPI Jet Resolution vs p_{T}, Barrel", + resVsPtDef.nbinsX, + resVsPtDef.xmin, + resVsPtDef.xmax); + + h_L1Puppi_jet_resolution_pt_endcap_ = ibooker.book1D("L1PUPPIJetResolutionVsPtEndcap", + "L1 PUPPI Jet Resolution vs p_{T}, Endcap", + resVsPtDef.nbinsX, + resVsPtDef.xmin, + resVsPtDef.xmax); + + h_L1Puppi_jet_resolution_pt_ecnotk_ = ibooker.book1D("L1PUPPIJetResolutionVsPtEndcapNoTk", + "L1 PUPPI Jet Resolution vs p_{T}, EndcapNoTk", + resVsPtDef.nbinsX, + resVsPtDef.xmin, + resVsPtDef.xmax); + + h_L1Puppi_jet_resolution_pt_hf_ = ibooker.book1D("L1PUPPIJetResolutionVsPtHF", + "L1 PUPPI Jet Resolution vs p_{T}, HF", + resVsPtDef.nbinsX, + resVsPtDef.xmin, + resVsPtDef.xmax); + + ibooker.cd(); + + return; +} + +// +// -------------------------------------- endRun -------------------------------------------- +// +void L1TPhase2CorrelatorOffline::dqmEndRun(const edm::Run& run, const edm::EventSetup& iSetup) { + computeResponseResolution(); +} + +void L1TPhase2CorrelatorOffline::computeResponseResolution() { + std::vector monElementstoComputeIn = {h_L1PF_part_ptratio_0p2_vs_pt_barrel_, + h_L1PF_part_ptratio_0p2_vs_pt_endcap_, + h_L1PF_part_ptratio_0p2_vs_pt_ecnotk_, + h_L1PF_part_ptratio_0p2_vs_pt_hf_, + h_L1PF_part_ptratio_0p2_vs_eta_, + h_L1Puppi_part_ptratio_0p2_vs_pt_barrel_, + h_L1Puppi_part_ptratio_0p2_vs_pt_endcap_, + h_L1Puppi_part_ptratio_0p2_vs_pt_ecnotk_, + h_L1Puppi_part_ptratio_0p2_vs_pt_hf_, + h_L1Puppi_part_ptratio_0p2_vs_eta_, + h_L1PF_jet_ptratio_vs_pt_barrel_, + h_L1PF_jet_ptratio_vs_pt_endcap_, + h_L1PF_jet_ptratio_vs_pt_ecnotk_, + h_L1PF_jet_ptratio_vs_pt_hf_, + h_L1PF_jet_ptratio_vs_eta_, + h_L1Puppi_jet_ptratio_vs_pt_barrel_, + h_L1Puppi_jet_ptratio_vs_pt_endcap_, + h_L1Puppi_jet_ptratio_vs_pt_ecnotk_, + h_L1Puppi_jet_ptratio_vs_pt_hf_, + h_L1Puppi_jet_ptratio_vs_eta_}; + std::vector monElementstoComputeResp = {h_L1PF_part_response_0p2_pt_barrel_, + h_L1PF_part_response_0p2_pt_endcap_, + h_L1PF_part_response_0p2_pt_ecnotk_, + h_L1PF_part_response_0p2_pt_hf_, + h_L1PF_part_response_0p2_eta_, + h_L1Puppi_part_response_0p2_pt_barrel_, + h_L1Puppi_part_response_0p2_pt_endcap_, + h_L1Puppi_part_response_0p2_pt_ecnotk_, + h_L1Puppi_part_response_0p2_pt_hf_, + h_L1Puppi_part_response_0p2_eta_, + h_L1PF_jet_response_pt_barrel_, + h_L1PF_jet_response_pt_endcap_, + h_L1PF_jet_response_pt_ecnotk_, + h_L1PF_jet_response_pt_hf_, + h_L1PF_jet_response_eta_, + h_L1Puppi_jet_response_pt_barrel_, + h_L1Puppi_jet_response_pt_endcap_, + h_L1Puppi_jet_response_pt_ecnotk_, + h_L1Puppi_jet_response_pt_hf_, + h_L1Puppi_jet_response_eta_}; + std::vector monElementstoComputeResol = {h_L1PF_part_resolution_0p2_pt_barrel_, + h_L1PF_part_resolution_0p2_pt_endcap_, + h_L1PF_part_resolution_0p2_pt_ecnotk_, + h_L1PF_part_resolution_0p2_pt_hf_, + nullptr, + h_L1Puppi_part_resolution_0p2_pt_barrel_, + h_L1Puppi_part_resolution_0p2_pt_endcap_, + h_L1Puppi_part_resolution_0p2_pt_ecnotk_, + h_L1Puppi_part_resolution_0p2_pt_hf_, + nullptr, + h_L1PF_jet_resolution_pt_barrel_, + h_L1PF_jet_resolution_pt_endcap_, + h_L1PF_jet_resolution_pt_ecnotk_, + h_L1PF_jet_resolution_pt_hf_, + nullptr, + h_L1Puppi_jet_resolution_pt_barrel_, + h_L1Puppi_jet_resolution_pt_endcap_, + h_L1Puppi_jet_resolution_pt_ecnotk_, + h_L1Puppi_jet_resolution_pt_hf_, + nullptr}; + + for (unsigned int i = 0; i < monElementstoComputeIn.size(); i++) { + if (monElementstoComputeIn[i] != nullptr && monElementstoComputeResp[i] != nullptr) { + medianResponseCorrResolution( + monElementstoComputeIn[i], monElementstoComputeResp[i], monElementstoComputeResol[i]); + } + } +} + +void L1TPhase2CorrelatorOffline::medianResponseCorrResolution(MonitorElement* in2D, + MonitorElement* response, + MonitorElement* resolution) { + auto hbase = in2D->getTH2F(); + auto hresp = response->getTH1F(); + if (hbase != nullptr && hresp != nullptr) { + if (hbase->GetNbinsX() == hresp->GetNbinsX()) { + TDirectory threadsafeDir = + TDirectory(((std::string)(hbase->GetName()) + "dirL1TPhase2CorrelatorOffline").c_str(), + ((std::string)(hbase->GetName()) + "dirL1TPhase2CorrelatorOffline").c_str()); + TDirectory::TContext context(gDirectory, &threadsafeDir); + auto med = hbase->QuantilesX(0.5, "_qx"); + TGraph* ptrecgen = new TGraph(hbase->GetNbinsX()); + for (int ib = 1; ib < hbase->GetNbinsX() + 1; ib++) { + float corr = med->GetBinContent(ib); + float xval = hbase->GetXaxis()->GetBinCenter(ib); + ptrecgen->SetPoint(ib - 1, xval * corr, xval); + hresp->SetBinContent(ib, corr); + } + delete med; + if (resolution != nullptr) { + auto hresol = resolution->getTH1F(); + if (hresol != nullptr) { + if (hbase->GetNbinsX() == hresol->GetNbinsX()) { + ptrecgen->Sort(); + TH2F* ch = new TH2F(*hbase); + ch->Reset("ICE"); + for (int ibx = 1; ibx < ch->GetNbinsX() + 1; ibx++) { + float xval = hbase->GetXaxis()->GetBinCenter(ibx); + for (int iby = 1; iby < ch->GetNbinsY() + 1; iby++) { + float yval = hbase->GetYaxis()->GetBinCenter(iby); + float newyval = ptrecgen->Eval(yval * xval) / xval; + int ycb = ch->FindBin(xval, newyval); + ch->SetBinContent(ycb, ch->GetBinContent(ycb) + hbase->GetBinContent(ibx, iby)); + } + } + delete ptrecgen; + auto qc = ch->QuantilesX(0.5, "_qc"); + auto qhi = ch->QuantilesX(0.84, "_qhi"); + auto qlo = ch->QuantilesX(0.16, "_qlo"); + delete ch; + for (int ibx = 1; ibx < hbase->GetNbinsX() + 1; ibx++) { + hresol->SetBinContent( + ibx, qc->GetBinContent(ibx) > 0.2 ? (qhi->GetBinContent(ibx) - qlo->GetBinContent(ibx)) / 2. : 0.); + } + delete qc; + delete qhi; + delete qlo; + } + } + } else { + delete ptrecgen; + } + } + } +} + +// define this as a plug-in +DEFINE_FWK_MODULE(L1TPhase2CorrelatorOffline); diff --git a/DQMOffline/L1Trigger/src/L1TPhase2OuterTrackerTkMET.cc b/DQMOffline/L1Trigger/src/L1TPhase2OuterTrackerTkMET.cc new file mode 100644 index 0000000000000..130126b4cc49c --- /dev/null +++ b/DQMOffline/L1Trigger/src/L1TPhase2OuterTrackerTkMET.cc @@ -0,0 +1,297 @@ +// Package: SiOuterTracker +// Class: SiOuterTracker +// +// Author: Emily MacDonald (emily.kaelyn.macdonald@cern.ch) + +// system include files +#include +#include +#include +#include +#include +#include + +// user include files +#include "DataFormats/Common/interface/DetSetVector.h" +#include "DataFormats/Common/interface/DetSetVectorNew.h" +#include "DataFormats/Common/interface/Ptr.h" +#include "DataFormats/Common/interface/Ref.h" +#include "DataFormats/L1TrackTrigger/interface/TTCluster.h" +#include "DataFormats/L1TrackTrigger/interface/TTStub.h" +#include "DataFormats/L1TrackTrigger/interface/TTTrack.h" +#include "DataFormats/SiStripDetId/interface/StripSubdetector.h" +#include "DataFormats/TrackerCommon/interface/TrackerTopology.h" + +#include "FWCore/MessageLogger/interface/MessageLogger.h" +#include "FWCore/ServiceRegistry/interface/Service.h" +#include "Geometry/Records/interface/TrackerDigiGeometryRecord.h" +#include "Geometry/CommonDetUnit/interface/GeomDet.h" +#include "Geometry/TrackerGeometryBuilder/interface/TrackerGeometry.h" +#include "Geometry/TrackerGeometryBuilder/interface/StripGeomDetUnit.h" +#include "SimDataFormats/TrackingAnalysis/interface/TrackingParticle.h" +#include "SimTracker/TrackTriggerAssociation/interface/TTStubAssociationMap.h" +#include "SimTracker/TrackTriggerAssociation/interface/TTTrackAssociationMap.h" +#include "SimTracker/TrackTriggerAssociation/interface/TTClusterAssociationMap.h" + +#include "DQMOffline/L1Trigger/interface/L1TPhase2OuterTrackerTkMET.h" + +// constructors and destructor +L1TPhase2OuterTrackerTkMET::L1TPhase2OuterTrackerTkMET(const edm::ParameterSet& iConfig) + : conf_(iConfig), m_topoToken(esConsumes()) { + topFolderName_ = conf_.getParameter("TopFolderName"); + ttTrackToken_ = + consumes > >(conf_.getParameter("TTTracksTag")); + pvToken = consumes(conf_.getParameter("L1VertexInputTag")); + + maxZ0 = conf_.getParameter("maxZ0"); + DeltaZ = conf_.getParameter("DeltaZ"); + chi2dofMax = conf_.getParameter("chi2dofMax"); + bendchi2Max = conf_.getParameter("bendchi2Max"); + minPt = conf_.getParameter("minPt"); + nStubsmin = iConfig.getParameter("nStubsmin"); + nStubsPSmin = iConfig.getParameter("nStubsPSmin"); + maxPt = conf_.getParameter("maxPt"); + maxEta = conf_.getParameter("maxEta"); + HighPtTracks = iConfig.getParameter("HighPtTracks"); +} + +L1TPhase2OuterTrackerTkMET::~L1TPhase2OuterTrackerTkMET() { + // do anything here that needs to be done at desctruction time + // (e.g. close files, deallocate resources etc.) +} + +// member functions + +// ------------ method called for each event ------------ +void L1TPhase2OuterTrackerTkMET::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) { + // L1 Primaries + edm::Handle L1VertexHandle; + iEvent.getByToken(pvToken, L1VertexHandle); + + edm::Handle > > TTTrackHandle; + iEvent.getByToken(ttTrackToken_, TTTrackHandle); + + // for PS stubs + // Tracker Topology + const TrackerTopology* const tTopo = &iSetup.getData(m_topoToken); + + // Adding protection + if (!TTTrackHandle.isValid()) { + edm::LogWarning("L1TPhase2OuterTrackerTkMET") << "cant find tracks" << std::endl; + return; + } + if (!L1VertexHandle.isValid()) { + edm::LogWarning("L1TPhase2OuterTrackerTkMET") << "cant find vertex" << std::endl; + return; + } + float sumPx = 0; + float sumPy = 0; + float etTot = 0; + double sumPx_PU = 0; + double sumPy_PU = 0; + double etTot_PU = 0; + int nTracks_counter = 0; + + float zVTX = L1VertexHandle->begin()->zvertex(); + unsigned int tkCnt = 0; + for (const auto& trackIter : *TTTrackHandle) { + edm::Ptr > tempTrackPtr(TTTrackHandle, tkCnt++); /// Make the pointer + float pt = tempTrackPtr->momentum().perp(); + float phi = tempTrackPtr->momentum().phi(); + float eta = tempTrackPtr->momentum().eta(); + std::vector >, TTStub > > + theStubs = trackIter.getStubRefs(); + int nstubs = (int)theStubs.size(); + + float chi2dof = tempTrackPtr->chi2Red(); + float bendchi2 = tempTrackPtr->stubPtConsistency(); + float z0 = tempTrackPtr->z0(); + + if (pt < minPt || fabs(z0) > maxZ0 || fabs(eta) > maxEta || chi2dof > chi2dofMax || bendchi2 > bendchi2Max) + continue; + if (maxPt > 0 && pt > maxPt) { + if (HighPtTracks == 0) + continue; // ignore these very high PT tracks: truncate + if (HighPtTracks == 1) + pt = maxPt; // saturate + } + + int nPS = 0.; // number of stubs in PS modules + // loop over the stubs + for (unsigned int istub = 0; istub < (unsigned int)theStubs.size(); istub++) { + DetId detId(theStubs.at(istub)->getDetId()); + if (detId.det() == DetId::Detector::Tracker) { + if ((detId.subdetId() == StripSubdetector::TOB && tTopo->tobLayer(detId) <= 3) || + (detId.subdetId() == StripSubdetector::TID && tTopo->tidRing(detId) <= 9)) + nPS++; + } + } + + if (nstubs < nStubsmin || nPS < nStubsPSmin) + continue; + + // construct deltaZ cut to be based on track eta + if (fabs(eta) >= 0 && fabs(eta) < 0.7) + DeltaZ = 0.4; + else if (fabs(eta) >= 0.7 && fabs(eta) < 1.0) + DeltaZ = 0.6; + else if (fabs(eta) >= 1.0 && fabs(eta) < 1.2) + DeltaZ = 0.76; + else if (fabs(eta) >= 1.2 && fabs(eta) < 1.6) + DeltaZ = 1.0; + else if (fabs(eta) >= 1.6 && fabs(eta) < 2.0) + DeltaZ = 1.7; + else if (fabs(eta) >= 2.0 && fabs(eta) <= 2.4) + DeltaZ = 2.2; + + if (fabs(z0 - zVTX) <= DeltaZ) { + nTracks_counter++; + Track_Pt->Fill(pt); + Track_NStubs->Fill(nstubs); + Track_NPSstubs->Fill(nPS); + Track_Eta->Fill(eta); + Track_VtxZ->Fill(z0); + Track_Chi2Dof->Fill(chi2dof); + Track_BendChi2->Fill(bendchi2); + + sumPx += pt * cos(phi); + sumPy += pt * sin(phi); + etTot += pt; + } else { // PU sums + sumPx_PU += pt * cos(phi); + sumPy_PU += pt * sin(phi); + etTot_PU += pt; + } + } // end loop over tracks + + Track_N->Fill(nTracks_counter); + float et = sqrt(sumPx * sumPx + sumPy * sumPy); + double etmiss_PU = sqrt(sumPx_PU * sumPx_PU + sumPy_PU * sumPy_PU); + + math::XYZTLorentzVector missingEt(-sumPx, -sumPy, 0, et); + + TkMET_QualityCuts->Fill(missingEt.Pt()); + TkMET_PU->Fill(etmiss_PU); + +} // end of method + +// ------------ method called once each job just before starting event loop ------------ +//Creating all histograms for DQM file output +void L1TPhase2OuterTrackerTkMET::bookHistograms(DQMStore::IBooker& iBooker, + edm::Run const& run, + edm::EventSetup const& es) { + std::string HistoName; + iBooker.setCurrentFolder(topFolderName_ + "/TkMET_Tracks/"); + + // Num of L1Tracks in tkMET selection + HistoName = "Track_N"; + edm::ParameterSet psTrack_N = conf_.getParameter("TH1_NTracks"); + Track_N = iBooker.book1D(HistoName, + HistoName, + psTrack_N.getParameter("Nbinsx"), + psTrack_N.getParameter("xmin"), + psTrack_N.getParameter("xmax")); + Track_N->setAxisTitle("# L1 Tracks", 1); + Track_N->setAxisTitle("# Events", 2); + + //Pt of the tracks + edm::ParameterSet psTrack_Pt = conf_.getParameter("TH1_Track_Pt"); + HistoName = "Track_Pt"; + Track_Pt = iBooker.book1D(HistoName, + HistoName, + psTrack_Pt.getParameter("Nbinsx"), + psTrack_Pt.getParameter("xmin"), + psTrack_Pt.getParameter("xmax")); + Track_Pt->setAxisTitle("p_{T} [GeV]", 1); + Track_Pt->setAxisTitle("# L1 Tracks", 2); + + //Eta + edm::ParameterSet psTrack_Eta = conf_.getParameter("TH1_Track_Eta"); + HistoName = "Track_Eta"; + Track_Eta = iBooker.book1D(HistoName, + HistoName, + psTrack_Eta.getParameter("Nbinsx"), + psTrack_Eta.getParameter("xmin"), + psTrack_Eta.getParameter("xmax")); + Track_Eta->setAxisTitle("#eta", 1); + Track_Eta->setAxisTitle("# L1 Tracks", 2); + + //VtxZ + edm::ParameterSet psTrack_VtxZ = conf_.getParameter("TH1_Track_VtxZ"); + HistoName = "Track_VtxZ"; + Track_VtxZ = iBooker.book1D(HistoName, + HistoName, + psTrack_VtxZ.getParameter("Nbinsx"), + psTrack_VtxZ.getParameter("xmin"), + psTrack_VtxZ.getParameter("xmax")); + Track_VtxZ->setAxisTitle("L1 Track vertex position z [cm]", 1); + Track_VtxZ->setAxisTitle("# L1 Tracks", 2); + + //chi2dof + edm::ParameterSet psTrack_Chi2Dof = conf_.getParameter("TH1_Track_Chi2Dof"); + HistoName = "Track_Chi2Dof"; + Track_Chi2Dof = iBooker.book1D(HistoName, + HistoName, + psTrack_Chi2Dof.getParameter("Nbinsx"), + psTrack_Chi2Dof.getParameter("xmin"), + psTrack_Chi2Dof.getParameter("xmax")); + Track_Chi2Dof->setAxisTitle("L1 Track #chi^{2}/D.O.F.", 1); + Track_Chi2Dof->setAxisTitle("# L1 Tracks", 2); + + //bend chi2 + edm::ParameterSet psTrack_BendChi2 = conf_.getParameter("TH1_Track_BendChi2"); + HistoName = "Track_BendChi2"; + Track_BendChi2 = iBooker.book1D(HistoName, + HistoName, + psTrack_BendChi2.getParameter("Nbinsx"), + psTrack_BendChi2.getParameter("xmin"), + psTrack_BendChi2.getParameter("xmax")); + Track_BendChi2->setAxisTitle("L1 Track Bend #chi^{2}", 1); + Track_BendChi2->setAxisTitle("# L1 Tracks", 2); + + //nstubs + edm::ParameterSet psTrack_NStubs = conf_.getParameter("TH1_Track_NStubs"); + HistoName = "Track_NStubs"; + Track_NStubs = iBooker.book1D(HistoName, + HistoName, + psTrack_NStubs.getParameter("Nbinsx"), + psTrack_NStubs.getParameter("xmin"), + psTrack_NStubs.getParameter("xmax")); + Track_NStubs->setAxisTitle("# L1 Stubs", 1); + Track_NStubs->setAxisTitle("# L1 Tracks", 2); + + //nPSstubs + edm::ParameterSet psTrack_NPSstubs = conf_.getParameter("TH1_Track_NPSstubs"); + HistoName = "Track_NPSstubs"; + Track_NPSstubs = iBooker.book1D(HistoName, + HistoName, + psTrack_NPSstubs.getParameter("Nbinsx"), + psTrack_NPSstubs.getParameter("xmin"), + psTrack_NPSstubs.getParameter("xmax")); + Track_NPSstubs->setAxisTitle("# PS Stubs", 1); + Track_NPSstubs->setAxisTitle("# L1 Tracks", 2); + + iBooker.setCurrentFolder(topFolderName_ + "/TkMET"); + //loose tkMET + edm::ParameterSet psTrack_TkMET = conf_.getParameter("TH1_Track_TkMET"); + HistoName = "TkMET_QualityCuts"; + TkMET_QualityCuts = iBooker.book1D(HistoName, + HistoName, + psTrack_TkMET.getParameter("Nbinsx"), + psTrack_TkMET.getParameter("xmin"), + psTrack_TkMET.getParameter("xmax")); + TkMET_QualityCuts->setAxisTitle("L1 Track MET [GeV]", 1); + TkMET_QualityCuts->setAxisTitle("# Events", 2); + + //tkMET -- PU only + HistoName = "TkMET_PU"; + TkMET_PU = iBooker.book1D(HistoName, + HistoName, + psTrack_TkMET.getParameter("Nbinsx"), + psTrack_TkMET.getParameter("xmin"), + psTrack_TkMET.getParameter("xmax")); + TkMET_PU->setAxisTitle("L1 Track MET (PU only) [GeV]", 1); + TkMET_PU->setAxisTitle("# Events", 2); +} //end of method + +DEFINE_FWK_MODULE(L1TPhase2OuterTrackerTkMET); diff --git a/DQMOffline/L1Trigger/test/runDQMOffline_L1TMuonEfficiency_cfg.py b/DQMOffline/L1Trigger/test/runDQMOffline_L1TMuonEfficiency_cfg.py index 3cbd699ae0338..14293d317bcc0 100644 --- a/DQMOffline/L1Trigger/test/runDQMOffline_L1TMuonEfficiency_cfg.py +++ b/DQMOffline/L1Trigger/test/runDQMOffline_L1TMuonEfficiency_cfg.py @@ -3,7 +3,6 @@ process = cms.Process("L1TDQMOffline") import os import sys -import commands process.load("FWCore.MessageLogger.MessageLogger_cfi") process.load("DQMServices.Core.DQM_cfg") diff --git a/DQMOffline/Muon/python/gem_dqm_offline_client_cff.py b/DQMOffline/Muon/python/gem_dqm_offline_client_cff.py index 1bf2ef27ff898..844b0629f67fc 100644 --- a/DQMOffline/Muon/python/gem_dqm_offline_client_cff.py +++ b/DQMOffline/Muon/python/gem_dqm_offline_client_cff.py @@ -1,7 +1,10 @@ import FWCore.ParameterSet.Config as cms +from DQM.GEM.GEMDQMHarvester_cfi import * from DQMOffline.Muon.gemEfficiencyHarvester_cfi import * gemClients = cms.Sequence( + GEMDQMHarvester * gemEfficiencyHarvesterTightGlb * - gemEfficiencyHarvesterSta) + gemEfficiencyHarvesterSta + ) diff --git a/DQMOffline/Muon/python/gem_dqm_offline_client_cosmics_cff.py b/DQMOffline/Muon/python/gem_dqm_offline_client_cosmics_cff.py index 1a6192a49b736..43156a30fd951 100644 --- a/DQMOffline/Muon/python/gem_dqm_offline_client_cosmics_cff.py +++ b/DQMOffline/Muon/python/gem_dqm_offline_client_cosmics_cff.py @@ -1,7 +1,10 @@ import FWCore.ParameterSet.Config as cms +from DQM.GEM.GEMDQMHarvester_cfi import * from DQMOffline.Muon.gemEfficiencyHarvesterCosmics_cfi import * gemClientsCosmics = cms.Sequence( + GEMDQMHarvester * gemEfficiencyHarvesterCosmics * - gemEfficiencyHarvesterCosmicsOneLeg) + gemEfficiencyHarvesterCosmicsOneLeg + ) diff --git a/DQMOffline/Muon/python/gem_dqm_offline_source_cff.py b/DQMOffline/Muon/python/gem_dqm_offline_source_cff.py index 177777879b265..b10143026a294 100644 --- a/DQMOffline/Muon/python/gem_dqm_offline_source_cff.py +++ b/DQMOffline/Muon/python/gem_dqm_offline_source_cff.py @@ -1,8 +1,16 @@ import FWCore.ParameterSet.Config as cms +from DQM.GEM.GEMDigiSource_cfi import * +from DQM.GEM.GEMRecHitSource_cfi import * + from DQMOffline.Muon.gemEfficiencyAnalyzer_cfi import * +GEMDigiSource.modeRelVal = True +GEMRecHitSource.modeRelVal = True + gemSources = cms.Sequence( + GEMDigiSource * + GEMRecHitSource * gemEfficiencyAnalyzerTightGlbSeq * gemEfficiencyAnalyzerStaSeq ) diff --git a/DQMOffline/Muon/python/gem_dqm_offline_source_cosmics_cff.py b/DQMOffline/Muon/python/gem_dqm_offline_source_cosmics_cff.py index 51ffa1322cb89..062fe3eb07ec4 100644 --- a/DQMOffline/Muon/python/gem_dqm_offline_source_cosmics_cff.py +++ b/DQMOffline/Muon/python/gem_dqm_offline_source_cosmics_cff.py @@ -1,7 +1,16 @@ import FWCore.ParameterSet.Config as cms +from DQM.GEM.GEMDigiSource_cfi import * +from DQM.GEM.GEMRecHitSource_cfi import * + from DQMOffline.Muon.gemEfficiencyAnalyzerCosmics_cfi import * +GEMDigiSource.modeRelVal = True +GEMRecHitSource.modeRelVal = True + gemSourcesCosmics = cms.Sequence( + GEMDigiSource * + GEMRecHitSource * gemEfficiencyAnalyzerCosmics * - gemEfficiencyAnalyzerCosmicsOneLeg) + gemEfficiencyAnalyzerCosmicsOneLeg + ) diff --git a/DQMServices/Components/scripts/dqmiodumpmetadata.py b/DQMServices/Components/scripts/dqmiodumpmetadata.py index feffbc1115e20..c02d6577e030e 100755 --- a/DQMServices/Components/scripts/dqmiodumpmetadata.py +++ b/DQMServices/Components/scripts/dqmiodumpmetadata.py @@ -14,13 +14,13 @@ f = uproot.open(args.filename) things = f.keys() -if b'Indices;1' in things: - indices = f[b'Indices'] - runs = indices.array(b"Run") - lumis = indices.array(b"Lumi") - firstindex = indices.array(b"FirstIndex") - lastindex = indices.array(b"LastIndex") - types = indices.array(b"Type") +if 'Indices;1' in things: + indices = f['Indices'] + runs = indices['Run'].array() + lumis = indices['Lumi'].array() + firstindex = indices['FirstIndex'].array() + lastindex = indices['LastIndex'].array() + types = indices['Type'].array() counts = defaultdict(lambda: 0) for run, lumi, first, last, type in zip(runs, lumis, firstindex, lastindex, types): @@ -54,5 +54,3 @@ def showrow(): else: print("This does not look like DQMIO data.") - - diff --git a/DQMServices/Components/scripts/dqmiolistmes.py b/DQMServices/Components/scripts/dqmiolistmes.py index 9e462a0240708..c03f82db56613 100755 --- a/DQMServices/Components/scripts/dqmiolistmes.py +++ b/DQMServices/Components/scripts/dqmiolistmes.py @@ -19,13 +19,13 @@ f = uproot.open(args.filename) things = f.keys() -if b'Indices;1' in things: - indices = f[b'Indices'] - runs = indices.array(b"Run") - lumis = indices.array(b"Lumi") - firstindex = indices.array(b"FirstIndex") - lastindex = indices.array(b"LastIndex") - types = indices.array(b"Type") +if 'Indices;1' in things: + indices = f['Indices'] + runs = indices['Run'].array() + lumis = indices['Lumi'].array() + firstindex = indices['FirstIndex'].array() + lastindex = indices['LastIndex'].array() + types = indices['Type'].array() # If run is not provided, print all available runs in a given file. if args.r == None or args.r < 0: @@ -36,25 +36,24 @@ exit() treenames = [ # order matters! - b"Ints", - b"Floats", - b"Strings", - b"TH1Fs", - b"TH1Ss", - b"TH1Ds", - b"TH2Fs", - b"TH2Ss", - b"TH2Ds", - b"TH3Fs", - b"TProfiles", - b"TProfile2Ds" + "Ints", + "Floats", + "Strings", + "TH1Fs", + "TH1Ss", + "TH1Ds", + "TH2Fs", + "TH2Ss", + "TH2Ds", + "TH3Fs", + "TProfiles", + "TProfile2Ds" ] - trees = [f[name][b"FullName"].array() for name in treenames] + trees = [f[name]["FullName"].array() for name in treenames] for run, lumi, first, last, type in zip(runs, lumis, firstindex, lastindex, types): if run == args.r and lumi == args.l: for i in range(first, int(last + 1)): # In DQMIO both ranges are inclusive - print(trees[type][i].decode()) + print(trees[type][i]) else: print("This does not look like DQMIO data.") - diff --git a/DQMServices/Components/test/test_fastHaddMerge.py b/DQMServices/Components/test/test_fastHaddMerge.py index 993b69228f327..c57bca239c12d 100644 --- a/DQMServices/Components/test/test_fastHaddMerge.py +++ b/DQMServices/Components/test/test_fastHaddMerge.py @@ -10,7 +10,7 @@ from builtins import range from optparse import OptionParser import sys -import commands +import subprocess import re word2num = {'One': 1, 'Two': 2, 'Ten': 10, 'Twenty': 20, 'Fifty': 50} @@ -88,7 +88,7 @@ def createIdenticalFiles(self): f.Close() print('Wrote %d histograms in %d folders' % (len(self.histos_), len(self.folders_))) for i in range(1, self.numFiles_): - commands.getoutput("cp %s_0.root %s_%d.root" % (self.prefix_, + subprocess.getoutput("cp %s_0.root %s_%d.root" % (self.prefix_, self.prefix_, i)) print('x') diff --git a/DQMServices/Core/interface/MonitorElement.h b/DQMServices/Core/interface/MonitorElement.h index 4b0cd2e890650..4f070717ef2a7 100644 --- a/DQMServices/Core/interface/MonitorElement.h +++ b/DQMServices/Core/interface/MonitorElement.h @@ -26,6 +26,7 @@ #include "TAxis.h" #include +#include #include #include #include @@ -136,9 +137,8 @@ namespace dqm::impl { }; private: - MutableMonitorElementData *mutable_; // only set if this is a mutable copy of this ME + std::shared_ptr mutable_; // only set if this is a mutable copy of this ME // there are no immutable MEs at this time, but we might need them in the future. - bool is_owned_; // true if we are responsible for deleting the mutable object. /** * To do anything to the MEs data, one needs to obtain an access object. * This object will contain the lock guard if one is needed. We differentiate @@ -176,7 +176,7 @@ namespace dqm::impl { // new ME. The new ME will own this data. MonitorElement(MonitorElementData &&data); // Create new ME and take ownership of this data. - MonitorElement(MutableMonitorElementData *data); + MonitorElement(std::shared_ptr data); // Create a new ME sharing data with this existing ME. MonitorElement(MonitorElement *me); @@ -184,13 +184,13 @@ namespace dqm::impl { // is owned by the returned value. MonitorElementData cloneMEData(); - // Remove access and ownership to the data. The flag is used for a sanity check. - MutableMonitorElementData *release(bool expectOwned); + // Remove access to the data. + std::shared_ptr release(); // re-initialize this ME as a shared copy of the other. void switchData(MonitorElement *other); // re-initialize taking ownership of this data. - void switchData(MutableMonitorElementData *data); + void switchData(std::shared_ptr data); // Replace the ROOT object in this ME's data with the new object, taking // ownership. The old object is deleted. diff --git a/DQMServices/Core/src/DQMStore.cc b/DQMServices/Core/src/DQMStore.cc index 01aa1b3c1e1f1..acdc64f587513 100644 --- a/DQMServices/Core/src/DQMStore.cc +++ b/DQMServices/Core/src/DQMStore.cc @@ -338,7 +338,7 @@ namespace dqm::implementation { MonitorElement* oldme = *proto; assert(oldme->getScope() == key.scope_); prototypes.erase(proto); - auto medata = oldme->release(/* expectOwned */ true); // destroy the ME, get its data. + auto medata = oldme->release(); // destroy the ME, get its data. // in this situation, nobody should be filling the ME concurrently. medata->data_.key_.id_ = key.id_; // We reuse the ME object here, even if we don't have to. This ensures @@ -408,7 +408,7 @@ namespace dqm::implementation { // reuse that. MonitorElement* oldme = *proto; prototypes.erase(proto); - auto medata = oldme->release(/* expectOwned */ true); // destroy the ME, get its data. + auto medata = oldme->release(); // destroy the ME, get its data. // in this situation, nobody should be filling the ME concurrently. medata->data_.key_.id_ = edm::LuminosityBlockID(run, lumi); // We reuse the ME object here, even if we don't have to. This ensures @@ -518,7 +518,7 @@ namespace dqm::implementation { if (me->isValid() && checkScope(me->getScope()) == true) { // if we left the scope, simply release the data. debugTrackME("leaveLumi (release)", me, nullptr); - me->release(/* expectOwned */ false); + me->release(); } } } @@ -576,7 +576,7 @@ namespace dqm::implementation { meset.clear(); for (MonitorElement* me : torecycle) { - auto medata = me->release(/* expectOwned */ true); // destroy the ME, get its data. + auto medata = me->release(); // destroy the ME, get its data. medata->data_.key_.id_ = edm::LuminosityBlockID(); // prototype // We reuse the ME object here, even if we don't have to. This ensures // that when running single-threaded without concurrent lumis/runs, diff --git a/DQMServices/Core/src/MonitorElement.cc b/DQMServices/Core/src/MonitorElement.cc index 5f096a90aa0ec..cb68f9ad21864 100644 --- a/DQMServices/Core/src/MonitorElement.cc +++ b/DQMServices/Core/src/MonitorElement.cc @@ -35,12 +35,11 @@ namespace dqm::impl { } MonitorElement::MonitorElement(MonitorElementData &&data) { - this->mutable_ = new MutableMonitorElementData(); + this->mutable_ = std::make_shared(); this->mutable_->data_ = std::move(data); - this->is_owned_ = true; syncCoreObject(); } - MonitorElement::MonitorElement(MutableMonitorElementData *data) { switchData(data); } + MonitorElement::MonitorElement(std::shared_ptr data) { switchData(std::move(data)); } MonitorElement::MonitorElement(MonitorElement *me) { switchData(me); } MonitorElementData MonitorElement::cloneMEData() { @@ -54,25 +53,20 @@ namespace dqm::impl { return out; } - MutableMonitorElementData *MonitorElement::release(bool expectOwned) { - assert(this->is_owned_ == expectOwned); - MutableMonitorElementData *data = this->mutable_; - this->mutable_ = nullptr; - this->is_owned_ = false; - assert(!expectOwned || data); + std::shared_ptr MonitorElement::release() { + auto data = this->mutable_; + this->mutable_.reset(); return data; } void MonitorElement::switchData(MonitorElement *other) { assert(other); this->mutable_ = other->mutable_; - this->is_owned_ = false; syncCoreObject(); } - void MonitorElement::switchData(MutableMonitorElementData *data) { - this->mutable_ = data; - this->is_owned_ = true; + void MonitorElement::switchData(std::shared_ptr data) { + this->mutable_ = std::move(data); syncCoreObject(); } @@ -150,10 +144,7 @@ namespace dqm::impl { } } - MonitorElement::~MonitorElement() { - if (is_owned_) - delete mutable_; - } + MonitorElement::~MonitorElement() {} //utility function to check the consistency of the axis labels //taken from TH1::CheckBinLabels which is not public diff --git a/DQMServices/Demo/test/runtests.sh b/DQMServices/Demo/test/runtests.sh index 7d018032a7d38..6c94d32c7b88c 100755 --- a/DQMServices/Demo/test/runtests.sh +++ b/DQMServices/Demo/test/runtests.sh @@ -72,7 +72,7 @@ dqmiodumpmetadata.py merged.root | grep -q '4 runs, 12 lumisections' rootlist () { python3 -c ' import uproot -for k in uproot.open("'"$1"'").allkeys(): print(k.decode())' +for k in uproot.open("'"$1"'").keys(): print(k)' } # we need to exclude MEs filled on run and lumi boundaries, since the split job *does* see a different number of begin/end run/lumi transitions. diff --git a/DQMServices/FileIO/plugins/DQMFileSaverPB.cc b/DQMServices/FileIO/plugins/DQMFileSaverPB.cc index eb826c8dbd503..aec8b2c7390dd 100644 --- a/DQMServices/FileIO/plugins/DQMFileSaverPB.cc +++ b/DQMServices/FileIO/plugins/DQMFileSaverPB.cc @@ -311,20 +311,17 @@ void DQMFileSaverPB::savePB(DQMStore* store, std::string const& filename, int ru GzipOutputStream gzip_stream(&file_stream, options); dqmstore_message.SerializeToZeroCopyStream(&gzip_stream); - // Flush the internal streams + // Flush the internal streams & Close the file descriptor gzip_stream.Close(); file_stream.Close(); } else { // We zlib compressed individual MEs so no need to compress the entire file again. dqmstore_message.SerializeToZeroCopyStream(&file_stream); - // Flush the internal stream + // Flush the internal stream & Close the file descriptor file_stream.Close(); } - // Close the file descriptor - ::close(filedescriptor); - // Maybe make some noise. edm::LogInfo("DQMFileSaverPB") << "savePB: successfully wrote " << nme << " objects " << "into DQM file '" << filename << "'\n"; diff --git a/DQMServices/FileIO/scripts/compareHistograms.py b/DQMServices/FileIO/scripts/compareHistograms.py index 2e269da323a46..070050162bb54 100755 --- a/DQMServices/FileIO/scripts/compareHistograms.py +++ b/DQMServices/FileIO/scripts/compareHistograms.py @@ -8,11 +8,12 @@ import argparse import numpy as np from DQMServices.FileIO.blacklist import get_blacklist +import multiprocessing -def create_dif(base_file_path, pr_file_path, pr_number, test_number, cmssw_version, output_dir_path): +def create_dif(base_file_path, pr_file_path, pr_number, test_number, cmssw_version, num_processes, output_dir_path): base_file = ROOT.TFile(base_file_path, 'read') ROOT.gROOT.GetListOfFiles().Remove(base_file) - + pr_file = ROOT.TFile(pr_file_path, 'read') ROOT.gROOT.GetListOfFiles().Remove(pr_file) @@ -29,7 +30,7 @@ def create_dif(base_file_path, pr_file_path, pr_number, test_number, cmssw_versi return run_nr = get_run_nr(pr_file_path) - + # Get list of paths (lists of directories) base_flat_dict = flatten_file(base_file, run_nr) pr_flat_dict = flatten_file(pr_file, run_nr) @@ -50,8 +51,35 @@ def create_dif(base_file_path, pr_file_path, pr_number, test_number, cmssw_versi paths_to_save_in_pr = [] # Make comparison - compare(shared_paths, pr_flat_dict, base_flat_dict, paths_to_save_in_pr, paths_to_save_in_base) - + if num_processes > 1: + print("starting comparison using %d process(es)" % num_processes) + manager = multiprocessing.Manager() + return_dict = manager.dict() + proc = [] + iProc = 0 + + block = len(shared_paths)//num_processes + for i in range(num_processes): + p = multiprocessing.Process(target=compareMP, args=(shared_paths[i*block:(i+1)*block], pr_flat_dict, base_flat_dict, i, return_dict)) + proc.append(p) + p.start() + iProc += 1 + p = multiprocessing.Process(target=compareMP, args=(shared_paths[(i+1)*block:len(shared_paths)], pr_flat_dict, base_flat_dict, num_processes, return_dict)) + proc.append(p) + p.start() + iProc += 1 + + for i in range(iProc): + proc[i].join() + paths_to_save_in_pr.extend(return_dict[i]['pr']) + paths_to_save_in_base.extend(return_dict[i]['base']) + + paths_to_save_in_pr.sort() + paths_to_save_in_base.sort() + print("Done") + else: + compare(shared_paths, pr_flat_dict, base_flat_dict, paths_to_save_in_pr, paths_to_save_in_base) + # Collect paths that have to be written to baseline output file for path in only_base_paths: item = base_flat_dict[path] @@ -60,7 +88,7 @@ def create_dif(base_file_path, pr_file_path, pr_number, test_number, cmssw_versi continue paths_to_save_in_base.append(path) - + # Collect paths that have to be written to PR output file for path in only_pr_paths: item = pr_flat_dict[path] @@ -75,7 +103,7 @@ def create_dif(base_file_path, pr_file_path, pr_number, test_number, cmssw_versi # Write baseline output save_paths(base_flat_dict, paths_to_save_in_base, os.path.join(output_dir_path, 'base', base_output_filename)) - + # Write PR output save_paths(pr_flat_dict, paths_to_save_in_pr, os.path.join(output_dir_path, 'pr', pr_output_filename)) @@ -92,6 +120,45 @@ def create_dif(base_file_path, pr_file_path, pr_number, test_number, cmssw_versi print(pr_output_filename) print('%s %s %s' % (nr_of_changed_elements, nr_of_removed_elements, nr_of_added_elements)) +def compareMP(shared_paths, pr_flat_dict, base_flat_dict, iProc, return_dict): + # Prepare output dictionary + comparisons = {'pr': [], 'base': []} + + # Collect paths that have to be written to both output files + for path in shared_paths: + pr_item = pr_flat_dict[path] + base_item = base_flat_dict[path] + + if pr_item == None or base_item == None: + continue + + are_different=False + + if pr_item.InheritsFrom('TProfile2D') and base_item.InheritsFrom('TProfile2D'): + # Compare TProfile (content, entries and errors) + are_different = not compare_TProfile(pr_item, base_item) + + elif pr_item.InheritsFrom('TProfile') and base_item.InheritsFrom('TProfile'): + # Compare TProfile (content, entries and errors) + are_different = not compare_TProfile(pr_item, base_item) + + elif pr_item.InheritsFrom('TH1') and base_item.InheritsFrom('TH1'): + # Compare bin by bin + pr_array = np.array(pr_item) + base_array = np.array(base_item) + + if pr_array.shape != base_array.shape or not np.allclose(pr_array, base_array, equal_nan=True): + are_different = True + else: + # Compare non histograms + if pr_item != base_item: + are_different = True + + if are_different: + comparisons['pr'].append(path) + comparisons['base'].append(path) + return_dict[iProc] = comparisons + def compare(shared_paths, pr_flat_dict, base_flat_dict, paths_to_save_in_pr, paths_to_save_in_base): # Collect paths that have to be written to both output files for path in shared_paths: @@ -106,7 +173,7 @@ def compare(shared_paths, pr_flat_dict, base_flat_dict, paths_to_save_in_pr, pat if pr_item.InheritsFrom('TProfile2D') and base_item.InheritsFrom('TProfile2D'): # Compare TProfile (content, entries and errors) are_different = not compare_TProfile(pr_item, base_item) - + elif pr_item.InheritsFrom('TProfile') and base_item.InheritsFrom('TProfile'): # Compare TProfile (content, entries and errors) are_different = not compare_TProfile(pr_item, base_item) @@ -131,7 +198,7 @@ def compare(shared_paths, pr_flat_dict, base_flat_dict, paths_to_save_in_pr, pat def compare_TProfile(pr_item, base_item): if pr_item.GetSize() != base_item.GetSize(): return False - + for i in range(pr_item.GetSize()): pr_bin_content = pr_item.GetBinContent(i) base_bin_content = base_item.GetBinContent(i) @@ -150,22 +217,22 @@ def compare_TProfile(pr_item, base_item): if not np.isclose(pr_bin_error, base_bin_error, equal_nan=True): return False - + return True def flatten_file(file, run_nr): - result = {} + result = {} for key in file.GetListOfKeys(): try: traverse_till_end(key.ReadObj(), [], result, run_nr) except: pass - + return result def traverse_till_end(node, dirs_list, result, run_nr): new_dir_list = dirs_list + [get_node_name(node)] - if hasattr(node, 'GetListOfKeys'): + if hasattr(node, 'GetListOfKeys'): for key in node.GetListOfKeys(): traverse_till_end(key.ReadObj(), new_dir_list, result, run_nr) else: @@ -202,7 +269,7 @@ def save_paths(flat_dict, paths, result_file_path): result_dir = os.path.dirname(result_file_path) if not os.path.exists(result_dir): os.makedirs(result_dir) - + result_file = ROOT.TFile(result_file_path, 'recreate') ROOT.gROOT.GetListOfFiles().Remove(result_file) @@ -270,9 +337,10 @@ def get_run_nr(file_path): parser.add_argument('-n', '--pr-number', help='PR number under test', default='00001') parser.add_argument('-t', '--test-number', help='Unique test number to distinguish different comparisons of the same PR.', default='1') parser.add_argument('-r', '--release-format', help='Release format in this format: CMSSW_10_5_X_2019-02-17-0000', default=os.environ['CMSSW_VERSION']) + parser.add_argument('-j', '--num-processes', help='Number of processes forked to parallel process the comparison', default=1, type=int) parser.add_argument('-o', '--output-dir', help='Comparison root files output directory', default='dqmHistoComparisonOutput') args = parser.parse_args() cmssw_version = '_'.join(args.release_format.split('_')[:4]) - - create_dif(args.base_file, args.pr_file, args.pr_number, args.test_number, cmssw_version, args.output_dir) + + create_dif(args.base_file, args.pr_file, args.pr_number, args.test_number, cmssw_version, args.num_processes, args.output_dir) diff --git a/DQMServices/FileIO/scripts/visDQMUpload.py b/DQMServices/FileIO/scripts/visDQMUpload.py index b6d981635c65d..a851d150cfb7f 100755 --- a/DQMServices/FileIO/scripts/visDQMUpload.py +++ b/DQMServices/FileIO/scripts/visDQMUpload.py @@ -12,15 +12,8 @@ import hashlib from stat import * -try: - import urllib.request as urllib2 -except ImportError: - import urllib2 - -try: - from commands import getstatusoutput -except ImportError: - from subprocess import getstatusoutput +import urllib.request as urllib2 +from subprocess import getstatusoutput try: from Monitoring.DQM import visDQMUtils diff --git a/DataFormats/CSCDigi/interface/CSCCLCTDigi.h b/DataFormats/CSCDigi/interface/CSCCLCTDigi.h index d2e1cb6c67030..b095210fe1650 100644 --- a/DataFormats/CSCDigi/interface/CSCCLCTDigi.h +++ b/DataFormats/CSCDigi/interface/CSCCLCTDigi.h @@ -173,7 +173,7 @@ class CSCCLCTDigi { void setCompCode(const int16_t code) { compCode_ = code; } // comparator hits in this CLCT - const ComparatorContainer& getHits() const { return hits_; } + const ComparatorContainer& getHits() const { return hits_.empty() ? emptyContainer() : hits_; } void setHits(const ComparatorContainer& hits) { hits_ = hits; } @@ -197,6 +197,7 @@ class CSCCLCTDigi { void setRun3(bool isRun3); private: + static const ComparatorContainer& emptyContainer(); uint16_t valid_; uint16_t quality_; // Run-1/2 pattern number. @@ -232,7 +233,6 @@ class CSCCLCTDigi { // which hits are in this CLCT? ComparatorContainer hits_; - Version version_; }; diff --git a/DataFormats/CSCDigi/src/CSCCLCTDigi.cc b/DataFormats/CSCDigi/src/CSCCLCTDigi.cc index 1004f8f6da3a2..3edc6dfbabada 100644 --- a/DataFormats/CSCDigi/src/CSCCLCTDigi.cc +++ b/DataFormats/CSCDigi/src/CSCCLCTDigi.cc @@ -13,6 +13,22 @@ enum Pattern_Info { NUM_LAYERS = 6, CLCT_PATTERN_WIDTH = 11 }; +namespace { + CSCCLCTDigi::ComparatorContainer makeEmptyContainer() { + CSCCLCTDigi::ComparatorContainer ret; + ret.resize(NUM_LAYERS); + for (auto& p : ret) { + p.resize(CLCT_PATTERN_WIDTH); + } + return ret; + } +} // namespace + +CSCCLCTDigi::ComparatorContainer const& CSCCLCTDigi::emptyContainer() { + static ComparatorContainer const s_container = makeEmptyContainer(); + return s_container; +} + /// Constructors CSCCLCTDigi::CSCCLCTDigi(const uint16_t valid, const uint16_t quality, @@ -45,12 +61,8 @@ CSCCLCTDigi::CSCCLCTDigi(const uint16_t valid, run3_eighth_strip_bit_(run3_eighth_strip_bit), run3_pattern_(run3_pattern), run3_slope_(run3_slope), - version_(version) { - hits_.resize(NUM_LAYERS); - for (auto& p : hits_) { - p.resize(CLCT_PATTERN_WIDTH); - } -} + hits_(), + version_(version) {} /// Default CSCCLCTDigi::CSCCLCTDigi() { @@ -77,10 +89,6 @@ void CSCCLCTDigi::clear() { run3_slope_ = 0; version_ = Version::Legacy; hits_.clear(); - hits_.resize(NUM_LAYERS); - for (auto& p : hits_) { - p.resize(CLCT_PATTERN_WIDTH); - } } // slope in number of half-strips/layer diff --git a/DataFormats/EgammaCandidates/interface/GsfElectron.h b/DataFormats/EgammaCandidates/interface/GsfElectron.h index b81bdf23d1974..22b6c65bd79ef 100644 --- a/DataFormats/EgammaCandidates/interface/GsfElectron.h +++ b/DataFormats/EgammaCandidates/interface/GsfElectron.h @@ -28,8 +28,8 @@ namespace reco { * Renamed from PixelMatchGsfElectron. * Originally adapted from the TRecElectron class in ORCA. * - * \author Claude Charlot - Laboratoire Leprince-Ringuet - École polytechnique, CNRS/IN2P3 - * \author David Chamont - Laboratoire Leprince-Ringuet - École polytechnique, CNRS/IN2P3 + * \author Claude Charlot - Laboratoire Leprince-Ringuet - École polytechnique, CNRS/IN2P3 + * \author David Chamont - Laboratoire Leprince-Ringuet - École polytechnique, CNRS/IN2P3 * ****************************************************************************/ @@ -701,12 +701,28 @@ namespace reco { etOutsideMustache(-std::numeric_limits::max()) {} }; + static constexpr float mvaPlaceholder = -999999999.; + struct MvaOutput { int status; // see PFCandidateElectronExtra::StatusFlag float mva_Isolated; float mva_e_pi; float mvaByPassForIsolated; // complementary MVA used in preselection - MvaOutput() : status(-1), mva_Isolated(-999999999.), mva_e_pi(-999999999.), mvaByPassForIsolated(-999999999.) {} + float dnn_e_sigIsolated; + float dnn_e_sigNonIsolated; + float dnn_e_bkgNonIsolated; + float dnn_e_bkgTau; + float dnn_e_bkgPhoton; + MvaOutput() + : status(-1), + mva_Isolated(mvaPlaceholder), + mva_e_pi(mvaPlaceholder), + mvaByPassForIsolated(mvaPlaceholder), + dnn_e_sigIsolated(mvaPlaceholder), + dnn_e_sigNonIsolated(mvaPlaceholder), + dnn_e_bkgNonIsolated(mvaPlaceholder), + dnn_e_bkgTau(mvaPlaceholder), + dnn_e_bkgPhoton(mvaPlaceholder) {} }; // accessors @@ -726,6 +742,11 @@ namespace reco { // for backward compatibility float mva_Isolated() const { return mvaOutput_.mva_Isolated; } float mva_e_pi() const { return mvaOutput_.mva_e_pi; } + float dnn_signal_Isolated() const { return mvaOutput_.dnn_e_sigIsolated; } + float dnn_signal_nonIsolated() const { return mvaOutput_.dnn_e_sigNonIsolated; } + float dnn_bkg_nonIsolated() const { return mvaOutput_.dnn_e_bkgNonIsolated; } + float dnn_bkg_Tau() const { return mvaOutput_.dnn_e_bkgTau; } + float dnn_bkg_Photon() const { return mvaOutput_.dnn_e_bkgPhoton; } private: PflowIsolationVariables pfIso_; diff --git a/DataFormats/EgammaCandidates/interface/Photon.h b/DataFormats/EgammaCandidates/interface/Photon.h index 071f0329a03fb..f1daf95615eb4 100644 --- a/DataFormats/EgammaCandidates/interface/Photon.h +++ b/DataFormats/EgammaCandidates/interface/Photon.h @@ -556,25 +556,23 @@ namespace reco { /// Set Particle Flow Isolation variables void setPflowIsolationVariables(const PflowIsolationVariables& pfisol) { pfIsolation_ = pfisol; } + static constexpr float mvaPlaceholder = -999999999.; + struct PflowIDVariables { int nClusterOutsideMustache; float etOutsideMustache; float mva; + float dnn; PflowIDVariables() - : - - nClusterOutsideMustache(-1), - etOutsideMustache(-999999999.), - mva(-999999999.) - - {} + : nClusterOutsideMustache(-1), etOutsideMustache(mvaPlaceholder), mva(mvaPlaceholder), dnn(mvaPlaceholder) {} }; // getters int nClusterOutsideMustache() const { return pfID_.nClusterOutsideMustache; } float etOutsideMustache() const { return pfID_.etOutsideMustache; } float pfMVA() const { return pfID_.mva; } + float pfDNN() const { return pfID_.dnn; } // setters void setPflowIDVariables(const PflowIDVariables& pfid) { pfID_ = pfid; } diff --git a/DataFormats/EgammaCandidates/src/classes_def.xml b/DataFormats/EgammaCandidates/src/classes_def.xml index 7b93b9863aa35..9432329160786 100644 --- a/DataFormats/EgammaCandidates/src/classes_def.xml +++ b/DataFormats/EgammaCandidates/src/classes_def.xml @@ -69,7 +69,8 @@ - + + @@ -221,7 +222,8 @@ - + + diff --git a/DataFormats/HGCDigi/interface/HGCDigiCollections.h b/DataFormats/HGCDigi/interface/HGCDigiCollections.h index d1e483cd9f075..bc41a76138565 100644 --- a/DataFormats/HGCDigi/interface/HGCDigiCollections.h +++ b/DataFormats/HGCDigi/interface/HGCDigiCollections.h @@ -5,18 +5,8 @@ #include "DataFormats/DetId/interface/DetId.h" #include "DataFormats/ForwardDetId/interface/HGCalDetId.h" #include "DataFormats/HGCDigi/interface/HGCDataFrame.h" -#include "DataFormats/HcalDetId/interface/HcalDetId.h" #include "DataFormats/HGCDigi/interface/HGCSample.h" -typedef HGCDataFrame HGCEEDataFrame; -typedef edm::SortedCollection HGCEEDigiCollection; - -typedef HGCDataFrame HGCHEDataFrame; -typedef edm::SortedCollection HGCHEDigiCollection; - -typedef HGCDataFrame HGCBHDataFrame; -typedef edm::SortedCollection HGCBHDigiCollection; - typedef HGCDataFrame HGCalDataFrame; typedef edm::SortedCollection HGCalDigiCollection; diff --git a/DataFormats/HGCDigi/src/classes_def.xml b/DataFormats/HGCDigi/src/classes_def.xml index f9c9f2367873b..1299c619e9818 100644 --- a/DataFormats/HGCDigi/src/classes_def.xml +++ b/DataFormats/HGCDigi/src/classes_def.xml @@ -17,18 +17,6 @@ - - - - - - - - - - - - diff --git a/DataFormats/HGCalReco/interface/Common.h b/DataFormats/HGCalReco/interface/Common.h index af1ad19f9ccb7..d01665aa2b80e 100644 --- a/DataFormats/HGCalReco/interface/Common.h +++ b/DataFormats/HGCalReco/interface/Common.h @@ -14,7 +14,6 @@ namespace ticl { static constexpr int nLayers = 104; static constexpr int iterations = 4; static constexpr int nBins = nEtaBins * nPhiBins; - static constexpr int type = 0; }; struct TileConstantsHFNose { @@ -25,7 +24,6 @@ namespace ticl { static constexpr int nLayers = 16; // 8x2 static constexpr int iterations = 4; static constexpr int nBins = nEtaBins * nPhiBins; - static constexpr int type = 1; }; } // namespace ticl diff --git a/DataFormats/HGCalReco/interface/TICLLayerTile.h b/DataFormats/HGCalReco/interface/TICLLayerTile.h index 5d9cc8fb51a1c..a002950cbea2e 100644 --- a/DataFormats/HGCalReco/interface/TICLLayerTile.h +++ b/DataFormats/HGCalReco/interface/TICLLayerTile.h @@ -10,12 +10,12 @@ template class TICLLayerTileT { public: + typedef T type; + void fill(double eta, double phi, unsigned int layerClusterId) { tile_[globalBin(eta, phi)].push_back(layerClusterId); } - int typeT() const { return T::type; } - int etaBin(float eta) const { constexpr float etaRange = T::maxEta - T::minEta; static_assert(etaRange >= 0.f); @@ -71,6 +71,8 @@ namespace ticl { template class TICLGenericTile { public: + // value_type_t is the type of the type of the array used by the incoming type. + using constants_type_t = typename T::value_type::type; // This class represents a generic collection of Tiles. The additional index // numbering is not handled internally. It is the user's responsibility to // properly use and consistently access it here. diff --git a/DataFormats/HcalDigi/test/HcalDigiDump.cc b/DataFormats/HcalDigi/test/HcalDigiDump.cc index 9041771fdbb84..a8279f2c66257 100644 --- a/DataFormats/HcalDigi/test/HcalDigiDump.cc +++ b/DataFormats/HcalDigi/test/HcalDigiDump.cc @@ -1,4 +1,4 @@ -#include "FWCore/Framework/interface/EDAnalyzer.h" +#include "FWCore/Framework/interface/one/EDAnalyzer.h" #include "FWCore/Framework/interface/Event.h" #include "DataFormats/Common/interface/Handle.h" #include "DataFormats/HcalDigi/interface/HcalDigiCollections.h" @@ -11,10 +11,11 @@ using namespace std; \author J. Mans - Minnesota */ -class HcalDigiDump : public edm::EDAnalyzer { +class HcalDigiDump : public edm::one::EDAnalyzer<> { public: explicit HcalDigiDump(edm::ParameterSet const& conf); - virtual void analyze(edm::Event const& e, edm::EventSetup const& c); + ~HcalDigiDump() override = default; + void analyze(edm::Event const& e, edm::EventSetup const& c) override; }; HcalDigiDump::HcalDigiDump(edm::ParameterSet const& conf) { diff --git a/DataFormats/L1TMuon/interface/RegionalMuonShower.h b/DataFormats/L1TMuon/interface/RegionalMuonShower.h index a81ccd95e5057..230dc49d12664 100644 --- a/DataFormats/L1TMuon/interface/RegionalMuonShower.h +++ b/DataFormats/L1TMuon/interface/RegionalMuonShower.h @@ -18,12 +18,16 @@ namespace l1t { RegionalMuonShower(bool oneNominalInTime = false, bool oneNominalOutOfTime = false, bool twoLooseInTime = false, - bool twoLooseOutOfTime = false); + bool twoLooseOutOfTime = false, + bool oneTightInTime = false, + bool oneTightOutOfTime = false); ~RegionalMuonShower(); void setOneNominalInTime(const bool bit) { isOneNominalInTime_ = bit; } void setOneNominalOutOfTime(const bool bit) { isOneNominalOutOfTime_ = bit; } + void setOneTightInTime(const bool bit) { isOneTightInTime_ = bit; } + void setOneTightOutOfTime(const bool bit) { isOneTightOutOfTime_ = bit; } void setTwoLooseOutOfTime(const bool bit) { isTwoLooseOutOfTime_ = bit; } void setTwoLooseInTime(const bool bit) { isTwoLooseInTime_ = bit; } @@ -34,6 +38,8 @@ namespace l1t { bool isValid() const; bool isOneNominalInTime() const { return isOneNominalInTime_; } bool isOneNominalOutOfTime() const { return isOneNominalOutOfTime_; } + bool isOneTightInTime() const { return isOneTightInTime_; } + bool isOneTightOutOfTime() const { return isOneTightOutOfTime_; } bool isTwoLooseInTime() const { return isTwoLooseInTime_; } bool isTwoLooseOutOfTime() const { return isTwoLooseOutOfTime_; } @@ -50,6 +56,8 @@ namespace l1t { // in time and out-of-time qualities. only 2 bits each. bool isOneNominalInTime_; bool isOneNominalOutOfTime_; + bool isOneTightInTime_; + bool isOneTightOutOfTime_; bool isTwoLooseInTime_; bool isTwoLooseOutOfTime_; int endcap_; // +/-1. For ME+ and ME-. diff --git a/DataFormats/L1TMuon/src/RegionalMuonShower.cc b/DataFormats/L1TMuon/src/RegionalMuonShower.cc index fb03609dac59c..ce73da8584331 100644 --- a/DataFormats/L1TMuon/src/RegionalMuonShower.cc +++ b/DataFormats/L1TMuon/src/RegionalMuonShower.cc @@ -3,9 +3,13 @@ l1t::RegionalMuonShower::RegionalMuonShower(bool oneNominalInTime, bool oneNominalOutOfTime, bool twoLooseInTime, - bool twoLooseOutOfTime) + bool twoLooseOutOfTime, + bool oneTightInTime, + bool oneTightOutOfTime) : isOneNominalInTime_(oneNominalInTime), isOneNominalOutOfTime_(oneNominalOutOfTime), + isOneTightInTime_(oneTightInTime), + isOneTightOutOfTime_(oneTightOutOfTime), isTwoLooseInTime_(twoLooseInTime), isTwoLooseOutOfTime_(twoLooseOutOfTime), endcap_(0), @@ -15,10 +19,10 @@ l1t::RegionalMuonShower::RegionalMuonShower(bool oneNominalInTime, l1t::RegionalMuonShower::~RegionalMuonShower() {} bool l1t::RegionalMuonShower::isValid() const { - return isOneNominalInTime_ or isTwoLooseInTime_ or isOneNominalOutOfTime_ or isTwoLooseOutOfTime_; + return (isOneNominalInTime_ or isTwoLooseInTime_ or isOneTightInTime_); } bool l1t::RegionalMuonShower::operator==(const l1t::RegionalMuonShower& rhs) const { return (isTwoLooseInTime_ == rhs.isTwoLooseInTime() and isOneNominalInTime_ == rhs.isOneNominalInTime() and - isTwoLooseOutOfTime_ == rhs.isTwoLooseOutOfTime() and isOneNominalOutOfTime_ == rhs.isOneNominalOutOfTime()); + isOneTightInTime_ == rhs.isOneTightInTime()); } diff --git a/DataFormats/L1TMuon/src/classes_def.xml b/DataFormats/L1TMuon/src/classes_def.xml index 5f8365cead888..d045b4388ab55 100644 --- a/DataFormats/L1TMuon/src/classes_def.xml +++ b/DataFormats/L1TMuon/src/classes_def.xml @@ -13,7 +13,8 @@ - + + diff --git a/DataFormats/L1Trigger/interface/MuonShower.h b/DataFormats/L1Trigger/interface/MuonShower.h index a5684377f224d..15125d77bc548 100644 --- a/DataFormats/L1Trigger/interface/MuonShower.h +++ b/DataFormats/L1Trigger/interface/MuonShower.h @@ -30,20 +30,53 @@ namespace l1t { MuonShower(bool oneNominalInTime = false, bool oneNominalOutOfTime = false, bool twoLooseInTime = false, - bool twoLooseOutOfTime = false); + bool twoLooseOutOfTime = false, + bool oneTightInTime = false, + bool oneTightOutOfTime = false); ~MuonShower() override; - void setOneNominalInTime(const bool bit) { isOneNominalInTime_ = bit; } - void setOneNominalOutOfTime(const bool bit) { isOneNominalOutOfTime_ = bit; } - void setTwoLooseInTime(const bool bit) { isTwoLooseInTime_ = bit; } - void setTwoLooseOutOfTime(const bool bit) { isTwoLooseOutOfTime_ = bit; } + /* + In CMSSW we consider 3 valid cases: + - 1 nominal shower (baseline trigger for physics at Run-3) + - 1 tight shower (backup trigger) + - 2 loose showers (to extend the physics reach) + In the uGT and UTM library, the hadronic shower trigger data is split + over 4 bits: 2 for in-time trigger data, 2 for out-of-time trigger data + - mus0, mus1 for in-time + - musOutOfTime0, musOutOfTime1 for out-of-time + + The mapping for Run-3 startup is as follows: + - 1 nominal shower -> 0b01 (mus0) + - 1 tight shower -> 0b10 (mus1) + + The 2 loose showers case would be mapped onto musOutOfTime0 and musOutOfTime1 later during Run-3 + */ + + void setMus0(const bool bit) { mus0_ = bit; } + void setMus1(const bool bit) { mus1_ = bit; } + void setMusOutOfTime0(const bool bit) { musOutOfTime0_ = bit; } + void setMusOutOfTime1(const bool bit) { musOutOfTime1_ = bit; } + + bool mus0() const { return mus0_; } + bool mus1() const { return mus1_; } + bool musOutOfTime0() const { return musOutOfTime0_; } + bool musOutOfTime1() const { return musOutOfTime1_; } + + // at least one bit must be valid bool isValid() const; - bool isOneNominalInTime() const { return isOneNominalInTime_; } - bool isOneNominalOutOfTime() const { return isOneNominalOutOfTime_; } - bool isTwoLooseInTime() const { return isTwoLooseInTime_; } - bool isTwoLooseOutOfTime() const { return isTwoLooseOutOfTime_; } + + // useful members for trigger performance studies + // needed at startup Run-3 + bool isOneNominalInTime() const { return mus0_; } + bool isOneTightInTime() const { return mus1_; } + // to be developed during Run-3 + bool isTwoLooseInTime() const { return false; } + // these options require more study + bool isOneNominalOutOfTime() const { return false; } + bool isTwoLooseOutOfTime() const { return false; } + bool isOneTightOutOfTime() const { return false; } virtual bool operator==(const l1t::MuonShower& rhs) const; virtual inline bool operator!=(const l1t::MuonShower& rhs) const { return !(operator==(rhs)); }; @@ -51,10 +84,10 @@ namespace l1t { private: // Run-3 definitions as provided in DN-20-033 // in time and out-of-time qualities. only 2 bits each. - bool isOneNominalInTime_; - bool isOneNominalOutOfTime_; - bool isTwoLooseInTime_; - bool isTwoLooseOutOfTime_; + bool mus0_; + bool mus1_; + bool musOutOfTime0_; + bool musOutOfTime1_; }; } // namespace l1t diff --git a/DataFormats/L1Trigger/src/MuonShower.cc b/DataFormats/L1Trigger/src/MuonShower.cc index dec1dc893a54e..123363221b79e 100644 --- a/DataFormats/L1Trigger/src/MuonShower.cc +++ b/DataFormats/L1Trigger/src/MuonShower.cc @@ -1,19 +1,24 @@ #include "DataFormats/L1Trigger/interface/MuonShower.h" -l1t::MuonShower::MuonShower(bool oneNominalInTime, bool oneNominalOutOfTime, bool twoLooseInTime, bool twoLooseOutOfTime) +l1t::MuonShower::MuonShower(bool oneNominalInTime, + bool oneNominalOutOfTime, + bool twoLooseInTime, + bool twoLooseOutOfTime, + bool oneTightInTime, + bool oneTightOutOfTime) : L1Candidate(math::PtEtaPhiMLorentzVector{0., 0., 0., 0.}, 0., 0., 0., 0, 0), - isOneNominalInTime_(oneNominalInTime), - isOneNominalOutOfTime_(oneNominalOutOfTime), - isTwoLooseInTime_(twoLooseInTime), - isTwoLooseOutOfTime_(twoLooseOutOfTime) {} + // in this object it makes more sense to the different shower types to + // the 4 bits, so that the object easily interfaces with the uGT emulator + mus0_(oneNominalInTime), + mus1_(oneTightInTime), + musOutOfTime0_(false), + musOutOfTime1_(false) {} l1t::MuonShower::~MuonShower() {} -bool l1t::MuonShower::isValid() const { - return isOneNominalInTime_ or isTwoLooseInTime_ or isOneNominalOutOfTime_ or isTwoLooseOutOfTime_; -} +bool l1t::MuonShower::isValid() const { return mus0_ or mus1_ or musOutOfTime0_ or musOutOfTime1_; } bool l1t::MuonShower::operator==(const l1t::MuonShower& rhs) const { - return (isTwoLooseInTime_ == rhs.isTwoLooseInTime() and isOneNominalInTime_ == rhs.isOneNominalInTime() and - isTwoLooseOutOfTime_ == rhs.isTwoLooseOutOfTime() and isOneNominalOutOfTime_ == rhs.isOneNominalOutOfTime()); + return (mus0_ == rhs.mus0() and mus1_ == rhs.mus1() and musOutOfTime0_ == rhs.musOutOfTime0() and + musOutOfTime1_ == rhs.musOutOfTime1()); } diff --git a/DataFormats/L1Trigger/src/classes_def.xml b/DataFormats/L1Trigger/src/classes_def.xml index 0bd493b85b81b..b639135a3e1f6 100644 --- a/DataFormats/L1Trigger/src/classes_def.xml +++ b/DataFormats/L1Trigger/src/classes_def.xml @@ -103,7 +103,8 @@ - + + diff --git a/DataFormats/ParticleFlowCandidate/interface/PFCandidate.h b/DataFormats/ParticleFlowCandidate/interface/PFCandidate.h index 31d43fa4c9087..9ca9bce8832c5 100644 --- a/DataFormats/ParticleFlowCandidate/interface/PFCandidate.h +++ b/DataFormats/ParticleFlowCandidate/interface/PFCandidate.h @@ -343,6 +343,31 @@ namespace reco { /// set mva for neutral hadron - gamma discrimination void set_mva_gamma_nh(float mva) { mva_gamma_nh_ = mva; } + // set DNN for electron PFID + // mva for ele PFID DNN sigIsolated class + float dnn_e_sigIsolated() const { return dnn_e_sigIsolated_; } + void set_dnn_e_sigIsolated(float mva) { dnn_e_sigIsolated_ = mva; } + + // mva for ele PFID DNN sigNonIsolated class + float dnn_e_sigNonIsolated() const { return dnn_e_sigNonIsolated_; } + void set_dnn_e_sigNonIsolated(float mva) { dnn_e_sigNonIsolated_ = mva; } + + // mva for ele PFID DNN bkgNonIsolated class + float dnn_e_bkgNonIsolated() const { return dnn_e_bkgNonIsolated_; } + void set_dnn_e_bkgNonIsolated(float mva) { dnn_e_bkgNonIsolated_ = mva; } + + // mva for ele PFID DNN bkgTau class + float dnn_e_bkgTau() const { return dnn_e_bkgTau_; } + void set_dnn_e_bkgTau(float mva) { dnn_e_bkgTau_ = mva; } + + // mva for ele PFID DNN bkgPhoton class + float dnn_e_bkgPhoton() const { return dnn_e_bkgPhoton_; } + void set_dnn_e_bkgPhoton(float mva) { dnn_e_bkgPhoton_ = mva; } + + // set DNN for gamma PFID + float dnn_gamma() const { return dnn_gamma_; } + void set_dnn_gamma(float mva) { dnn_gamma_ = mva; } + /// mva for neutral hadron - gamma discrimination float mva_gamma_nh() const { return mva_gamma_nh_; } @@ -383,7 +408,7 @@ namespace reco { const ElementsInBlocks& elementsInBlocks() const; - static const float bigMva_; + static constexpr float bigMva_ = -999.; friend std::ostream& operator<<(std::ostream& out, const PFCandidate& c); @@ -492,6 +517,24 @@ namespace reco { /// mva for neutral hadron - gamma discrimination float mva_gamma_nh_; + /// DNN for electron PFid: isolated signal + float dnn_e_sigIsolated_; + + /// DNN for electron PFid: non-isolated signal + float dnn_e_sigNonIsolated_; + + /// DNN for electron PFid: non-isolated bkg + float dnn_e_bkgNonIsolated_; + + /// DNN for electron PFid: tau bkg + float dnn_e_bkgTau_; + + /// DNN for electron PFid: photon bkg + float dnn_e_bkgPhoton_; + + // DNN for gamma PFid + float dnn_gamma_; + /// position at ECAL entrance, from the PFRecTrack math::XYZPointF positionAtECALEntrance_; diff --git a/DataFormats/ParticleFlowCandidate/src/PFCandidate.cc b/DataFormats/ParticleFlowCandidate/src/PFCandidate.cc index c178c042e604b..632579a364f6d 100644 --- a/DataFormats/ParticleFlowCandidate/src/PFCandidate.cc +++ b/DataFormats/ParticleFlowCandidate/src/PFCandidate.cc @@ -18,8 +18,6 @@ using namespace reco; using namespace std; -const float PFCandidate::bigMva_ = -999.; - #include "DataFormats/ParticleFlowCandidate/src/CountBits.h" PFCandidate::PFCandidate() @@ -35,13 +33,18 @@ PFCandidate::PFCandidate() flags_(0), deltaP_(0.), vertexType_(kCandVertex), - mva_Isolated_(bigMva_), - mva_e_pi_(bigMva_), - mva_e_mu_(bigMva_), - mva_pi_mu_(bigMva_), - mva_nothing_gamma_(bigMva_), - mva_nothing_nh_(bigMva_), - mva_gamma_nh_(bigMva_), + mva_Isolated_(PFCandidate::bigMva_), + mva_e_pi_(PFCandidate::bigMva_), + mva_e_mu_(PFCandidate::bigMva_), + mva_pi_mu_(PFCandidate::bigMva_), + mva_nothing_gamma_(PFCandidate::bigMva_), + mva_nothing_nh_(PFCandidate::bigMva_), + mva_gamma_nh_(PFCandidate::bigMva_), + dnn_e_sigIsolated_(PFCandidate::bigMva_), + dnn_e_sigNonIsolated_(PFCandidate::bigMva_), + dnn_e_bkgNonIsolated_(PFCandidate::bigMva_), + dnn_e_bkgTau_(PFCandidate::bigMva_), + dnn_e_bkgPhoton_(PFCandidate::bigMva_), getter_(nullptr), storedRefsBitPattern_(0), time_(0.f), @@ -74,13 +77,18 @@ PFCandidate::PFCandidate(Charge charge, const LorentzVector& p4, ParticleType pa flags_(0), deltaP_(0.), vertexType_(kCandVertex), - mva_Isolated_(bigMva_), - mva_e_pi_(bigMva_), - mva_e_mu_(bigMva_), - mva_pi_mu_(bigMva_), - mva_nothing_gamma_(bigMva_), - mva_nothing_nh_(bigMva_), - mva_gamma_nh_(bigMva_), + mva_Isolated_(PFCandidate::bigMva_), + mva_e_pi_(PFCandidate::bigMva_), + mva_e_mu_(PFCandidate::bigMva_), + mva_pi_mu_(PFCandidate::bigMva_), + mva_nothing_gamma_(PFCandidate::bigMva_), + mva_nothing_nh_(PFCandidate::bigMva_), + mva_gamma_nh_(PFCandidate::bigMva_), + dnn_e_sigIsolated_(PFCandidate::bigMva_), + dnn_e_sigNonIsolated_(PFCandidate::bigMva_), + dnn_e_bkgNonIsolated_(PFCandidate::bigMva_), + dnn_e_bkgTau_(PFCandidate::bigMva_), + dnn_e_bkgPhoton_(PFCandidate::bigMva_), getter_(nullptr), storedRefsBitPattern_(0), time_(0.f), @@ -137,6 +145,11 @@ PFCandidate::PFCandidate(PFCandidate const& iOther) mva_nothing_gamma_(iOther.mva_nothing_gamma_), mva_nothing_nh_(iOther.mva_nothing_nh_), mva_gamma_nh_(iOther.mva_gamma_nh_), + dnn_e_sigIsolated_(iOther.dnn_e_sigIsolated_), + dnn_e_sigNonIsolated_(iOther.dnn_e_sigNonIsolated_), + dnn_e_bkgNonIsolated_(iOther.dnn_e_bkgNonIsolated_), + dnn_e_bkgTau_(iOther.dnn_e_bkgTau_), + dnn_e_bkgPhoton_(iOther.dnn_e_bkgPhoton_), positionAtECALEntrance_(iOther.positionAtECALEntrance_), getter_(iOther.getter_), storedRefsBitPattern_(iOther.storedRefsBitPattern_), @@ -181,6 +194,11 @@ PFCandidate& PFCandidate::operator=(PFCandidate const& iOther) { mva_nothing_gamma_ = iOther.mva_nothing_gamma_; mva_nothing_nh_ = iOther.mva_nothing_nh_; mva_gamma_nh_ = iOther.mva_gamma_nh_; + dnn_e_sigIsolated_ = iOther.dnn_e_sigIsolated_; + dnn_e_sigNonIsolated_ = iOther.dnn_e_sigNonIsolated_; + dnn_e_bkgNonIsolated_ = iOther.dnn_e_bkgNonIsolated_; + dnn_e_bkgTau_ = iOther.dnn_e_bkgTau_; + dnn_e_bkgPhoton_ = iOther.dnn_e_bkgPhoton_; positionAtECALEntrance_ = iOther.positionAtECALEntrance_; getter_ = iOther.getter_; storedRefsBitPattern_ = iOther.storedRefsBitPattern_; diff --git a/DataFormats/ParticleFlowCandidate/src/classes_def.xml b/DataFormats/ParticleFlowCandidate/src/classes_def.xml index eca906716f5bc..17fa11e0ed1ee 100644 --- a/DataFormats/ParticleFlowCandidate/src/classes_def.xml +++ b/DataFormats/ParticleFlowCandidate/src/classes_def.xml @@ -1,6 +1,7 @@ - + + @@ -52,7 +53,8 @@ - + + @@ -67,7 +69,8 @@ - + + diff --git a/DataFormats/PatCandidates/src/classes_def_objects.xml b/DataFormats/PatCandidates/src/classes_def_objects.xml index e4a78ebf00e43..2b98aef02aab2 100644 --- a/DataFormats/PatCandidates/src/classes_def_objects.xml +++ b/DataFormats/PatCandidates/src/classes_def_objects.xml @@ -314,7 +314,8 @@ - + + diff --git a/DataFormats/TrajectorySeed/interface/PropagationDirection.h b/DataFormats/TrajectorySeed/interface/PropagationDirection.h index 5aa5eb180d166..da18ae894c580 100644 --- a/DataFormats/TrajectorySeed/interface/PropagationDirection.h +++ b/DataFormats/TrajectorySeed/interface/PropagationDirection.h @@ -1,6 +1,6 @@ #ifndef dataFormats_PropagationDirection_H #define dataFormats_PropagationDirection_H -enum PropagationDirection { oppositeToMomentum, alongMomentum, anyDirection }; +enum PropagationDirection { oppositeToMomentum, alongMomentum, anyDirection, invalidDirection }; #endif diff --git a/DataFormats/TrajectorySeed/interface/TrajectorySeed.h b/DataFormats/TrajectorySeed/interface/TrajectorySeed.h index 61b653709cc82..ca7c76d5a6f6a 100644 --- a/DataFormats/TrajectorySeed/interface/TrajectorySeed.h +++ b/DataFormats/TrajectorySeed/interface/TrajectorySeed.h @@ -59,7 +59,7 @@ class TrajectorySeed { private: RecHitContainer hits_; PTrajectoryStateOnDet tsos_; - PropagationDirection dir_; + PropagationDirection dir_ = invalidDirection; }; inline void swap(TrajectorySeed& rh, TrajectorySeed& lh) noexcept { rh.swap(lh); } diff --git a/DetectorDescription/DDCMS/plugins/DDCMSDetector.cc b/DetectorDescription/DDCMS/plugins/DDCMSDetector.cc index 16bb608420a70..1cf405f1db39c 100644 --- a/DetectorDescription/DDCMS/plugins/DDCMSDetector.cc +++ b/DetectorDescription/DDCMS/plugins/DDCMSDetector.cc @@ -29,13 +29,17 @@ class DDCMSDetector : public one::EDAnalyzer<> { private: const ESInputTag m_tag; + const ESGetToken m_detectorToken; + const ESGetToken m_registryToken; }; -DDCMSDetector::DDCMSDetector(const ParameterSet& iConfig) : m_tag(iConfig.getParameter("DDDetector")) {} +DDCMSDetector::DDCMSDetector(const ParameterSet& iConfig) + : m_tag(iConfig.getParameter("DDDetector")), + m_detectorToken(esConsumes(m_tag)), + m_registryToken(esConsumes(m_tag)) {} void DDCMSDetector::analyze(const Event&, const EventSetup& iEventSetup) { - ESTransientHandle det; - iEventSetup.get().get(m_tag, det); + ESTransientHandle det = iEventSetup.getTransientHandle(m_detectorToken); LogVerbatim("Geometry") << "Iterate over the detectors:\n"; LogVerbatim("Geometry").log([&](auto& log) { @@ -46,8 +50,7 @@ void DDCMSDetector::analyze(const Event&, const EventSetup& iEventSetup) { }); LogVerbatim("Geometry") << "..done!"; - ESTransientHandle registry; - iEventSetup.get().get(m_tag, registry); + ESTransientHandle registry = iEventSetup.getTransientHandle(m_registryToken); LogVerbatim("Geometry") << "DD Vector Registry size: " << registry->vectors.size(); LogVerbatim("Geometry").log([&](auto& log) { diff --git a/DetectorDescription/DDCMS/plugins/test/DDTestCompactView.cc b/DetectorDescription/DDCMS/plugins/test/DDTestCompactView.cc index f38bd8d123330..2d31029c269f8 100644 --- a/DetectorDescription/DDCMS/plugins/test/DDTestCompactView.cc +++ b/DetectorDescription/DDCMS/plugins/test/DDTestCompactView.cc @@ -14,7 +14,8 @@ using namespace edm; class DDTestCompactView : public one::EDAnalyzer<> { public: - explicit DDTestCompactView(const ParameterSet& iConfig) : m_tag(iConfig.getParameter("DDDetector")) {} + explicit DDTestCompactView(const ParameterSet& iConfig) + : m_tag(iConfig.getParameter("DDDetector")), m_token(esConsumes(m_tag)) {} void beginJob() override {} void analyze(Event const& iEvent, EventSetup const&) override; @@ -22,12 +23,12 @@ class DDTestCompactView : public one::EDAnalyzer<> { private: const ESInputTag m_tag; + const ESGetToken m_token; }; void DDTestCompactView::analyze(const Event&, const EventSetup& iEventSetup) { LogVerbatim("Geometry") << "DDTestCompactView::analyze: " << m_tag; - ESTransientHandle cpv; - iEventSetup.get().get(m_tag, cpv); + ESTransientHandle cpv = iEventSetup.getTransientHandle(m_token); std::cout << "Get trackerParameters:detIdShifts:\n"; auto const& vec = cpv->getVector("detIdShifts"); diff --git a/DetectorDescription/DDCMS/plugins/test/DDTestDumpFile.cc b/DetectorDescription/DDCMS/plugins/test/DDTestDumpFile.cc index 81c2317337470..7be824e03a8e2 100644 --- a/DetectorDescription/DDCMS/plugins/test/DDTestDumpFile.cc +++ b/DetectorDescription/DDCMS/plugins/test/DDTestDumpFile.cc @@ -32,17 +32,18 @@ class DDTestDumpFile : public one::EDAnalyzer<> { const string m_tag; const string m_outputFileName; const ESInputTag m_label; + const ESGetToken m_token; }; DDTestDumpFile::DDTestDumpFile(const ParameterSet& iConfig) : m_tag(iConfig.getUntrackedParameter("tag", "unknown")), m_outputFileName(iConfig.getUntrackedParameter("outputFileName", "cmsDD4HepGeom.root")), - m_label(iConfig.getParameter("DDDetector")) {} + m_label(iConfig.getParameter("DDDetector")), + m_token(esConsumes(m_label)) {} void DDTestDumpFile::analyze(const Event&, const EventSetup& iEventSetup) { LogVerbatim("Geometry") << "DDTestDumpFile::analyze: " << m_label; - ESTransientHandle det; - iEventSetup.get().get(m_label, det); + ESTransientHandle det = iEventSetup.getTransientHandle(m_token); TGeoManager& geom = det->manager(); diff --git a/DetectorDescription/DDCMS/plugins/test/DDTestDumpGeometry.cc b/DetectorDescription/DDCMS/plugins/test/DDTestDumpGeometry.cc index d8b7a8babd2f0..f3ef7a1e9ca53 100644 --- a/DetectorDescription/DDCMS/plugins/test/DDTestDumpGeometry.cc +++ b/DetectorDescription/DDCMS/plugins/test/DDTestDumpGeometry.cc @@ -29,15 +29,15 @@ class DDTestDumpGeometry : public one::EDAnalyzer<> { private: const ESInputTag m_tag; + const ESGetToken m_token; }; DDTestDumpGeometry::DDTestDumpGeometry(const ParameterSet& iConfig) - : m_tag(iConfig.getParameter("DDDetector")) {} + : m_tag(iConfig.getParameter("DDDetector")), m_token(esConsumes(m_tag)) {} void DDTestDumpGeometry::analyze(const Event&, const EventSetup& iEventSetup) { LogVerbatim("Geometry") << "DDTestDumpGeometry::analyze: " << m_tag; - ESTransientHandle det; - iEventSetup.get().get(m_tag, det); + ESTransientHandle det = iEventSetup.getTransientHandle(m_token); TGeoManager const& geom = det->manager(); diff --git a/DetectorDescription/DDCMS/plugins/test/DDTestFilteredView.cc b/DetectorDescription/DDCMS/plugins/test/DDTestFilteredView.cc index b71982d161ea6..6375eb3a4bb20 100644 --- a/DetectorDescription/DDCMS/plugins/test/DDTestFilteredView.cc +++ b/DetectorDescription/DDCMS/plugins/test/DDTestFilteredView.cc @@ -15,7 +15,8 @@ using namespace edm; class DDTestFilteredView : public one::EDAnalyzer<> { public: - explicit DDTestFilteredView(const ParameterSet& iConfig) : m_tag(iConfig.getParameter("DDDetector")) {} + explicit DDTestFilteredView(const ParameterSet& iConfig) + : m_tag(iConfig.getParameter("DDDetector")), m_token(esConsumes(m_tag)) {} void beginJob() override {} void analyze(Event const& iEvent, EventSetup const&) override; @@ -23,12 +24,12 @@ class DDTestFilteredView : public one::EDAnalyzer<> { private: const ESInputTag m_tag; + const ESGetToken m_token; }; void DDTestFilteredView::analyze(const Event&, const EventSetup& iEventSetup) { LogVerbatim("Geometry") << "DDTestFilteredView::analyze: " << m_tag; - ESTransientHandle cpv; - iEventSetup.get().get(m_tag, cpv); + ESTransientHandle cpv = iEventSetup.getTransientHandle(m_token); DDFilteredView fv(cpv->detector(), cpv->detector()->worldVolume()); diff --git a/DetectorDescription/DDCMS/plugins/test/DDTestSpecPars.cc b/DetectorDescription/DDCMS/plugins/test/DDTestSpecPars.cc index 3ed77010eb060..e17dc4c11ada8 100644 --- a/DetectorDescription/DDCMS/plugins/test/DDTestSpecPars.cc +++ b/DetectorDescription/DDCMS/plugins/test/DDTestSpecPars.cc @@ -1,4 +1,4 @@ -#include "FWCore/Framework/interface/one/EDAnalyzer.h" +#include "FWCore/Framework/interface/global/EDAnalyzer.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/Framework/interface/ESTransientHandle.h" #include "FWCore/Framework/interface/EventSetup.h" @@ -12,24 +12,25 @@ using namespace std; using namespace cms; using namespace edm; -class DDTestSpecPars : public one::EDAnalyzer<> { +class DDTestSpecPars : public global::EDAnalyzer<> { public: - explicit DDTestSpecPars(const ParameterSet& iConfig) : m_tag(iConfig.getParameter("DDDetector")) {} + explicit DDTestSpecPars(const ParameterSet& iConfig) + : m_tag(iConfig.getParameter("DDDetector")), m_token(esConsumes(m_tag)) {} void beginJob() override {} - void analyze(Event const& iEvent, EventSetup const&) override; + void analyze(StreamID, Event const& iEvent, EventSetup const&) const override; void endJob() override {} private: const ESInputTag m_tag; + const ESGetToken m_token; }; -void DDTestSpecPars::analyze(const Event&, const EventSetup& iEventSetup) { - LogVerbatim("Geometry") << "DDTestSpecPars::analyze: " << m_tag; - ESTransientHandle registry; - iEventSetup.get().get(m_tag, registry); +void DDTestSpecPars::analyze(StreamID, const Event&, const EventSetup& iEventSetup) const { + ESTransientHandle registry = iEventSetup.getTransientHandle(m_token); - LogVerbatim("Geometry").log([®istry](auto& log) { + LogVerbatim("Geometry").log([®istry, this](auto& log) { + log << "DDTestSpecPars::analyze: " << m_tag; log << "DD SpecPar Registry size: " << registry->specpars.size(); for (const auto& i : registry->specpars) { log << " " << i.first << " =>"; diff --git a/DetectorDescription/DDCMS/plugins/test/DDTestSpecParsFilter.cc b/DetectorDescription/DDCMS/plugins/test/DDTestSpecParsFilter.cc index 503825ff89dd2..6d01b703227b0 100644 --- a/DetectorDescription/DDCMS/plugins/test/DDTestSpecParsFilter.cc +++ b/DetectorDescription/DDCMS/plugins/test/DDTestSpecParsFilter.cc @@ -17,6 +17,7 @@ class DDTestSpecParsFilter : public one::EDAnalyzer<> { public: explicit DDTestSpecParsFilter(const ParameterSet& iConfig) : m_tag(iConfig.getParameter("DDDetector")), + m_token(esConsumes(m_tag)), m_attribute(iConfig.getUntrackedParameter("attribute", "")), m_value(iConfig.getUntrackedParameter("value", "")) {} @@ -26,14 +27,14 @@ class DDTestSpecParsFilter : public one::EDAnalyzer<> { private: const ESInputTag m_tag; + const ESGetToken m_token; const string m_attribute; const string m_value; }; void DDTestSpecParsFilter::analyze(const Event&, const EventSetup& iEventSetup) { LogVerbatim("Geometry") << "DDTestSpecParsFilter::analyze: " << m_tag; - ESTransientHandle registry; - iEventSetup.get().get(m_tag, registry); + ESTransientHandle registry = iEventSetup.getTransientHandle(m_token); LogVerbatim("Geometry") << "DDTestSpecParsFilter::analyze: " << m_tag << " for attribute " << m_attribute << " and value " << m_value; diff --git a/DetectorDescription/DDCMS/plugins/test/DDTestVectors.cc b/DetectorDescription/DDCMS/plugins/test/DDTestVectors.cc index 6dd4830d77619..569bb6c4d8c16 100644 --- a/DetectorDescription/DDCMS/plugins/test/DDTestVectors.cc +++ b/DetectorDescription/DDCMS/plugins/test/DDTestVectors.cc @@ -1,4 +1,4 @@ -#include "FWCore/Framework/interface/one/EDAnalyzer.h" +#include "FWCore/Framework/interface/global/EDAnalyzer.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/Framework/interface/ESTransientHandle.h" #include "FWCore/Framework/interface/EventSetup.h" @@ -12,24 +12,25 @@ using namespace std; using namespace cms; using namespace edm; -class DDTestVectors : public one::EDAnalyzer<> { +class DDTestVectors : public global::EDAnalyzer<> { public: - explicit DDTestVectors(const ParameterSet& iConfig) : m_tag(iConfig.getParameter("DDDetector")) {} + explicit DDTestVectors(const ParameterSet& iConfig) + : m_tag(iConfig.getParameter("DDDetector")), m_token(esConsumes(m_tag)) {} void beginJob() override {} - void analyze(Event const& iEvent, EventSetup const&) override; + void analyze(StreamID, Event const& iEvent, EventSetup const&) const override; void endJob() override {} private: const ESInputTag m_tag; + const ESGetToken m_token; }; -void DDTestVectors::analyze(const Event&, const EventSetup& iEventSetup) { - LogVerbatim("Geometry") << "DDTestVectors::analyze: " << m_tag; - ESTransientHandle registry; - iEventSetup.get().get(m_tag, registry); +void DDTestVectors::analyze(StreamID, const Event&, const EventSetup& iEventSetup) const { + ESTransientHandle registry = iEventSetup.getTransientHandle(m_token); - LogVerbatim("Geometry").log([®istry](auto& log) { + LogVerbatim("Geometry").log([®istry, this](auto& log) { + log << "DDTestVectors::analyze: " << m_tag; log << "DD Vector Registry size: " << registry->vectors.size() << "\n"; for (const auto& p : registry->vectors) { log << " " << p.first << " => "; diff --git a/DetectorDescription/OfflineDBLoader/src/DDCoreToDDXMLOutput.cc b/DetectorDescription/OfflineDBLoader/src/DDCoreToDDXMLOutput.cc index 422d6605e4b86..878988b972f24 100644 --- a/DetectorDescription/OfflineDBLoader/src/DDCoreToDDXMLOutput.cc +++ b/DetectorDescription/OfflineDBLoader/src/DDCoreToDDXMLOutput.cc @@ -180,6 +180,10 @@ void DDCoreToDDXMLOutput::solid(const dd4hep::Solid& solid, const cms::DDParsing } case cms::DDSolidShape::ddtrap: { dd4hep::Trap rs(solid); + xos << std::setprecision(8); + // Precision of 8 is needed to prevent complaints from Native Geant4 10.7 about + // small deviations from planarity of trapezoid faces. + xos << "" << std::endl; + xos << std::setprecision(5); + // Before CMSSW_12_1_0_pre5, all solids, including Trapezoids, had precision of 5. + // In tests With Native Geant4 10.7, this precision caused complaints, as explained above. + // To minimize changes, the precision was increased only for Trapezoids. + // In future, when there is an opportunity to revise the geometry, it might be + // desirable to use precision of 8 for all solids for consistency. break; } case cms::DDSolidShape::ddcons: { diff --git a/Documentation/ReferenceManualScripts/python/BeautifulSoup.py b/Documentation/ReferenceManualScripts/python/BeautifulSoup.py deleted file mode 100644 index beee856e507e7..0000000000000 --- a/Documentation/ReferenceManualScripts/python/BeautifulSoup.py +++ /dev/null @@ -1,2018 +0,0 @@ -"""Beautiful Soup -Elixir and Tonic -"The Screen-Scraper's Friend" -http://www.crummy.com/software/BeautifulSoup/ - -Beautiful Soup parses a (possibly invalid) XML or HTML document into a -tree representation. It provides methods and Pythonic idioms that make -it easy to navigate, search, and modify the tree. - -A well-formed XML/HTML document yields a well-formed data -structure. An ill-formed XML/HTML document yields a correspondingly -ill-formed data structure. If your document is only locally -well-formed, you can use this library to find and process the -well-formed part of it. - -Beautiful Soup works with Python 2.2 and up. It has no external -dependencies, but you'll have more success at converting data to UTF-8 -if you also install these three packages: - -* chardet, for auto-detecting character encodings - http://chardet.feedparser.org/ -* cjkcodecs and iconv_codec, which add more encodings to the ones supported - by stock Python. - http://cjkpython.i18n.org/ - -Beautiful Soup defines classes for two main parsing strategies: - - * BeautifulStoneSoup, for parsing XML, SGML, or your domain-specific - language that kind of looks like XML. - - * BeautifulSoup, for parsing run-of-the-mill HTML code, be it valid - or invalid. This class has web browser-like heuristics for - obtaining a sensible parse tree in the face of common HTML errors. - -Beautiful Soup also defines a class (UnicodeDammit) for autodetecting -the encoding of an HTML or XML document, and converting it to -Unicode. Much of this code is taken from Mark Pilgrim's Universal Feed Parser. - -For more than you ever wanted to know about Beautiful Soup, see the -documentation: -http://www.crummy.com/software/BeautifulSoup/documentation.html - -Here, have some legalese: - -Copyright (c) 2004-2010, Leonard Richardson - -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following - disclaimer in the documentation and/or other materials provided - with the distribution. - - * Neither the name of the the Beautiful Soup Consortium and All - Night Kosher Bakery nor the names of its contributors may be - used to endorse or promote products derived from this software - without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR -CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE, DAMMIT. - -""" -from __future__ import generators -from __future__ import print_function - -__author__ = "Leonard Richardson (leonardr@segfault.org)" -__version__ = "3.2.1" -__copyright__ = "Copyright (c) 2004-2012 Leonard Richardson" -__license__ = "New-style BSD" - -from sgmllib import SGMLParser, SGMLParseError -import codecs -import markupbase -import types -import re -import sgmllib -try: - from htmlentitydefs import name2codepoint -except ImportError: - name2codepoint = {} -try: - set -except NameError: - from sets import Set as set - -#These hacks make Beautiful Soup able to parse XML with namespaces -sgmllib.tagfind = re.compile('[a-zA-Z][-_.:a-zA-Z0-9]*') -markupbase._declname_match = re.compile(r'[a-zA-Z][-_.:a-zA-Z0-9]*\s*').match - -DEFAULT_OUTPUT_ENCODING = "utf-8" - -def _match_css_class(str): - """Build a RE to match the given CSS class.""" - return re.compile(r"(^|.*\s)%s($|\s)" % str) - -# First, the classes that represent markup elements. - -class PageElement(object): - """Contains the navigational information for some part of the page - (either a tag or a piece of text)""" - - def _invert(h): - "Cheap function to invert a hash." - i = {} - for k,v in h.items(): - i[v] = k - return i - - XML_ENTITIES_TO_SPECIAL_CHARS = { "apos" : "'", - "quot" : '"', - "amp" : "&", - "lt" : "<", - "gt" : ">" } - - XML_SPECIAL_CHARS_TO_ENTITIES = _invert(XML_ENTITIES_TO_SPECIAL_CHARS) - - def setup(self, parent=None, previous=None): - """Sets up the initial relations between this element and - other elements.""" - self.parent = parent - self.previous = previous - self.next = None - self.previousSibling = None - self.nextSibling = None - if self.parent and self.parent.contents: - self.previousSibling = self.parent.contents[-1] - self.previousSibling.nextSibling = self - - def replaceWith(self, replaceWith): - oldParent = self.parent - myIndex = self.parent.index(self) - if hasattr(replaceWith, "parent")\ - and replaceWith.parent is self.parent: - # We're replacing this element with one of its siblings. - index = replaceWith.parent.index(replaceWith) - if index and index < myIndex: - # Furthermore, it comes before this element. That - # means that when we extract it, the index of this - # element will change. - myIndex = myIndex - 1 - self.extract() - oldParent.insert(myIndex, replaceWith) - - def replaceWithChildren(self): - myParent = self.parent - myIndex = self.parent.index(self) - self.extract() - reversedChildren = list(self.contents) - reversedChildren.reverse() - for child in reversedChildren: - myParent.insert(myIndex, child) - - def extract(self): - """Destructively rips this element out of the tree.""" - if self.parent: - try: - del self.parent.contents[self.parent.index(self)] - except ValueError: - pass - - #Find the two elements that would be next to each other if - #this element (and any children) hadn't been parsed. Connect - #the two. - lastChild = self._lastRecursiveChild() - nextElement = lastChild.next - - if self.previous: - self.previous.next = nextElement - if nextElement: - nextElement.previous = self.previous - self.previous = None - lastChild.next = None - - self.parent = None - if self.previousSibling: - self.previousSibling.nextSibling = self.nextSibling - if self.nextSibling: - self.nextSibling.previousSibling = self.previousSibling - self.previousSibling = self.nextSibling = None - return self - - def _lastRecursiveChild(self): - "Finds the last element beneath this object to be parsed." - lastChild = self - while hasattr(lastChild, 'contents') and lastChild.contents: - lastChild = lastChild.contents[-1] - return lastChild - - def insert(self, position, newChild): - if isinstance(newChild, str) \ - and not isinstance(newChild, NavigableString): - newChild = NavigableString(newChild) - - position = min(position, len(self.contents)) - if hasattr(newChild, 'parent') and newChild.parent is not None: - # We're 'inserting' an element that's already one - # of this object's children. - if newChild.parent is self: - index = self.index(newChild) - if index > position: - # Furthermore we're moving it further down the - # list of this object's children. That means that - # when we extract this element, our target index - # will jump down one. - position = position - 1 - newChild.extract() - - newChild.parent = self - previousChild = None - if position == 0: - newChild.previousSibling = None - newChild.previous = self - else: - previousChild = self.contents[position-1] - newChild.previousSibling = previousChild - newChild.previousSibling.nextSibling = newChild - newChild.previous = previousChild._lastRecursiveChild() - if newChild.previous: - newChild.previous.next = newChild - - newChildsLastElement = newChild._lastRecursiveChild() - - if position >= len(self.contents): - newChild.nextSibling = None - - parent = self - parentsNextSibling = None - while not parentsNextSibling: - parentsNextSibling = parent.nextSibling - parent = parent.parent - if not parent: # This is the last element in the document. - break - if parentsNextSibling: - newChildsLastElement.next = parentsNextSibling - else: - newChildsLastElement.next = None - else: - nextChild = self.contents[position] - newChild.nextSibling = nextChild - if newChild.nextSibling: - newChild.nextSibling.previousSibling = newChild - newChildsLastElement.next = nextChild - - if newChildsLastElement.next: - newChildsLastElement.next.previous = newChildsLastElement - self.contents.insert(position, newChild) - - def append(self, tag): - """Appends the given tag to the contents of this tag.""" - self.insert(len(self.contents), tag) - - def findNext(self, name=None, attrs={}, text=None, **kwargs): - """Returns the first item that matches the given criteria and - appears after this Tag in the document.""" - return self._findOne(self.findAllNext, name, attrs, text, **kwargs) - - def findAllNext(self, name=None, attrs={}, text=None, limit=None, - **kwargs): - """Returns all items that match the given criteria and appear - after this Tag in the document.""" - return self._findAll(name, attrs, text, limit, self.nextGenerator, - **kwargs) - - def findNextSibling(self, name=None, attrs={}, text=None, **kwargs): - """Returns the closest sibling to this Tag that matches the - given criteria and appears after this Tag in the document.""" - return self._findOne(self.findNextSiblings, name, attrs, text, - **kwargs) - - def findNextSiblings(self, name=None, attrs={}, text=None, limit=None, - **kwargs): - """Returns the siblings of this Tag that match the given - criteria and appear after this Tag in the document.""" - return self._findAll(name, attrs, text, limit, - self.nextSiblingGenerator, **kwargs) - fetchNextSiblings = findNextSiblings # Compatibility with pre-3.x - - def findPrevious(self, name=None, attrs={}, text=None, **kwargs): - """Returns the first item that matches the given criteria and - appears before this Tag in the document.""" - return self._findOne(self.findAllPrevious, name, attrs, text, **kwargs) - - def findAllPrevious(self, name=None, attrs={}, text=None, limit=None, - **kwargs): - """Returns all items that match the given criteria and appear - before this Tag in the document.""" - return self._findAll(name, attrs, text, limit, self.previousGenerator, - **kwargs) - fetchPrevious = findAllPrevious # Compatibility with pre-3.x - - def findPreviousSibling(self, name=None, attrs={}, text=None, **kwargs): - """Returns the closest sibling to this Tag that matches the - given criteria and appears before this Tag in the document.""" - return self._findOne(self.findPreviousSiblings, name, attrs, text, - **kwargs) - - def findPreviousSiblings(self, name=None, attrs={}, text=None, - limit=None, **kwargs): - """Returns the siblings of this Tag that match the given - criteria and appear before this Tag in the document.""" - return self._findAll(name, attrs, text, limit, - self.previousSiblingGenerator, **kwargs) - fetchPreviousSiblings = findPreviousSiblings # Compatibility with pre-3.x - - def findParent(self, name=None, attrs={}, **kwargs): - """Returns the closest parent of this Tag that matches the given - criteria.""" - # NOTE: We can't use _findOne because findParents takes a different - # set of arguments. - r = None - l = self.findParents(name, attrs, 1) - if l: - r = l[0] - return r - - def findParents(self, name=None, attrs={}, limit=None, **kwargs): - """Returns the parents of this Tag that match the given - criteria.""" - - return self._findAll(name, attrs, None, limit, self.parentGenerator, - **kwargs) - fetchParents = findParents # Compatibility with pre-3.x - - #These methods do the real heavy lifting. - - def _findOne(self, method, name, attrs, text, **kwargs): - r = None - l = method(name, attrs, text, 1, **kwargs) - if l: - r = l[0] - return r - - def _findAll(self, name, attrs, text, limit, generator, **kwargs): - "Iterates over a generator looking for things that match." - - if isinstance(name, SoupStrainer): - strainer = name - # (Possibly) special case some findAll*(...) searches - elif text is None and not limit and not attrs and not kwargs: - # findAll*(True) - if name is True: - return [element for element in generator() - if isinstance(element, Tag)] - # findAll*('tag-name') - elif isinstance(name, str): - return [element for element in generator() - if isinstance(element, Tag) and - element.name == name] - else: - strainer = SoupStrainer(name, attrs, text, **kwargs) - # Build a SoupStrainer - else: - strainer = SoupStrainer(name, attrs, text, **kwargs) - results = ResultSet(strainer) - g = generator() - while True: - try: - i = next(g) - except StopIteration: - break - if i: - found = strainer.search(i) - if found: - results.append(found) - if limit and len(results) >= limit: - break - return results - - #These Generators can be used to navigate starting from both - #NavigableStrings and Tags. - def nextGenerator(self): - i = self - while i is not None: - i = i.next - yield i - - def nextSiblingGenerator(self): - i = self - while i is not None: - i = i.nextSibling - yield i - - def previousGenerator(self): - i = self - while i is not None: - i = i.previous - yield i - - def previousSiblingGenerator(self): - i = self - while i is not None: - i = i.previousSibling - yield i - - def parentGenerator(self): - i = self - while i is not None: - i = i.parent - yield i - - # Utility methods - def substituteEncoding(self, str, encoding=None): - encoding = encoding or "utf-8" - return str.replace("%SOUP-ENCODING%", encoding) - - def toEncoding(self, s, encoding=None): - """Encodes an object to a string in some encoding, or to Unicode. - .""" - if isinstance(s, unicode): - if encoding: - s = s.encode(encoding) - elif isinstance(s, str): - if encoding: - s = s.encode(encoding) - else: - s = unicode(s) - else: - if encoding: - s = self.toEncoding(str(s), encoding) - else: - s = unicode(s) - return s - - BARE_AMPERSAND_OR_BRACKET = re.compile("([<>]|" - + "&(?!#\d+;|#x[0-9a-fA-F]+;|\w+;)" - + ")") - - def _sub_entity(self, x): - """Used with a regular expression to substitute the - appropriate XML entity for an XML special character.""" - return "&" + self.XML_SPECIAL_CHARS_TO_ENTITIES[x.group(0)[0]] + ";" - - -class NavigableString(unicode, PageElement): - - def __new__(cls, value): - """Create a new NavigableString. - - When unpickling a NavigableString, this method is called with - the string in DEFAULT_OUTPUT_ENCODING. That encoding needs to be - passed in to the superclass's __new__ or the superclass won't know - how to handle non-ASCII characters. - """ - if isinstance(value, unicode): - return unicode.__new__(cls, value) - return unicode.__new__(cls, value, DEFAULT_OUTPUT_ENCODING) - - def __getnewargs__(self): - return (NavigableString.__str__(self),) - - def __getattr__(self, attr): - """text.string gives you text. This is for backwards - compatibility for Navigable*String, but for CData* it lets you - get the string without the CData wrapper.""" - if attr == 'string': - return self - else: - raise AttributeError("'%s' object has no attribute '%s'" % (self.__class__.__name__, attr)) - - def __unicode__(self): - return str(self).decode(DEFAULT_OUTPUT_ENCODING) - - def __str__(self, encoding=DEFAULT_OUTPUT_ENCODING): - # Substitute outgoing XML entities. - data = self.BARE_AMPERSAND_OR_BRACKET.sub(self._sub_entity, self) - if encoding: - return data.encode(encoding) - else: - return data - -class CData(NavigableString): - - def __str__(self, encoding=DEFAULT_OUTPUT_ENCODING): - return "" % NavigableString.__str__(self, encoding) - -class ProcessingInstruction(NavigableString): - def __str__(self, encoding=DEFAULT_OUTPUT_ENCODING): - output = self - if "%SOUP-ENCODING%" in output: - output = self.substituteEncoding(output, encoding) - return "" % self.toEncoding(output, encoding) - -class Comment(NavigableString): - def __str__(self, encoding=DEFAULT_OUTPUT_ENCODING): - return "" % NavigableString.__str__(self, encoding) - -class Declaration(NavigableString): - def __str__(self, encoding=DEFAULT_OUTPUT_ENCODING): - return "" % NavigableString.__str__(self, encoding) - -class Tag(PageElement): - - """Represents a found HTML tag with its attributes and contents.""" - - def _convertEntities(self, match): - """Used in a call to re.sub to replace HTML, XML, and numeric - entities with the appropriate Unicode characters. If HTML - entities are being converted, any unrecognized entities are - escaped.""" - x = match.group(1) - if self.convertHTMLEntities and x in name2codepoint: - return unichr(name2codepoint[x]) - elif x in self.XML_ENTITIES_TO_SPECIAL_CHARS: - if self.convertXMLEntities: - return self.XML_ENTITIES_TO_SPECIAL_CHARS[x] - else: - return u'&%s;' % x - elif len(x) > 0 and x[0] == '#': - # Handle numeric entities - if len(x) > 1 and x[1] == 'x': - return unichr(int(x[2:], 16)) - else: - return unichr(int(x[1:])) - - elif self.escapeUnrecognizedEntities: - return u'&%s;' % x - else: - return u'&%s;' % x - - def __init__(self, parser, name, attrs=None, parent=None, - previous=None): - "Basic constructor." - - # We don't actually store the parser object: that lets extracted - # chunks be garbage-collected - self.parserClass = parser.__class__ - self.isSelfClosing = parser.isSelfClosingTag(name) - self.name = name - if attrs is None: - attrs = [] - elif isinstance(attrs, dict): - attrs = attrs.items() - self.attrs = attrs - self.contents = [] - self.setup(parent, previous) - self.hidden = False - self.containsSubstitutions = False - self.convertHTMLEntities = parser.convertHTMLEntities - self.convertXMLEntities = parser.convertXMLEntities - self.escapeUnrecognizedEntities = parser.escapeUnrecognizedEntities - - # Convert any HTML, XML, or numeric entities in the attribute values. - convert = lambda k_val: (k_val[0], - re.sub("&(#\d+|#x[0-9a-fA-F]+|\w+);", - self._convertEntities, - k_val[1])) - self.attrs = map(convert, self.attrs) - - def getString(self): - if (len(self.contents) == 1 - and isinstance(self.contents[0], NavigableString)): - return self.contents[0] - - def setString(self, string): - """Replace the contents of the tag with a string""" - self.clear() - self.append(string) - - string = property(getString, setString) - - def getText(self, separator=u""): - if not len(self.contents): - return u"" - stopNode = self._lastRecursiveChild().next - strings = [] - current = self.contents[0] - while current is not stopNode: - if isinstance(current, NavigableString): - strings.append(current.strip()) - current = current.next - return separator.join(strings) - - text = property(getText) - - def get(self, key, default=None): - """Returns the value of the 'key' attribute for the tag, or - the value given for 'default' if it doesn't have that - attribute.""" - return self._getAttrMap().get(key, default) - - def clear(self): - """Extract all children.""" - for child in self.contents[:]: - child.extract() - - def index(self, element): - for i, child in enumerate(self.contents): - if child is element: - return i - raise ValueError("Tag.index: element not in tag") - - def has_key(self, key): - return key in self._getAttrMap() - - def __getitem__(self, key): - """tag[key] returns the value of the 'key' attribute for the tag, - and throws an exception if it's not there.""" - return self._getAttrMap()[key] - - def __iter__(self): - "Iterating over a tag iterates over its contents." - return iter(self.contents) - - def __len__(self): - "The length of a tag is the length of its list of contents." - return len(self.contents) - - def __contains__(self, x): - return x in self.contents - - def __nonzero__(self): - "A tag is non-None even if it has no contents." - return True - - def __setitem__(self, key, value): - """Setting tag[key] sets the value of the 'key' attribute for the - tag.""" - self._getAttrMap() - self.attrMap[key] = value - found = False - for i in range(0, len(self.attrs)): - if self.attrs[i][0] == key: - self.attrs[i] = (key, value) - found = True - if not found: - self.attrs.append((key, value)) - self._getAttrMap()[key] = value - - def __delitem__(self, key): - "Deleting tag[key] deletes all 'key' attributes for the tag." - for item in self.attrs: - if item[0] == key: - self.attrs.remove(item) - #We don't break because bad HTML can define the same - #attribute multiple times. - self._getAttrMap() - if key in self.attrMap: - del self.attrMap[key] - - def __call__(self, *args, **kwargs): - """Calling a tag like a function is the same as calling its - findAll() method. Eg. tag('a') returns a list of all the A tags - found within this tag.""" - return self.findAll(*args, **kwargs) - - def __getattr__(self, tag): - #print "Getattr %s.%s" % (self.__class__, tag) - if len(tag) > 3 and tag.rfind('Tag') == len(tag)-3: - return self.find(tag[:-3]) - elif tag.find('__') != 0: - return self.find(tag) - raise AttributeError("'%s' object has no attribute '%s'" % (self.__class__, tag)) - - def __eq__(self, other): - """Returns true iff this tag has the same name, the same attributes, - and the same contents (recursively) as the given tag. - - NOTE: right now this will return false if two tags have the - same attributes in a different order. Should this be fixed?""" - if other is self: - return True - if not hasattr(other, 'name') or not hasattr(other, 'attrs') or not hasattr(other, 'contents') or self.name != other.name or self.attrs != other.attrs or len(self) != len(other): - return False - for i in range(0, len(self.contents)): - if self.contents[i] != other.contents[i]: - return False - return True - - def __ne__(self, other): - """Returns true iff this tag is not identical to the other tag, - as defined in __eq__.""" - return not self == other - - def __repr__(self, encoding=DEFAULT_OUTPUT_ENCODING): - """Renders this tag as a string.""" - return self.__str__(encoding) - - def __unicode__(self): - return self.__str__(None) - - def __str__(self, encoding=DEFAULT_OUTPUT_ENCODING, - prettyPrint=False, indentLevel=0): - """Returns a string or Unicode representation of this tag and - its contents. To get Unicode, pass None for encoding. - - NOTE: since Python's HTML parser consumes whitespace, this - method is not certain to reproduce the whitespace present in - the original string.""" - - encodedName = self.toEncoding(self.name, encoding) - - attrs = [] - if self.attrs: - for key, val in self.attrs: - fmt = '%s="%s"' - if isinstance(val, str): - if self.containsSubstitutions and '%SOUP-ENCODING%' in val: - val = self.substituteEncoding(val, encoding) - - # The attribute value either: - # - # * Contains no embedded double quotes or single quotes. - # No problem: we enclose it in double quotes. - # * Contains embedded single quotes. No problem: - # double quotes work here too. - # * Contains embedded double quotes. No problem: - # we enclose it in single quotes. - # * Embeds both single _and_ double quotes. This - # can't happen naturally, but it can happen if - # you modify an attribute value after parsing - # the document. Now we have a bit of a - # problem. We solve it by enclosing the - # attribute in single quotes, and escaping any - # embedded single quotes to XML entities. - if '"' in val: - fmt = "%s='%s'" - if "'" in val: - # TODO: replace with apos when - # appropriate. - val = val.replace("'", "&squot;") - - # Now we're okay w/r/t quotes. But the attribute - # value might also contain angle brackets, or - # ampersands that aren't part of entities. We need - # to escape those to XML entities too. - val = self.BARE_AMPERSAND_OR_BRACKET.sub(self._sub_entity, val) - - attrs.append(fmt % (self.toEncoding(key, encoding), - self.toEncoding(val, encoding))) - close = '' - closeTag = '' - if self.isSelfClosing: - close = ' /' - else: - closeTag = '' % encodedName - - indentTag, indentContents = 0, 0 - if prettyPrint: - indentTag = indentLevel - space = (' ' * (indentTag-1)) - indentContents = indentTag + 1 - contents = self.renderContents(encoding, prettyPrint, indentContents) - if self.hidden: - s = contents - else: - s = [] - attributeString = '' - if attrs: - attributeString = ' ' + ' '.join(attrs) - if prettyPrint: - s.append(space) - s.append('<%s%s%s>' % (encodedName, attributeString, close)) - if prettyPrint: - s.append("\n") - s.append(contents) - if prettyPrint and contents and contents[-1] != "\n": - s.append("\n") - if prettyPrint and closeTag: - s.append(space) - s.append(closeTag) - if prettyPrint and closeTag and self.nextSibling: - s.append("\n") - s = ''.join(s) - return s - - def decompose(self): - """Recursively destroys the contents of this tree.""" - self.extract() - if len(self.contents) == 0: - return - current = self.contents[0] - while current is not None: - next = current.next - if isinstance(current, Tag): - del current.contents[:] - current.parent = None - current.previous = None - current.previousSibling = None - current.next = None - current.nextSibling = None - current = next - - def prettify(self, encoding=DEFAULT_OUTPUT_ENCODING): - return self.__str__(encoding, True) - - def renderContents(self, encoding=DEFAULT_OUTPUT_ENCODING, - prettyPrint=False, indentLevel=0): - """Renders the contents of this tag as a string in the given - encoding. If encoding is None, returns a Unicode string..""" - s=[] - for c in self: - text = None - if isinstance(c, NavigableString): - text = c.__str__(encoding) - elif isinstance(c, Tag): - s.append(c.__str__(encoding, prettyPrint, indentLevel)) - if text and prettyPrint: - text = text.strip() - if text: - if prettyPrint: - s.append(" " * (indentLevel-1)) - s.append(text) - if prettyPrint: - s.append("\n") - return ''.join(s) - - #Soup methods - - def find(self, name=None, attrs={}, recursive=True, text=None, - **kwargs): - """Return only the first child of this Tag matching the given - criteria.""" - r = None - l = self.findAll(name, attrs, recursive, text, 1, **kwargs) - if l: - r = l[0] - return r - findChild = find - - def findAll(self, name=None, attrs={}, recursive=True, text=None, - limit=None, **kwargs): - """Extracts a list of Tag objects that match the given - criteria. You can specify the name of the Tag and any - attributes you want the Tag to have. - - The value of a key-value pair in the 'attrs' map can be a - string, a list of strings, a regular expression object, or a - callable that takes a string and returns whether or not the - string matches for some custom definition of 'matches'. The - same is true of the tag name.""" - generator = self.recursiveChildGenerator - if not recursive: - generator = self.childGenerator - return self._findAll(name, attrs, text, limit, generator, **kwargs) - findChildren = findAll - - # Pre-3.x compatibility methods - first = find - fetch = findAll - - def fetchText(self, text=None, recursive=True, limit=None): - return self.findAll(text=text, recursive=recursive, limit=limit) - - def firstText(self, text=None, recursive=True): - return self.find(text=text, recursive=recursive) - - #Private methods - - def _getAttrMap(self): - """Initializes a map representation of this tag's attributes, - if not already initialized.""" - if not getattr(self, 'attrMap'): - self.attrMap = {} - for (key, value) in self.attrs: - self.attrMap[key] = value - return self.attrMap - - #Generator methods - def childGenerator(self): - # Just use the iterator from the contents - return iter(self.contents) - - def recursiveChildGenerator(self): - if not len(self.contents): - raise StopIteration - stopNode = self._lastRecursiveChild().next - current = self.contents[0] - while current is not stopNode: - yield current - current = current.next - - -# Next, a couple classes to represent queries and their results. -class SoupStrainer: - """Encapsulates a number of ways of matching a markup element (tag or - text).""" - - def __init__(self, name=None, attrs={}, text=None, **kwargs): - self.name = name - if isinstance(attrs, str): - kwargs['class'] = _match_css_class(attrs) - attrs = None - if kwargs: - if attrs: - attrs = attrs.copy() - attrs.update(kwargs) - else: - attrs = kwargs - self.attrs = attrs - self.text = text - - def __str__(self): - if self.text: - return self.text - else: - return "%s|%s" % (self.name, self.attrs) - - def searchTag(self, markupName=None, markupAttrs={}): - found = None - markup = None - if isinstance(markupName, Tag): - markup = markupName - markupAttrs = markup - callFunctionWithTagData = callable(self.name) \ - and not isinstance(markupName, Tag) - - if (not self.name) \ - or callFunctionWithTagData \ - or (markup and self._matches(markup, self.name)) \ - or (not markup and self._matches(markupName, self.name)): - if callFunctionWithTagData: - match = self.name(markupName, markupAttrs) - else: - match = True - markupAttrMap = None - for attr, matchAgainst in self.attrs.items(): - if not markupAttrMap: - if hasattr(markupAttrs, 'get'): - markupAttrMap = markupAttrs - else: - markupAttrMap = {} - for k,v in markupAttrs: - markupAttrMap[k] = v - attrValue = markupAttrMap.get(attr) - if not self._matches(attrValue, matchAgainst): - match = False - break - if match: - if markup: - found = markup - else: - found = markupName - return found - - def search(self, markup): - #print 'looking for %s in %s' % (self, markup) - found = None - # If given a list of items, scan it for a text element that - # matches. - if hasattr(markup, "__iter__") \ - and not isinstance(markup, Tag): - for element in markup: - if isinstance(element, NavigableString) \ - and self.search(element): - found = element - break - # If it's a Tag, make sure its name or attributes match. - # Don't bother with Tags if we're searching for text. - elif isinstance(markup, Tag): - if not self.text: - found = self.searchTag(markup) - # If it's text, make sure the text matches. - elif isinstance(markup, NavigableString) or \ - isinstance(markup, str): - if self._matches(markup, self.text): - found = markup - else: - raise Exception("I don't know how to match against a %s" \ - % markup.__class__) - return found - - def _matches(self, markup, matchAgainst): - #print "Matching %s against %s" % (markup, matchAgainst) - result = False - if matchAgainst is True: - result = markup is not None - elif callable(matchAgainst): - result = matchAgainst(markup) - else: - #Custom match methods take the tag as an argument, but all - #other ways of matching match the tag name as a string. - if isinstance(markup, Tag): - markup = markup.name - if markup and not isinstance(markup, str): - markup = unicode(markup) - #Now we know that chunk is either a string, or None. - if hasattr(matchAgainst, 'match'): - # It's a regexp object. - result = markup and matchAgainst.search(markup) - elif hasattr(matchAgainst, '__iter__'): # list-like - result = markup in matchAgainst - elif hasattr(matchAgainst, 'items'): - result = matchAgainst in markup - elif matchAgainst and isinstance(markup, str): - if isinstance(markup, unicode): - matchAgainst = unicode(matchAgainst) - else: - matchAgainst = str(matchAgainst) - - if not result: - result = matchAgainst == markup - return result - -class ResultSet(list): - """A ResultSet is just a list that keeps track of the SoupStrainer - that created it.""" - def __init__(self, source): - list.__init__([]) - self.source = source - -# Now, some helper functions. - -def buildTagMap(default, *args): - """Turns a list of maps, lists, or scalars into a single map. - Used to build the SELF_CLOSING_TAGS, NESTABLE_TAGS, and - NESTING_RESET_TAGS maps out of lists and partial maps.""" - built = {} - for portion in args: - if hasattr(portion, 'items'): - #It's a map. Merge it. - for k,v in portion.items(): - built[k] = v - elif hasattr(portion, '__iter__'): # is a list - #It's a list. Map each item to the default. - for k in portion: - built[k] = default - else: - #It's a scalar. Map it to the default. - built[portion] = default - return built - -# Now, the parser classes. - -class BeautifulStoneSoup(Tag, SGMLParser): - - """This class contains the basic parser and search code. It defines - a parser that knows nothing about tag behavior except for the - following: - - You can't close a tag without closing all the tags it encloses. - That is, "" actually means - "". - - [Another possible explanation is "", but since - this class defines no SELF_CLOSING_TAGS, it will never use that - explanation.] - - This class is useful for parsing XML or made-up markup languages, - or when BeautifulSoup makes an assumption counter to what you were - expecting.""" - - SELF_CLOSING_TAGS = {} - NESTABLE_TAGS = {} - RESET_NESTING_TAGS = {} - QUOTE_TAGS = {} - PRESERVE_WHITESPACE_TAGS = [] - - MARKUP_MASSAGE = [(re.compile('(<[^<>]*)/>'), - lambda x: x.group(1) + ' />'), - (re.compile(']*)>'), - lambda x: '') - ] - - ROOT_TAG_NAME = u'[document]' - - HTML_ENTITIES = "html" - XML_ENTITIES = "xml" - XHTML_ENTITIES = "xhtml" - # TODO: This only exists for backwards-compatibility - ALL_ENTITIES = XHTML_ENTITIES - - # Used when determining whether a text node is all whitespace and - # can be replaced with a single space. A text node that contains - # fancy Unicode spaces (usually non-breaking) should be left - # alone. - STRIP_ASCII_SPACES = { 9: None, 10: None, 12: None, 13: None, 32: None, } - - def __init__(self, markup="", parseOnlyThese=None, fromEncoding=None, - markupMassage=True, smartQuotesTo=XML_ENTITIES, - convertEntities=None, selfClosingTags=None, isHTML=False): - """The Soup object is initialized as the 'root tag', and the - provided markup (which can be a string or a file-like object) - is fed into the underlying parser. - - sgmllib will process most bad HTML, and the BeautifulSoup - class has some tricks for dealing with some HTML that kills - sgmllib, but Beautiful Soup can nonetheless choke or lose data - if your data uses self-closing tags or declarations - incorrectly. - - By default, Beautiful Soup uses regexes to sanitize input, - avoiding the vast majority of these problems. If the problems - don't apply to you, pass in False for markupMassage, and - you'll get better performance. - - The default parser massage techniques fix the two most common - instances of invalid HTML that choke sgmllib: - -
(No space between name of closing tag and tag close) - (Extraneous whitespace in declaration) - - You can pass in a custom list of (RE object, replace method) - tuples to get Beautiful Soup to scrub your input the way you - want.""" - - self.parseOnlyThese = parseOnlyThese - self.fromEncoding = fromEncoding - self.smartQuotesTo = smartQuotesTo - self.convertEntities = convertEntities - # Set the rules for how we'll deal with the entities we - # encounter - if self.convertEntities: - # It doesn't make sense to convert encoded characters to - # entities even while you're converting entities to Unicode. - # Just convert it all to Unicode. - self.smartQuotesTo = None - if convertEntities == self.HTML_ENTITIES: - self.convertXMLEntities = False - self.convertHTMLEntities = True - self.escapeUnrecognizedEntities = True - elif convertEntities == self.XHTML_ENTITIES: - self.convertXMLEntities = True - self.convertHTMLEntities = True - self.escapeUnrecognizedEntities = False - elif convertEntities == self.XML_ENTITIES: - self.convertXMLEntities = True - self.convertHTMLEntities = False - self.escapeUnrecognizedEntities = False - else: - self.convertXMLEntities = False - self.convertHTMLEntities = False - self.escapeUnrecognizedEntities = False - - self.instanceSelfClosingTags = buildTagMap(None, selfClosingTags) - SGMLParser.__init__(self) - - if hasattr(markup, 'read'): # It's a file-type object. - markup = markup.read() - self.markup = markup - self.markupMassage = markupMassage - try: - self._feed(isHTML=isHTML) - except StopParsing: - pass - self.markup = None # The markup can now be GCed - - def convert_charref(self, name): - """This method fixes a bug in Python's SGMLParser.""" - try: - n = int(name) - except ValueError: - return - if not 0 <= n <= 127 : # ASCII ends at 127, not 255 - return - return self.convert_codepoint(n) - - def _feed(self, inDocumentEncoding=None, isHTML=False): - # Convert the document to Unicode. - markup = self.markup - if isinstance(markup, unicode): - if not hasattr(self, 'originalEncoding'): - self.originalEncoding = None - else: - dammit = UnicodeDammit\ - (markup, [self.fromEncoding, inDocumentEncoding], - smartQuotesTo=self.smartQuotesTo, isHTML=isHTML) - markup = dammit.unicode - self.originalEncoding = dammit.originalEncoding - self.declaredHTMLEncoding = dammit.declaredHTMLEncoding - if markup: - if self.markupMassage: - if not hasattr(self.markupMassage, "__iter__"): - self.markupMassage = self.MARKUP_MASSAGE - for fix, m in self.markupMassage: - markup = fix.sub(m, markup) - # TODO: We get rid of markupMassage so that the - # soup object can be deepcopied later on. Some - # Python installations can't copy regexes. If anyone - # was relying on the existence of markupMassage, this - # might cause problems. - del(self.markupMassage) - self.reset() - - SGMLParser.feed(self, markup) - # Close out any unfinished strings and close all the open tags. - self.endData() - while self.currentTag.name != self.ROOT_TAG_NAME: - self.popTag() - - def __getattr__(self, methodName): - """This method routes method call requests to either the SGMLParser - superclass or the Tag superclass, depending on the method name.""" - #print "__getattr__ called on %s.%s" % (self.__class__, methodName) - - if methodName.startswith('start_') or methodName.startswith('end_') \ - or methodName.startswith('do_'): - return SGMLParser.__getattr__(self, methodName) - elif not methodName.startswith('__'): - return Tag.__getattr__(self, methodName) - else: - raise AttributeError - - def isSelfClosingTag(self, name): - """Returns true iff the given string is the name of a - self-closing tag according to this parser.""" - return name in self.SELF_CLOSING_TAGS \ - or name in self.instanceSelfClosingTags - - def reset(self): - Tag.__init__(self, self, self.ROOT_TAG_NAME) - self.hidden = 1 - SGMLParser.reset(self) - self.currentData = [] - self.currentTag = None - self.tagStack = [] - self.quoteStack = [] - self.pushTag(self) - - def popTag(self): - tag = self.tagStack.pop() - - #print "Pop", tag.name - if self.tagStack: - self.currentTag = self.tagStack[-1] - return self.currentTag - - def pushTag(self, tag): - #print "Push", tag.name - if self.currentTag: - self.currentTag.contents.append(tag) - self.tagStack.append(tag) - self.currentTag = self.tagStack[-1] - - def endData(self, containerClass=NavigableString): - if self.currentData: - currentData = u''.join(self.currentData) - if (currentData.translate(self.STRIP_ASCII_SPACES) == '' and - not set([tag.name for tag in self.tagStack]).intersection( - self.PRESERVE_WHITESPACE_TAGS)): - if '\n' in currentData: - currentData = '\n' - else: - currentData = ' ' - self.currentData = [] - if self.parseOnlyThese and len(self.tagStack) <= 1 and \ - (not self.parseOnlyThese.text or \ - not self.parseOnlyThese.search(currentData)): - return - o = containerClass(currentData) - o.setup(self.currentTag, self.previous) - if self.previous: - self.previous.next = o - self.previous = o - self.currentTag.contents.append(o) - - - def _popToTag(self, name, inclusivePop=True): - """Pops the tag stack up to and including the most recent - instance of the given tag. If inclusivePop is false, pops the tag - stack up to but *not* including the most recent instqance of - the given tag.""" - #print "Popping to %s" % name - if name == self.ROOT_TAG_NAME: - return - - numPops = 0 - mostRecentTag = None - for i in range(len(self.tagStack)-1, 0, -1): - if name == self.tagStack[i].name: - numPops = len(self.tagStack)-i - break - if not inclusivePop: - numPops = numPops - 1 - - for i in range(0, numPops): - mostRecentTag = self.popTag() - return mostRecentTag - - def _smartPop(self, name): - - """We need to pop up to the previous tag of this type, unless - one of this tag's nesting reset triggers comes between this - tag and the previous tag of this type, OR unless this tag is a - generic nesting trigger and another generic nesting trigger - comes between this tag and the previous tag of this type. - - Examples: -

FooBar *

* should pop to 'p', not 'b'. -

FooBar *

* should pop to 'table', not 'p'. -

Foo

Bar *

* should pop to 'tr', not 'p'. - -

    • *
    • * should pop to 'ul', not the first 'li'. -
  • ** should pop to 'table', not the first 'tr' - tag should - implicitly close the previous tag within the same
    ** should pop to 'tr', not the first 'td' - """ - - nestingResetTriggers = self.NESTABLE_TAGS.get(name) - isNestable = nestingResetTriggers != None - isResetNesting = name in self.RESET_NESTING_TAGS - popTo = None - inclusive = True - for i in range(len(self.tagStack)-1, 0, -1): - p = self.tagStack[i] - if (not p or p.name == name) and not isNestable: - #Non-nestable tags get popped to the top or to their - #last occurance. - popTo = name - break - if (nestingResetTriggers is not None - and p.name in nestingResetTriggers) \ - or (nestingResetTriggers is None and isResetNesting - and p.name in self.RESET_NESTING_TAGS): - - #If we encounter one of the nesting reset triggers - #peculiar to this tag, or we encounter another tag - #that causes nesting to reset, pop up to but not - #including that tag. - popTo = p.name - inclusive = False - break - p = p.parent - if popTo: - self._popToTag(popTo, inclusive) - - def unknown_starttag(self, name, attrs, selfClosing=0): - #print "Start tag %s: %s" % (name, attrs) - if self.quoteStack: - #This is not a real tag. - #print "<%s> is not real!" % name - attrs = ''.join([' %s="%s"' % (x, y) for x, y in attrs]) - self.handle_data('<%s%s>' % (name, attrs)) - return - self.endData() - - if not self.isSelfClosingTag(name) and not selfClosing: - self._smartPop(name) - - if self.parseOnlyThese and len(self.tagStack) <= 1 \ - and (self.parseOnlyThese.text or not self.parseOnlyThese.searchTag(name, attrs)): - return - - tag = Tag(self, name, attrs, self.currentTag, self.previous) - if self.previous: - self.previous.next = tag - self.previous = tag - self.pushTag(tag) - if selfClosing or self.isSelfClosingTag(name): - self.popTag() - if name in self.QUOTE_TAGS: - #print "Beginning quote (%s)" % name - self.quoteStack.append(name) - self.literal = 1 - return tag - - def unknown_endtag(self, name): - #print "End tag %s" % name - if self.quoteStack and self.quoteStack[-1] != name: - #This is not a real end tag. - #print " is not real!" % name - self.handle_data('' % name) - return - self.endData() - self._popToTag(name) - if self.quoteStack and self.quoteStack[-1] == name: - self.quoteStack.pop() - self.literal = (len(self.quoteStack) > 0) - - def handle_data(self, data): - self.currentData.append(data) - - def _toStringSubclass(self, text, subclass): - """Adds a certain piece of text to the tree as a NavigableString - subclass.""" - self.endData() - self.handle_data(text) - self.endData(subclass) - - def handle_pi(self, text): - """Handle a processing instruction as a ProcessingInstruction - object, possibly one with a %SOUP-ENCODING% slot into which an - encoding will be plugged later.""" - if text[:3] == "xml": - text = u"xml version='1.0' encoding='%SOUP-ENCODING%'" - self._toStringSubclass(text, ProcessingInstruction) - - def handle_comment(self, text): - "Handle comments as Comment objects." - self._toStringSubclass(text, Comment) - - def handle_charref(self, ref): - "Handle character references as data." - if self.convertEntities: - data = unichr(int(ref)) - else: - data = '&#%s;' % ref - self.handle_data(data) - - def handle_entityref(self, ref): - """Handle entity references as data, possibly converting known - HTML and/or XML entity references to the corresponding Unicode - characters.""" - data = None - if self.convertHTMLEntities: - try: - data = unichr(name2codepoint[ref]) - except KeyError: - pass - - if not data and self.convertXMLEntities: - data = self.XML_ENTITIES_TO_SPECIAL_CHARS.get(ref) - - if not data and self.convertHTMLEntities and \ - not self.XML_ENTITIES_TO_SPECIAL_CHARS.get(ref): - # TODO: We've got a problem here. We're told this is - # an entity reference, but it's not an XML entity - # reference or an HTML entity reference. Nonetheless, - # the logical thing to do is to pass it through as an - # unrecognized entity reference. - # - # Except: when the input is "&carol;" this function - # will be called with input "carol". When the input is - # "AT&T", this function will be called with input - # "T". We have no way of knowing whether a semicolon - # was present originally, so we don't know whether - # this is an unknown entity or just a misplaced - # ampersand. - # - # The more common case is a misplaced ampersand, so I - # escape the ampersand and omit the trailing semicolon. - data = "&%s" % ref - if not data: - # This case is different from the one above, because we - # haven't already gone through a supposedly comprehensive - # mapping of entities to Unicode characters. We might not - # have gone through any mapping at all. So the chances are - # very high that this is a real entity, and not a - # misplaced ampersand. - data = "&%s;" % ref - self.handle_data(data) - - def handle_decl(self, data): - "Handle DOCTYPEs and the like as Declaration objects." - self._toStringSubclass(data, Declaration) - - def parse_declaration(self, i): - """Treat a bogus SGML declaration as raw data. Treat a CDATA - declaration as a CData object.""" - j = None - if self.rawdata[i:i+9] == '', i) - if k == -1: - k = len(self.rawdata) - data = self.rawdata[i+9:k] - j = k+3 - self._toStringSubclass(data, CData) - else: - try: - j = SGMLParser.parse_declaration(self, i) - except SGMLParseError: - toHandle = self.rawdata[i:] - self.handle_data(toHandle) - j = i + len(toHandle) - return j - -class BeautifulSoup(BeautifulStoneSoup): - - """This parser knows the following facts about HTML: - - * Some tags have no closing tag and should be interpreted as being - closed as soon as they are encountered. - - * The text inside some tags (ie. 'script') may contain tags which - are not really part of the document and which should be parsed - as text, not tags. If you want to parse the text as tags, you can - always fetch it and parse it explicitly. - - * Tag nesting rules: - - Most tags can't be nested at all. For instance, the occurance of - a

    tag should implicitly close the previous

    tag. - -

    Para1

    Para2 - should be transformed into: -

    Para1

    Para2 - - Some tags can be nested arbitrarily. For instance, the occurance - of a

    tag should _not_ implicitly close the previous -
    tag. - - Alice said:
    Bob said:
    Blah - should NOT be transformed into: - Alice said:
    Bob said:
    Blah - - Some tags can be nested, but the nesting is reset by the - interposition of other tags. For instance, a
    , - but not close a tag in another table. - -
    BlahBlah - should be transformed into: -
    BlahBlah - but, - Blah
    Blah - should NOT be transformed into - Blah
    Blah - - Differing assumptions about tag nesting rules are a major source - of problems with the BeautifulSoup class. If BeautifulSoup is not - treating as nestable a tag your page author treats as nestable, - try ICantBelieveItsBeautifulSoup, MinimalSoup, or - BeautifulStoneSoup before writing your own subclass.""" - - def __init__(self, *args, **kwargs): - if 'smartQuotesTo' not in kwargs: - kwargs['smartQuotesTo'] = self.HTML_ENTITIES - kwargs['isHTML'] = True - BeautifulStoneSoup.__init__(self, *args, **kwargs) - - SELF_CLOSING_TAGS = buildTagMap(None, - ('br' , 'hr', 'input', 'img', 'meta', - 'spacer', 'link', 'frame', 'base', 'col')) - - PRESERVE_WHITESPACE_TAGS = set(['pre', 'textarea']) - - QUOTE_TAGS = {'script' : None, 'textarea' : None} - - #According to the HTML standard, each of these inline tags can - #contain another tag of the same type. Furthermore, it's common - #to actually use these tags this way. - NESTABLE_INLINE_TAGS = ('span', 'font', 'q', 'object', 'bdo', 'sub', 'sup', - 'center') - - #According to the HTML standard, these block tags can contain - #another tag of the same type. Furthermore, it's common - #to actually use these tags this way. - NESTABLE_BLOCK_TAGS = ('blockquote', 'div', 'fieldset', 'ins', 'del') - - #Lists can contain other lists, but there are restrictions. - NESTABLE_LIST_TAGS = { 'ol' : [], - 'ul' : [], - 'li' : ['ul', 'ol'], - 'dl' : [], - 'dd' : ['dl'], - 'dt' : ['dl'] } - - #Tables can contain other tables, but there are restrictions. - NESTABLE_TABLE_TAGS = {'table' : [], - 'tr' : ['table', 'tbody', 'tfoot', 'thead'], - 'td' : ['tr'], - 'th' : ['tr'], - 'thead' : ['table'], - 'tbody' : ['table'], - 'tfoot' : ['table'], - } - - NON_NESTABLE_BLOCK_TAGS = ('address', 'form', 'p', 'pre') - - #If one of these tags is encountered, all tags up to the next tag of - #this type are popped. - RESET_NESTING_TAGS = buildTagMap(None, NESTABLE_BLOCK_TAGS, 'noscript', - NON_NESTABLE_BLOCK_TAGS, - NESTABLE_LIST_TAGS, - NESTABLE_TABLE_TAGS) - - NESTABLE_TAGS = buildTagMap([], NESTABLE_INLINE_TAGS, NESTABLE_BLOCK_TAGS, - NESTABLE_LIST_TAGS, NESTABLE_TABLE_TAGS) - - # Used to detect the charset in a META tag; see start_meta - CHARSET_RE = re.compile("((^|;)\s*charset=)([^;]*)", re.M) - - def start_meta(self, attrs): - """Beautiful Soup can detect a charset included in a META tag, - try to convert the document to that charset, and re-parse the - document from the beginning.""" - httpEquiv = None - contentType = None - contentTypeIndex = None - tagNeedsEncodingSubstitution = False - - for i in range(0, len(attrs)): - key, value = attrs[i] - key = key.lower() - if key == 'http-equiv': - httpEquiv = value - elif key == 'content': - contentType = value - contentTypeIndex = i - - if httpEquiv and contentType: # It's an interesting meta tag. - match = self.CHARSET_RE.search(contentType) - if match: - if (self.declaredHTMLEncoding is not None or - self.originalEncoding == self.fromEncoding): - # An HTML encoding was sniffed while converting - # the document to Unicode, or an HTML encoding was - # sniffed during a previous pass through the - # document, or an encoding was specified - # explicitly and it worked. Rewrite the meta tag. - def rewrite(match): - return match.group(1) + "%SOUP-ENCODING%" - newAttr = self.CHARSET_RE.sub(rewrite, contentType) - attrs[contentTypeIndex] = (attrs[contentTypeIndex][0], - newAttr) - tagNeedsEncodingSubstitution = True - else: - # This is our first pass through the document. - # Go through it again with the encoding information. - newCharset = match.group(3) - if newCharset and newCharset != self.originalEncoding: - self.declaredHTMLEncoding = newCharset - self._feed(self.declaredHTMLEncoding) - raise StopParsing - pass - tag = self.unknown_starttag("meta", attrs) - if tag and tagNeedsEncodingSubstitution: - tag.containsSubstitutions = True - -class StopParsing(Exception): - pass - -class ICantBelieveItsBeautifulSoup(BeautifulSoup): - - """The BeautifulSoup class is oriented towards skipping over - common HTML errors like unclosed tags. However, sometimes it makes - errors of its own. For instance, consider this fragment: - - FooBar - - This is perfectly valid (if bizarre) HTML. However, the - BeautifulSoup class will implicitly close the first b tag when it - encounters the second 'b'. It will think the author wrote - "FooBar", and didn't close the first 'b' tag, because - there's no real-world reason to bold something that's already - bold. When it encounters '' it will close two more 'b' - tags, for a grand total of three tags closed instead of two. This - can throw off the rest of your document structure. The same is - true of a number of other tags, listed below. - - It's much more common for someone to forget to close a 'b' tag - than to actually use nested 'b' tags, and the BeautifulSoup class - handles the common case. This class handles the not-co-common - case: where you can't believe someone wrote what they did, but - it's valid HTML and BeautifulSoup screwed up by assuming it - wouldn't be.""" - - I_CANT_BELIEVE_THEYRE_NESTABLE_INLINE_TAGS = \ - ('em', 'big', 'i', 'small', 'tt', 'abbr', 'acronym', 'strong', - 'cite', 'code', 'dfn', 'kbd', 'samp', 'strong', 'var', 'b', - 'big') - - I_CANT_BELIEVE_THEYRE_NESTABLE_BLOCK_TAGS = ('noscript',) - - NESTABLE_TAGS = buildTagMap([], BeautifulSoup.NESTABLE_TAGS, - I_CANT_BELIEVE_THEYRE_NESTABLE_BLOCK_TAGS, - I_CANT_BELIEVE_THEYRE_NESTABLE_INLINE_TAGS) - -class MinimalSoup(BeautifulSoup): - """The MinimalSoup class is for parsing HTML that contains - pathologically bad markup. It makes no assumptions about tag - nesting, but it does know which tags are self-closing, that -