diff --git a/InnerDetector/InDetConfig/python/InDetVKalVxInJetToolConfig.py b/InnerDetector/InDetConfig/python/InDetVKalVxInJetToolConfig.py index e003b7dda3d569df567222fec4677ae05e085c26..1018e623e3d166a4ca7c049ac76a29fd1a10a759 100644 --- a/InnerDetector/InDetConfig/python/InDetVKalVxInJetToolConfig.py +++ b/InnerDetector/InDetConfig/python/InDetVKalVxInJetToolConfig.py @@ -5,9 +5,23 @@ from AthenaConfiguration.ComponentAccumulator import ComponentAccumulator from AthenaConfiguration.ComponentFactory import CompFactory from AthenaConfiguration.Enums import LHCPeriod +def TCTDecorCheckInToolCfg(flags, name="TCTDecorCheckInTool", **kwargs): + + acc = ComponentAccumulator() + + kwargs.setdefault("JetCollection","AntiKt4EMPFlowJets") + + from TrkConfig.TrkVKalVrtFitterConfig import TrkVKalVrtFitterCfg + VertexFitterTool = acc.popToolsAndMerge(TrkVKalVrtFitterCfg(flags,"VertexFitterTool")) + kwargs.setdefault("TrackClassificationTool",acc.popToolsAndMerge(InDetTrkInJetTypeCfg(flags,name="TrkInJetType",JetCollection=kwargs["JetCollection"],VertexFitterTool=VertexFitterTool))) + + acc.addEventAlgo(CompFactory.TCTDecorCheckInTool(name, **kwargs)) + return acc + def InDetTrkInJetTypeCfg(flags, name="TrkInJetType", **kwargs): acc = ComponentAccumulator() kwargs.setdefault("trkSctHits", 4 if flags.GeoModel.Run <= LHCPeriod.Run3 else -1) + kwargs.setdefault("useFivePtJetBinVersion", flags.BTagging.TrkClassFiveBinMode) acc.setPrivateTools(CompFactory.InDet.InDetTrkInJetType(name, **kwargs)) return acc diff --git a/InnerDetector/InDetRecTools/InDetVKalVxInJetTool/CMakeLists.txt b/InnerDetector/InDetRecTools/InDetVKalVxInJetTool/CMakeLists.txt index 056a4b4e8c104ef1d619e343ba609503c13590ed..aab6a2a799106ffe19cde3191f8035ab3970b331 100644 --- a/InnerDetector/InDetRecTools/InDetVKalVxInJetTool/CMakeLists.txt +++ b/InnerDetector/InDetRecTools/InDetVKalVxInJetTool/CMakeLists.txt @@ -13,7 +13,7 @@ atlas_add_library( InDetVKalVxInJetToolLib src/*.cxx PUBLIC_HEADERS InDetVKalVxInJetTool INCLUDE_DIRS ${Boost_INCLUDE_DIRS} ${ROOT_INCLUDE_DIRS} - LINK_LIBRARIES ${Boost_LIBRARIES} ${ROOT_LIBRARIES} AnalysisUtilsLib AthenaBaseComps BeamPipeGeoModelLib PixelReadoutGeometryLib CxxUtils InDetRecToolInterfaces MVAUtils PathResolver TrkNeutralParameters TrkToolInterfaces TrkVKalVrtFitterLib VxSecVertex xAODTracking xAODTruth xAODEventInfo) + LINK_LIBRARIES ${Boost_LIBRARIES} ${ROOT_LIBRARIES} AnalysisUtilsLib AthenaBaseComps BeamPipeGeoModelLib PixelReadoutGeometryLib CxxUtils GeoPrimitives InDetRecToolInterfaces MVAUtils PathResolver TrkNeutralParameters TrkToolInterfaces TrkVKalVrtFitterLib VxSecVertex xAODTracking xAODTruth xAODEventInfo xAODJet TestTools) atlas_add_component( InDetVKalVxInJetTool src/components/*.cxx @@ -27,5 +27,5 @@ atlas_install_joboptions( share/*.txt ) atlas_add_test( InDetTrkInJetType_test SOURCES test/InDetTrkInJetType_test.cxx INCLUDE_DIRS ${CLHEP_INCLUDE_DIRS} ${ROOT_INCLUDE_DIRS} - LINK_LIBRARIES ${CLHEP_LIBRARIES} ${ROOT_LIBRARIES} AthenaBaseComps AthenaKernel CxxUtils EventPrimitives GaudiKernel MagFieldConditions TestTools TrkVertexFitterInterfaces xAODTracking + LINK_LIBRARIES ${CLHEP_LIBRARIES} ${ROOT_LIBRARIES} AthenaBaseComps AthenaKernel CxxUtils EventPrimitives GaudiKernel MagFieldConditions TestTools TrkVertexFitterInterfaces xAODTracking xAODJet LOG_IGNORE_PATTERN "Booking|ClassIDSvc|weight file|create data set info" ) diff --git a/InnerDetector/InDetRecTools/InDetVKalVxInJetTool/InDetVKalVxInJetTool/InDetTrkInJetType.h b/InnerDetector/InDetRecTools/InDetVKalVxInJetTool/InDetVKalVxInJetTool/InDetTrkInJetType.h index e2fa3ef7fbaee8197faf4dd561570e7052efb287..1ff3632d11ca310c13aff517d4c71dcbef2b0ae1 100644 --- a/InnerDetector/InDetRecTools/InDetVKalVxInJetTool/InDetVKalVxInJetTool/InDetTrkInJetType.h +++ b/InnerDetector/InDetRecTools/InDetVKalVxInJetTool/InDetVKalVxInJetTool/InDetTrkInJetType.h @@ -18,6 +18,13 @@ The tool is trained using ttbar+Z'(2.5,5TeV)+JZ4,6,8 + Gbb7000 samples The tool uses trkPt vs JetAxis (no any dR cone cut!) therefore the tool can be used for any jet with "reasonable" dR size. + When setting the python configuration useFivePtJetBinVersion to True, a retrained TCT BDT model is used, where five BDTs were + trained separately in the regions [0.02,0.2]; [0.2,0.5]; [0.5,1]; [1,2] and [2,7] TeV with an Zprime, ZprimeExtended and ttbar sample. + + Either the TrackParticle objects can be decorated with the TCT score and a ElementLink to the Jet object, which was used to + calculate the TCT score (decorateTrack) or the Jet object can be decorated with a std::vector of TCT scores and a std::vector of ElementLinks + to TrackParticle associated with the given jet. + Author: Vadim Kostyukhin e-mail: vadim.kostyukhin@cern.ch */ @@ -27,8 +34,12 @@ #include #include "AthenaBaseComps/AthAlgTool.h" #include "GaudiKernel/ToolHandle.h" +#include "xAODJet/JetContainer.h" #include "xAODTracking/TrackParticleContainer.h" #include "TrkVertexFitterInterfaces/IVertexFitter.h" + +#include "StoreGate/WriteDecorHandle.h" + // class TLorentzVector; @@ -46,6 +57,10 @@ namespace InDet { //Interface itself virtual std::vector trkTypeWgts( const xAOD::TrackParticle *, const xAOD::Vertex &, const TLorentzVector &) const =0; + virtual bool usesFivePtJetBinVersion() const=0; + virtual void decorateTrack(const xAOD::TrackParticle* , const xAOD::Vertex & , const xAOD::JetContainer & , const xAOD::Jet* ) const =0; + virtual void decorateJet(const std::vector & , const xAOD::TrackParticleContainer& , const xAOD::Vertex & , const xAOD::Jet* ) const =0; + }; @@ -66,6 +81,13 @@ namespace InDet { virtual StatusCode finalize() override; virtual std::vector trkTypeWgts(const xAOD::TrackParticle *, const xAOD::Vertex &, const TLorentzVector &) const override; + /* return the five ptjet bin mode: if true, the retrained FivePtJetBin TCT BDT is used; if false, the default TCT BDT is used */ + virtual bool usesFivePtJetBinVersion() const override {return m_useFivePtJetBinVersion; } + /* decorates a TrackParticle associated to the given Jet (element from the passed JetContainer)*/ + virtual void decorateTrack(const xAOD::TrackParticle* , const xAOD::Vertex & , const xAOD::JetContainer & , const xAOD::Jet* ) const override; + /* decorates a Jet with the TCT scores and TrackParticleLinks of the tracks passed through the std::vector*/ + virtual void decorateJet(const std::vector & , const xAOD::TrackParticleContainer& , const xAOD::Vertex & , const xAOD::Jet* ) const override; + //------------------------------------------------------------------------------------------------------------------ // Private data and functions @@ -73,7 +95,7 @@ namespace InDet { private: - std::unique_ptr m_trkClassBDT; + std::vector> m_vTrkClassBDT{}; IChronoStatSvc* m_timingProfile{}; int m_trkSctHitsCut{}; @@ -87,11 +109,32 @@ namespace InDet { float m_Z0_limLow{}; float m_Z0_limUpp{}; std::string m_calibFileName; + std::string m_calibFileNameFivePtJetBin; + std::string m_jetCollection; + bool m_useFivePtJetBinVersion; ToolHandle < Trk::IVertexFitter > m_fitterSvc {this, "VertexFitterTool", "Trk::TrkVKalVrtFitter/VertexFitterTool",""}; Trk::TrkVKalVrtFitter* m_fitSvc{}; int m_initialised{}; + + //numbering of the jet pt slices + enum e_ptjetRange {e_ptjet0to0p2TeV=0, e_ptjet0p2to0p5TeV=1, e_ptjet0p5to1TeV=2, e_ptjet1to2TeV=3, e_ptjet2to7TeV=4}; + + /** The write key for adding TCT score as decoration to TrackParticle objects */ + //from https://acode-browser1.usatlas.bnl.gov/lxr/source/athena/Event/xAOD/xAODTrackingCnv/src/TrackParticleCnvAlg.cxx + SG::WriteDecorHandleKey m_trackWriteDecorKeyTCTScore{this,"trackDecorKeyTCTScore", + "","WriteDecorHandleKey for adding TCT score to TrackParticles"}; + SG::WriteDecorHandleKey m_trackWriteDecorKeyJetLink{this,"trackDecorKeyJetLink", + "","WriteDecorHandleKey for adding JetLink to TrackParticles"}; + + /** The write key for adding TCT score as decoration to Jet objects */ + SG::WriteDecorHandleKey m_jetWriteDecorKeyTCTScore{this,"jetDecorKeyTCTScore", + "","WriteDecorHandleKey for adding TCT score to Jets"}; + SG::WriteDecorHandleKey m_jetWriteDecorKeyTrackLink{this,"jetDecorKeyJetLink", + "","WriteDecorHandleKey for adding TrackParticleLink to Jets"}; + + }; diff --git a/InnerDetector/InDetRecTools/InDetVKalVxInJetTool/InDetVKalVxInJetTool/TCTDecorCheckInTool.h b/InnerDetector/InDetRecTools/InDetVKalVxInJetTool/InDetVKalVxInJetTool/TCTDecorCheckInTool.h new file mode 100644 index 0000000000000000000000000000000000000000..38c069d1f9283e97a1108af643b1d54f054d4f92 --- /dev/null +++ b/InnerDetector/InDetRecTools/InDetVKalVxInJetTool/InDetVKalVxInJetTool/TCTDecorCheckInTool.h @@ -0,0 +1,82 @@ +/* + Copyright (C) 2002-2022 CERN for the benefit of the ATLAS collaboration +*/ +// +// TCTDecorCheck.h - Description +// +/* + Test algorithm to check that TrackParticle decorations regarding the TCT are correctly saved + Before running TCTDecorCheck the decorations have to be applied through the InDetVKalVxInJetTool/TrackClassificationDecorator algorithm + + Author: Katharina Voss + e-mail: katharina.voss@cern.ch +*/ +#ifndef ANALYSISEXAMPLES_TCTDecorCheckInTool_H +#define ANALYSISEXAMPLES_TCTDecorCheckInTool_H + +#include +#include +#include "AthenaBaseComps/AthAlgorithm.h" +//#include "AthenaBaseComps/AthReentrantAlgorithm.h" +#include "GaudiKernel/ToolHandle.h" +#include "StoreGate/DataHandle.h" +#include "StoreGate/ReadDecorHandle.h" + +#include "xAODJet/JetContainer.h" +#include "xAODTracking/VertexContainer.h" +#include "xAODTracking/TrackParticleContainer.h" + +#include "InDetVKalVxInJetTool/InDetTrkInJetType.h" + + + +class TLorentzVector; + + + class TCTDecorCheckInTool : public AthAlgorithm + { + public: + /* Constructor */ + TCTDecorCheckInTool(const std::string& type, ISvcLocator* pSvcLocator); + /* Destructor */ + virtual ~TCTDecorCheckInTool(); + + + virtual StatusCode initialize() override; + virtual StatusCode execute() override; + virtual StatusCode finalize() override; + +//------------------------------------------------------------------------------------------------------------------ +// Private data and functions +// + + private: + + // get handle to TCT Tool + ToolHandle m_trackClassificationTool; + + // ReadHandle for the jets + SG::ReadHandleKey m_jetsKey{this,"JetContainer","AntiKt4EMPFlowJets","ReadHandleKey for Jet Container"}; + SG::ReadHandleKey m_particlesKey{this, "trackCollection", "InDetTrackParticles"}; + SG::ReadHandleKey m_verticesKey { this, "VertexContainer", "PrimaryVertices"}; + + /** The read key for adding TCT score as decoration to TrackParticle objects */ + //from https://acode-browser1.usatlas.bnl.gov/lxr/source/athena/Event/xAOD/xAODTrackingCnv/src/TrackParticleCnvAlg.cxx + SG::ReadDecorHandleKey m_trackReadDecorKeyTCTScore{this,"trackDecorKeyTCTScore", + "InDetTrackParticles.TCTScore_AntiKt4EMPFlowJets","ReadDecorHandleKey for adding TCT score to TrackParticles"}; + SG::ReadDecorHandleKey m_trackReadDecorKeyJetLink{this,"trackDecorKeyJetLink", + "InDetTrackParticles.TCTJetLink_AntiKt4EMPFlowJets","ReadDecorHandleKey for adding JetLink to TrackParticles"}; + + /** The write key for adding TCT score as decoration to Jet objects */ + SG::ReadDecorHandleKey m_jetReadDecorKeyTCTScore{this,"jetDecorKeyTCTScore", + "AntiKt4EMPFlowJets.TCTScore","ReadDecorHandleKey for adding TCT score to Jets"}; + SG::ReadDecorHandleKey m_jetReadDecorKeyTrackLink{this,"jetDecorKeyJetLink", + "AntiKt4EMPFlowJets.TCTTrackLink","ReadDecorHandleKey for adding TrackParticleLink to Jets"}; + + std::string m_decoratorMethod{}; + std::string m_jetCollection{}; + + }; + + +#endif diff --git a/InnerDetector/InDetRecTools/InDetVKalVxInJetTool/src/BTagVrtSec.cxx b/InnerDetector/InDetRecTools/InDetVKalVxInJetTool/src/BTagVrtSec.cxx index 6645be2c4b9539d92589e744a5a13e0be1b9d1ad..f7df7e804916e559531aa0e7c664d67c7f5a7c47 100755 --- a/InnerDetector/InDetRecTools/InDetVKalVxInJetTool/src/BTagVrtSec.cxx +++ b/InnerDetector/InDetRecTools/InDetVKalVxInJetTool/src/BTagVrtSec.cxx @@ -626,7 +626,7 @@ namespace InDet{ h.m_curTup->pTvsJet[i] = TLV.Perp(jetDir.Vect()); TLorentzVector normJ; normJ.SetPtEtaPhiM(1.,jetDir.Eta(),jetDir.Phi(),0.); - h.m_curTup->prodTJ[i] = std::sqrt(TLV.Dot(normJ)); + h.m_curTup->prodTJ[i] = std::sqrt(TMath::Abs(TLV.Dot(normJ))); h.m_curTup->nVrtT[i] = 0; } } diff --git a/InnerDetector/InDetRecTools/InDetVKalVxInJetTool/src/InDetTrkInJetType.cxx b/InnerDetector/InDetRecTools/InDetVKalVxInJetTool/src/InDetTrkInJetType.cxx index 233d705142c43919caf6c1a9cb37f7bead23a83c..b35ec4ea41dbc10fa8d2b39a8f3ee6019711f28f 100644 --- a/InnerDetector/InDetRecTools/InDetVKalVxInJetTool/src/InDetTrkInJetType.cxx +++ b/InnerDetector/InDetRecTools/InDetVKalVxInJetTool/src/InDetTrkInJetType.cxx @@ -20,7 +20,6 @@ InDetTrkInJetType::InDetTrkInJetType(const std::string& type, const std::string& name, const IInterface* parent): base_class(type,name,parent), - m_trkClassBDT(nullptr), m_trkSctHitsCut(4), m_trkPixelHitsCut(1), m_trkChi2Cut(5.), @@ -31,7 +30,10 @@ InDetTrkInJetType::InDetTrkInJetType(const std::string& type, m_d0_limUpp( 5.), m_Z0_limLow(-15.), m_Z0_limUpp( 15.), - m_calibFileName("TrackClassif_3cl.v03.root") + m_calibFileName("TrackClassif_3cl.v03.root"), + m_calibFileNameFivePtJetBin("TrackClassif_3cl.v04.root"), + m_jetCollection(""), //AntiKt4EMPFlowJets + m_useFivePtJetBinVersion(kFALSE) { declareProperty("trkSctHits", m_trkSctHitsCut , "Cut on track SCT hits number" ); declareProperty("trkPixelHits", m_trkPixelHitsCut , "Cut on track Pixel hits number" ); @@ -43,7 +45,10 @@ InDetTrkInJetType::InDetTrkInJetType(const std::string& type, declareProperty("d0_limUpp", m_d0_limUpp , "Upper d0 impact cut" ); declareProperty("Z0_limLow", m_Z0_limLow , "Low Z0 impact cut" ); declareProperty("Z0_limUpp", m_Z0_limUpp , "Upper Z0 impact cut" ); + declareProperty("useFivePtJetBinVersion", m_useFivePtJetBinVersion, "Use five ptjet bin BDT model of TCT"); + declareProperty("JetCollection",m_jetCollection, "Type of JetContainer which should be decorated with TCT scores and TrackLinks"); m_timingProfile=nullptr; + } //Destructor--------------------------------------------------------------- @@ -58,13 +63,37 @@ InDetTrkInJetType::InDetTrkInJetType(const std::string& type, //-- Calibration file // std::string fullPathToFile = PathResolverFindCalibFile("InDetVKalVxInJetTool/"+m_calibFileName); + if(m_useFivePtJetBinVersion) {fullPathToFile = PathResolverFindCalibFile("InDetVKalVxInJetTool/"+m_calibFileNameFivePtJetBin);} std::unique_ptr rootFile(TFile::Open(fullPathToFile.c_str(), "READ")); if (!rootFile) { - ATH_MSG_ERROR("Can not retrieve TrackClassification calibration root file: " << m_calibFileName); + if(!m_useFivePtJetBinVersion) {ATH_MSG_ERROR("Can not retrieve TrackClassification calibration root file: " << m_calibFileName); } + else {ATH_MSG_ERROR("Can not retrieve TrackClassification five ptjet bin calibration root file: " << m_calibFileNameFivePtJetBin); } return StatusCode::FAILURE; } - std::unique_ptr training((TTree*)rootFile->Get("BDT")); - m_trkClassBDT =std::make_unique(training.get()); + if(!m_useFivePtJetBinVersion) + { + std::unique_ptr training((TTree*)rootFile->Get("BDT")); + m_vTrkClassBDT.push_back(std::make_unique(training.get())); + } + else + { + unsigned int nPtjetRanges=5; + std::vector v_BDTName(nPtjetRanges,""); + + v_BDTName.at(e_ptjet0to0p2TeV) = "BDTG_0_200GeV"; + v_BDTName.at(e_ptjet0p2to0p5TeV) = "BDTG_200_500GeV"; + v_BDTName.at(e_ptjet0p5to1TeV) = "BDTG_500_1000GeV"; + v_BDTName.at(e_ptjet1to2TeV) = "BDTG_1000_2000GeV"; + v_BDTName.at(e_ptjet2to7TeV) = "BDTG_gt2000GeV"; + + for(auto bdtname : v_BDTName) + { + std::unique_ptr training((TTree*)rootFile->Get(bdtname.c_str())); + m_vTrkClassBDT.push_back(std::make_unique(training.get())); + } + if(m_vTrkClassBDT.size() != nPtjetRanges) {ATH_MSG_ERROR("TrackClassification five ptjet bin BDT model not correctly loaded."); } + } + if(!m_useFivePtJetBinVersion) {if(m_vTrkClassBDT.size() != 1) {ATH_MSG_ERROR("TrackClassification BDT model not correctly loaded."); }} //------- if (m_fitterSvc.retrieve().isFailure()) { ATH_MSG_DEBUG("Could not find Trk::TrkVKalVrtFitter"); @@ -77,6 +106,27 @@ InDetTrkInJetType::InDetTrkInJetType(const std::string& type, ATH_MSG_DEBUG(" No implemented Trk::ITrkVKalVrtFitter interface"); return StatusCode::SUCCESS; } + + if(m_jetCollection!="") + { + + //from https://acode-browser1.usatlas.bnl.gov/lxr/source/athena/Event/xAOD/xAODTrackingCnv/src/TrackParticleCnvAlg.cxx + m_trackWriteDecorKeyTCTScore = "InDetTrackParticles.TCTScore_"+m_jetCollection; + m_trackWriteDecorKeyJetLink = "InDetTrackParticles.TCTJetLink_"+m_jetCollection; + + m_jetWriteDecorKeyTCTScore = m_jetCollection+ ".TCTScore"; + m_jetWriteDecorKeyTrackLink = m_jetCollection +".TCTTrackLink"; + + //initialize SG WriteDecorHandleKeys needed for decorating tracks + ATH_CHECK( m_trackWriteDecorKeyTCTScore.initialize()); + ATH_CHECK( m_trackWriteDecorKeyJetLink.initialize()); + + //initialize SG WriteDecorHandleKeys needed for decorating jets + ATH_CHECK( m_jetWriteDecorKeyTCTScore.initialize()); + ATH_CHECK( m_jetWriteDecorKeyTrackLink.initialize()); + } + + m_initialised = 1; // Tool is initialised successfully. //----- if(msgLvl(MSG::DEBUG)) ATH_CHECK(service("ChronoStatSvc", m_timingProfile)); @@ -106,7 +156,6 @@ InDetTrkInJetType::InDetTrkInJetType(const std::string& type, if( !(Trk->summaryValue( SctHits,xAOD::numberOfSCTHits)) ) return safeReturn; // No SCT hits. Bad. if( PixelHits < m_trkPixelHitsCut ) return safeReturn; if( SctHits < m_trkSctHitsCut ) return safeReturn; - std::vector Impact,ImpactError; float Sig3D=m_fitSvc->VKalGetImpact(Trk, PV.position(), 1, Impact, ImpactError); AmgVector(5) tmpPerigee = Trk->perigeeParameters().parameters(); @@ -167,10 +216,55 @@ InDetTrkInJetType::InDetTrkInJetType(const std::string& type, if(m_timingProfile)m_timingProfile->chronoStart("InDet_TrkInJetType"); //-----Use MVAUtils to save CPU std::vector bdt_vars={Sig3D, prbP, pTvsJet, d0, SigR, SigZ, ptjet, (float)hitIBL, (float)hitBL, etatrk}; - std::vector weights=m_trkClassBDT->GetMultiResponse(bdt_vars,3); + std::vector weights; + if(!m_useFivePtJetBinVersion) {weights =m_vTrkClassBDT.at(0)->GetMultiResponse(bdt_vars,3);} + else{ + e_ptjetRange e_ptjet; + if(ptjet < 0.2e6) {e_ptjet = e_ptjet0to0p2TeV; } + else if(ptjet > 0.2e6 && ptjet < 0.5e6) {e_ptjet = e_ptjet0p2to0p5TeV; } + else if(ptjet > 0.5e6 && ptjet < 1.e6) {e_ptjet = e_ptjet0p5to1TeV; } + else if(ptjet > 1.e6 && ptjet < 2.e6) {e_ptjet = e_ptjet1to2TeV; } + else if(ptjet > 2.e6) {e_ptjet = e_ptjet2to7TeV; } + else {ATH_MSG_ERROR("Not a valid ptjet value in five ptjet bin TrackClassification application: " << ptjet); return safeReturn; } + weights = m_vTrkClassBDT.at(e_ptjet)->GetMultiResponse(bdt_vars,3); + } + //----- if(m_timingProfile)m_timingProfile->chronoStop("InDet_TrkInJetType"); - return weights; + return weights; //order: wgtB, wgtL, wgtG } + + void InDetTrkInJetType::decorateTrack(const xAOD::TrackParticle* trk, const xAOD::Vertex & PV, const xAOD::JetContainer & jets, const xAOD::Jet* curjet) const + { + if(m_jetCollection=="") {ATH_MSG_FATAL("No JetContainer chosen for decorating tracks!"); } + + SG::WriteDecorHandle< xAOD::TrackParticleContainer, std::vector > trackWriteDecorHandleTCTScore (m_trackWriteDecorKeyTCTScore); + SG::WriteDecorHandle< xAOD::TrackParticleContainer, ElementLink > trackWriteDecorHandleJetLink (m_trackWriteDecorKeyJetLink); + std::vector v_tctScore = trkTypeWgts(trk,PV,curjet->p4()); + trackWriteDecorHandleTCTScore(*trk) = v_tctScore; + ElementLink< xAOD::JetContainer> linkJet; + linkJet.toContainedElement(jets, curjet); + trackWriteDecorHandleJetLink(*trk) = linkJet; + } + + void InDetTrkInJetType::decorateJet(const std::vector & trks, const xAOD::TrackParticleContainer& trkContainer, const xAOD::Vertex & PV, const xAOD::Jet* curjet) const + { + if(m_jetCollection=="") {ATH_MSG_FATAL("No JetContainer chosen for decorating tracks!"); } + SG::WriteDecorHandle< xAOD::JetContainer, std::vector> > jetWriteDecorHandleTCTScore (m_jetWriteDecorKeyTCTScore); + SG::WriteDecorHandle< xAOD::JetContainer, std::vector> > jetWriteDecorHandleTrackLink (m_jetWriteDecorKeyTrackLink); + + for(auto itrk : trks) + { + std::vector v_tctScore = trkTypeWgts(itrk,PV,curjet->p4()); + jetWriteDecorHandleTCTScore(*curjet).push_back(v_tctScore); + //adapted from https://acode-browser1.usatlas.bnl.gov/lxr/source/athena/PhysicsAnalysis/JetTagging/JetTagAlgs/BTagging/src/JetBTaggingAlg.cxx + //line 253-255 + ElementLink< xAOD::TrackParticleContainer> linkTrack; + linkTrack.toContainedElement(trkContainer, itrk); + jetWriteDecorHandleTrackLink(*curjet).push_back(linkTrack); + } // end track loop + } + }// close namespace + diff --git a/InnerDetector/InDetRecTools/InDetVKalVxInJetTool/src/TCTDecorCheckInTool.cxx b/InnerDetector/InDetRecTools/InDetVKalVxInJetTool/src/TCTDecorCheckInTool.cxx new file mode 100644 index 0000000000000000000000000000000000000000..24118388c3c58aa32bb54c2b1c9027a14e7fa8f4 --- /dev/null +++ b/InnerDetector/InDetRecTools/InDetVKalVxInJetTool/src/TCTDecorCheckInTool.cxx @@ -0,0 +1,186 @@ +/* + Copyright (C) 2002-2022 CERN for the benefit of the ATLAS collaboration +*/ + +#include "InDetVKalVxInJetTool/TCTDecorCheckInTool.h" +#include "PathResolver/PathResolver.h" +#include "TLorentzVector.h" + +#include +#include "TestTools/FLOATassert.h" +// +//------------------------------------------------- +// +//Constructor-------------------------------------------------------------- +TCTDecorCheckInTool::TCTDecorCheckInTool( const std::string& name, + ISvcLocator* pSvcLocator): + AthAlgorithm( name, pSvcLocator ), + m_trackClassificationTool("InDet::InDetTrkInJetType",this), + m_decoratorMethod("decorateTrack"), + m_jetCollection("") //AntiKt4EMPFlowJets + { + declareProperty("TrackClassificationTool", m_trackClassificationTool); + declareProperty("decoratorMethod", m_decoratorMethod); + declareProperty("JetCollection",m_jetCollection, "Type of JetContainer which should be decorated with TCT scores and TrackLinks"); + + + } + +//Destructor--------------------------------------------------------------- + TCTDecorCheckInTool::~TCTDecorCheckInTool(){ + ATH_MSG_DEBUG("TCTDecorCheckInTool destructor called"); + } + +//Initialize--------------------------------------------------------------- + StatusCode TCTDecorCheckInTool::initialize(){ + + + ATH_CHECK( m_particlesKey.initialize() ); + ATH_CHECK( m_verticesKey.initialize() ); + ATH_CHECK( m_jetsKey.initialize() ); + + if(m_jetCollection!="") + { + //from https://acode-browser1.usatlas.bnl.gov/lxr/source/athena/Event/xAOD/xAODTrackingCnv/src/TrackParticleCnvAlg.cxx + m_trackReadDecorKeyTCTScore = "InDetTrackParticles.TCTScore_"+m_jetCollection; + m_trackReadDecorKeyJetLink = "InDetTrackParticles.TCTJetLink_"+m_jetCollection; + + m_jetReadDecorKeyTCTScore = m_jetCollection+ ".TCTScore"; + m_jetReadDecorKeyTrackLink = m_jetCollection +".TCTTrackLink"; + + ATH_CHECK( m_trackReadDecorKeyTCTScore.initialize()); + ATH_CHECK( m_trackReadDecorKeyJetLink.initialize()); + + ATH_CHECK( m_jetReadDecorKeyTCTScore.initialize()); + ATH_CHECK( m_jetReadDecorKeyTrackLink.initialize()); + } + + //------- + //check that the TrackClassificationTool can be accessed + if (m_trackClassificationTool.retrieve().isFailure()) { + ATH_MSG_DEBUG("Could not find InDet::InDetTrkInJetType"); + return StatusCode::SUCCESS; + } else { + ATH_MSG_DEBUG("InDet::InDetTrkInJetType found"); + } + + return StatusCode::SUCCESS; + } + + StatusCode TCTDecorCheckInTool::finalize() + { + ATH_MSG_DEBUG("TCTDecorCheck finalize()"); + return StatusCode::SUCCESS; + } + + StatusCode TCTDecorCheckInTool::execute() + { + ATH_MSG_DEBUG( "Executing..." ); + if(m_jetCollection==""){ ATH_MSG_FATAL("No JetCollection selected! ");} + SG::ReadDecorHandle< xAOD::TrackParticleContainer, std::vector > trackReadDecorHandleTCTScore (m_trackReadDecorKeyTCTScore); + SG::ReadDecorHandle< xAOD::TrackParticleContainer, ElementLink > trackReadDecorHandleJetLink (m_trackReadDecorKeyJetLink); + + //JetRead handles + SG::ReadDecorHandle< xAOD::JetContainer, std::vector> > jetReadDecorHandleTCTScore (m_jetReadDecorKeyTCTScore); + SG::ReadDecorHandle< xAOD::JetContainer, std::vector> > jetReadDecorHandleTrackLink (m_jetReadDecorKeyTrackLink); + + + // Retrieve the track particles: + SG::ReadHandle trackTES(m_particlesKey); + if ( !trackTES.isValid() ) { + ATH_MSG_WARNING( "No TrackParticle container found in TDS" ); + return StatusCode::SUCCESS; } + ATH_MSG_DEBUG( "TrackParticleContainer successfully retrieved" ); + + SG::ReadHandle pvTES(m_verticesKey); + if ( !pvTES.isValid() ) { + ATH_MSG_WARNING( "No Primary Vertices container found in TDS" ); + return StatusCode::SUCCESS; } + ATH_MSG_DEBUG( "Primary Vertices container successfully retrieved" ); + const xAOD::Vertex *primVertex=*(pvTES->begin()); + + + + //========================================================================== + SG::ReadHandle jetTES(m_jetsKey); + if ( !jetTES.isValid() ) { + ATH_MSG_WARNING( "No AntiKt4EMPflow jet container found in TDS" ); + return StatusCode::SUCCESS; } + ATH_MSG_DEBUG( "AntiKt4EMPflow jet container successfully retrieved" ); + + xAOD::TrackParticleContainer::const_iterator trackItr = trackTES->begin(); + xAOD::TrackParticleContainer::const_iterator trackItrE = trackTES->end(); + + xAOD::JetContainer::const_iterator jetItr = jetTES->begin(); + xAOD::JetContainer::const_iterator jetItrE = jetTES->end(); + + //decorator methods for decorating the tracks + if(m_decoratorMethod=="decorateTrack") + { + ATH_MSG_DEBUG("Using decorateTrack method "); + for(trackItr = trackTES->begin(); trackItr != trackItrE; trackItr++){ + const xAOD::TrackParticle* itrk = (*trackItr); + //first decorate the track with the InDetTrkInJetType method + //find closest jet to the track in Delta R + float minDeltaR=1.0; + const xAOD::Jet* closestJet = *(jetTES->begin()); + for(jetItr = jetTES->begin(); jetItr != jetItrE; jetItr++){ + const xAOD::Jet* curJet = (*jetItr); + float curDeltaR = (itrk)->p4().DeltaR(curJet->p4()); + if(curDeltaR < minDeltaR) {minDeltaR = curDeltaR; closestJet = curJet;} + } + m_trackClassificationTool->decorateTrack(itrk,*primVertex, *jetTES, closestJet); + } + + //loop over tracks and check if decoration was correctly added (using either decorateTrack) + for(trackItr = trackTES->begin(); trackItr != trackItrE; trackItr++){ + const xAOD::TrackParticle* itrk = (*trackItr); + std::vector v_tctScoresDeco = trackReadDecorHandleTCTScore(*itrk); + ElementLink v_jetLinks = trackReadDecorHandleJetLink(*itrk); + + ATH_MSG_DEBUG("TCT score from decoration: " << v_tctScoresDeco.at(0) << ", " << v_tctScoresDeco.at(1) << ", "<< v_tctScoresDeco.at(2)); + std::vector v_tctScore = m_trackClassificationTool->trkTypeWgts(itrk,*primVertex,(*v_jetLinks)->p4()); + ATH_MSG_DEBUG("Calculated TCT score: " << v_tctScore.at(0) << ", " << v_tctScore.at(1) << ", " << v_tctScore.at(2)); + + for(int j=0; j<=2 ; j++) {assert(Athena_test::isEqual(v_tctScore.at(j),v_tctScoresDeco.at(j)));} + + }//end track loop + }//end if decorator methods for decorating tracks + else if(m_decoratorMethod=="decorateJet") + { + ATH_MSG_DEBUG("Using decorateJets method "); + for(jetItr = jetTES->begin(); jetItr != jetItrE; jetItr++){ + const xAOD::Jet* ijet = (*jetItr); + std::vector trkparticles(0); + for(trackItr = trackTES->begin(); trackItr != trackItrE; trackItr++){ + const xAOD::TrackParticle* itrk = (*trackItr); + if((itrk)->p4().DeltaR(ijet->p4()) < 0.4) {trkparticles.push_back(itrk); } + } + m_trackClassificationTool->decorateJet(trkparticles,*trackTES,*primVertex, ijet); + } + + //loop over jets and check if decoration was correctly added + for(jetItr = jetTES->begin(); jetItr != jetItrE; jetItr++){ + const xAOD::Jet* ijet = (*jetItr); + std::vector> v_tctScoresDeco = jetReadDecorHandleTCTScore(*ijet); + std::vector> v_trackLinks = jetReadDecorHandleTrackLink(*ijet); + + for(unsigned int i=0; i v_tctScore = m_trackClassificationTool->trkTypeWgts(*v_trackLinks.at(i),*primVertex,ijet->p4()); + ATH_MSG_DEBUG("Calculated TCT score: " << v_tctScore.at(0) << ", " << v_tctScore.at(1) << ", " << v_tctScore.at(2)); + + for(int j=0; j<=2 ; j++) {assert(Athena_test::isEqual(v_tctScore.at(j),v_tctScoresDeco.at(i).at(j)));} + }//end of tct vector loop + }//end of jet loop + } + else + { + ATH_MSG_ERROR("Specified decorator method not implemented in InDetTrkInJetType: " << m_decoratorMethod ); + } + + + return StatusCode::SUCCESS; + } + diff --git a/InnerDetector/InDetRecTools/InDetVKalVxInJetTool/src/components/InDetVKalVxInJetTool_entries.cxx b/InnerDetector/InDetRecTools/InDetVKalVxInJetTool/src/components/InDetVKalVxInJetTool_entries.cxx index 6262d64189554b94732996c72e8528a14ac90e6b..cac4808dbf702c325fdef5a7aaa6e344d72fb1b6 100644 --- a/InnerDetector/InDetRecTools/InDetVKalVxInJetTool/src/components/InDetVKalVxInJetTool_entries.cxx +++ b/InnerDetector/InDetRecTools/InDetVKalVxInJetTool/src/components/InDetVKalVxInJetTool_entries.cxx @@ -1,8 +1,10 @@ #include "InDetVKalVxInJetTool/InDetVKalVxInJetTool.h" #include "InDetVKalVxInJetTool/InDetTrkInJetType.h" +#include "InDetVKalVxInJetTool/TCTDecorCheckInTool.h" -using namespace InDet; +//using namespace InDet; -DECLARE_COMPONENT( InDetVKalVxInJetTool ) -DECLARE_COMPONENT( InDetTrkInJetType ) +DECLARE_COMPONENT( InDet::InDetVKalVxInJetTool ) +DECLARE_COMPONENT( InDet::InDetTrkInJetType ) +DECLARE_COMPONENT( TCTDecorCheckInTool ) diff --git a/PhysicsAnalysis/JetTagging/JetTagConfig/python/BTaggingConfigFlags.py b/PhysicsAnalysis/JetTagging/JetTagConfig/python/BTaggingConfigFlags.py index 2bd81cbe61f3bfea7641f7df5c6ef7a3fa0e8728..411b55ee2b865c5af58db839b6f9aab8e0e0b8cd 100644 --- a/PhysicsAnalysis/JetTagging/JetTagConfig/python/BTaggingConfigFlags.py +++ b/PhysicsAnalysis/JetTagging/JetTagConfig/python/BTaggingConfigFlags.py @@ -78,4 +78,7 @@ def createBTaggingConfigFlags(): btagcf.addFlag("BTagging.Trackless", False) btagcf.addFlag("BTagging.Pseudotrack", False) + # track classification tool flags + btagcf.addFlag("BTagging.TrkClassFiveBinMode",False) + return btagcf diff --git a/PhysicsAnalysis/JetTagging/JetTagTools/CMakeLists.txt b/PhysicsAnalysis/JetTagging/JetTagTools/CMakeLists.txt index f6621374062130da5fec0633110f645dd94b4f82..306d573213888024b3bdce515cbc18ed40e6eda8 100644 --- a/PhysicsAnalysis/JetTagging/JetTagTools/CMakeLists.txt +++ b/PhysicsAnalysis/JetTagging/JetTagTools/CMakeLists.txt @@ -23,6 +23,8 @@ atlas_add_library( JetTagToolsLib src/MultiSVTag.cxx src/MultivariateTagManager.cxx src/TagNtupleDumper.cxx + src/ClassifiedTrackTaggerTool.cxx + src/CTTDecorCheckInTool.cxx PUBLIC_HEADERS JetTagTools INCLUDE_DIRS ${ROOT_INCLUDE_DIRS} @@ -30,11 +32,11 @@ atlas_add_library( JetTagToolsLib PRIVATE_DEFINITIONS ${CLHEP_DEFINITIONS} LINK_LIBRARIES ${ROOT_LIBRARIES} AthenaBaseComps AthenaKernel CxxUtils GaudiKernel GeoPrimitives ITrackToVertex InDetRecToolInterfaces JetTagCalibrationLib JetTagInfo - MVAUtils xAODBTagging xAODJet xAODTracking + MVAUtils xAODBTagging xAODJet xAODTracking InDetVKalVxInJetToolLib PRIVATE_LINK_LIBRARIES ${CLHEP_LIBRARIES} InDetTrackSelectionToolLib Navigation Particle ParticleJetToolsLib TrkEventPrimitives TrkLinks TrkNeuralNetworkUtilsLib TrkParameters TrkTrack TrkTrackLink TrkTrackSummary TrkVertexFitterInterfaces VxJetVertex - VxSecVertex VxVertex ) + VxSecVertex VxVertex TestTools) atlas_add_component( JetTagTools src/components/*.cxx @@ -43,3 +45,12 @@ atlas_add_component( JetTagTools # Install files from the package: atlas_install_runtime( share/*.root share/*.txt ) atlas_install_python_modules( python/*.py POST_BUILD_CMD ${ATLAS_FLAKE8} ) + + +# Test(s) in the package: +atlas_add_test( ClassifiedTrackTaggerTool_test + SOURCES test/ClassifiedTrackTaggerTool_test.cxx + INCLUDE_DIRS ${CLHEP_INCLUDE_DIRS} ${ROOT_INCLUDE_DIRS} + LINK_LIBRARIES ${CLHEP_LIBRARIES} ${ROOT_LIBRARIES} AthenaBaseComps AthenaKernel CxxUtils EventPrimitives GaudiKernel MagFieldConditions TestTools TrkVertexFitterInterfaces xAODTracking InDetVKalVxInJetToolLib xAODJet + LOG_IGNORE_PATTERN "Booking|ClassIDSvc|weight file|create data set info" ) +atlas_install_joboptions( share/*.txt ) \ No newline at end of file diff --git a/PhysicsAnalysis/JetTagging/JetTagTools/JetTagTools/CTTDecorCheckInTool.h b/PhysicsAnalysis/JetTagging/JetTagTools/JetTagTools/CTTDecorCheckInTool.h new file mode 100644 index 0000000000000000000000000000000000000000..4ba32a41f095365974a3a1622ae0b05c44fc4999 --- /dev/null +++ b/PhysicsAnalysis/JetTagging/JetTagTools/JetTagTools/CTTDecorCheckInTool.h @@ -0,0 +1,74 @@ +/* + Copyright (C) 2002-2022 CERN for the benefit of the ATLAS collaboration +*/ +// +// CTTDecorCheck.h - Description +// +/* + Test algorithm to check that Jet decorations regarding the CTT are correctly saved + Before running CTTDecorCheck the decorations have to be applied through the JetTagTools/ClassifiedTrackTaggerDecorator algorithm + + Author: Katharina Voss + e-mail: katharina.voss@cern.ch +*/ +#ifndef ANALYSISEXAMPLES_CTTDecorCheckInTool_H +#define ANALYSISEXAMPLES_CTTDecorCheckInTool_H + +#include +#include "AthenaBaseComps/AthAlgorithm.h" +//#include "AthenaBaseComps/AthReentrantAlgorithm.h" +#include "GaudiKernel/ToolHandle.h" +#include "StoreGate/DataHandle.h" +#include "StoreGate/ReadDecorHandle.h" +#include "StoreGate/ReadHandle.h" + + +#include "xAODJet/JetContainer.h" +#include "xAODTracking/VertexContainer.h" +#include "xAODTracking/TrackParticleContainer.h" + +#include "JetTagTools/ClassifiedTrackTaggerTool.h" + + + +class TLorentzVector; + + + + class CTTDecorCheckInTool : public AthAlgorithm + { + public: + /* Constructor */ + CTTDecorCheckInTool(const std::string& type, ISvcLocator* pSvcLocator); + /* Destructor */ + virtual ~CTTDecorCheckInTool(); + + + virtual StatusCode initialize() override; + virtual StatusCode execute() override; + virtual StatusCode finalize() override; + +//------------------------------------------------------------------------------------------------------------------ +// Private data and functions +// + + private: + + // get handle to new CTT Tool + ToolHandle m_classifiedTrackTagger; + std::string m_jetCollection; + + // ReadHandle for the jets + SG::ReadHandleKey m_jetsKey{this,"JetContainer","AntiKt4EMPFlowJets","ReadHandleKey for Jet Container"}; + SG::ReadHandleKey m_particlesKey{this, "trackCollection", "InDetTrackParticles"}; + SG::ReadHandleKey m_verticesKey { this, "VertexContainer", "PrimaryVertices"}; + + SG::ReadDecorHandleKey m_jetReadDecorKey{this,"JetDecorKey","AntiKt4EMPFlowJets.CTTScore","ReadDecorHandleKey for adding CTT score to Jets"}; + + + }; + + + + +#endif diff --git a/PhysicsAnalysis/JetTagging/JetTagTools/JetTagTools/ClassifiedTrackTaggerTool.h b/PhysicsAnalysis/JetTagging/JetTagTools/JetTagTools/ClassifiedTrackTaggerTool.h new file mode 100644 index 0000000000000000000000000000000000000000..c7c8207ad4db08f7499650c8c338ae151aaba1eb --- /dev/null +++ b/PhysicsAnalysis/JetTagging/JetTagTools/JetTagTools/ClassifiedTrackTaggerTool.h @@ -0,0 +1,112 @@ +/* + Copyright (C) 2002-2022 CERN for the benefit of the ATLAS collaboration +*/ +// +// ClassifiedTrackTaggerTool.h - Description +// +/* + Tool to give b-tagging score based on the track information + provided by the Track Classification Tool (TCT, InDetTrkInJetType) + + The three tracks with the highest probability of originating from a + B-hadron decay are used for the classification through a binary BDT, + which uses the three weights of the TCT for each of the three tracks + and the track multiplicity information through ptjet / ntrk + + Author: Katharina Voss + e-mail: katharina.voss@cern.ch +*/ +#ifndef Analysis_ClassifiedTrackTaggerTool_H +#define Analysis_ClassifiedTrackTaggerTool_H + +#include +#include "AthenaBaseComps/AthAlgTool.h" +#include "GaudiKernel/ToolHandle.h" +#include "xAODTracking/TrackParticleContainer.h" +#include "xAODJet/JetContainer.h" +//Interface of InDetTrkInJetType (inside .h file of InDetTrkInJetType class) +#include "InDetVKalVxInJetTool/InDetTrkInJetType.h" + +#include "StoreGate/WriteDecorHandle.h" +// + +class TLorentzVector; +class IChronoStatSvc; +namespace MVAUtils { class BDT; } +namespace InDet { class IInDetTrkInJetType; } + +namespace Analysis { + +//------------------------------------------------------------------------ + class IClassifiedTrackTaggerTool : virtual public IAlgTool { + public: + DeclareInterfaceID( IClassifiedTrackTaggerTool, 1, 0 ); +//--------------------------------------------------------------------------- +//Interface + + virtual float bJetWgts( const std::vector & , const xAOD::Vertex &, const TLorentzVector &) const =0; + virtual void decorateJets(const std::vector & , const xAOD::Vertex &, const xAOD::JetContainer & ) const =0; + + }; + + + + + class ClassifiedTrackTaggerTool : public extends + { + public: + /* Constructor */ + ClassifiedTrackTaggerTool(const std::string& type, const std::string& name, const IInterface* parent); + /* Destructor */ + virtual ~ClassifiedTrackTaggerTool(); + + + virtual StatusCode initialize() override; + virtual StatusCode finalize() override; + + /** Method to retrieve the classifier score of the ClassifiedTrackTagger (CTT) */ + virtual float bJetWgts( const std::vector & , const xAOD::Vertex &, const TLorentzVector &) const override; + /** Method to decorate the xAOD::Jet object with the CTT score */ + virtual void decorateJets(const std::vector & , const xAOD::Vertex &, const xAOD::JetContainer & ) const override; + +//------------------------------------------------------------------------------------------------------------------ +// Private data and functions +// + + private: + //debugging + IChronoStatSvc* m_timingProfile{}; + //variable to check: before public method bJetWgts can be executed, check that initialize() has been run! + int m_initialised{}; + + //variables for retrieving the CTT classification score given the TCT weights + std::unique_ptr m_CTTBDT; + + //TCT Tool to retrieve TCT weights, which are input to CTT BDT + ToolHandle < InDet::IInDetTrkInJetType > m_trackClassificator; + + //delta R cone size determining the considered tracks around the jet axis + float m_deltaRConeSize; + + //use updated TCT tool and CTT model trained with TCT weights from updated TCT tool + bool m_useFivePtJetBinTCT; + + //name of the BDT calibration file + std::string m_calibFileName; + + //name of the jet collection + std::string m_jetCollection; + + /** Private method for sorting tracks according to the highest wgtB */ + std::vector GetSortedIndices(std::vector> unordered_vec) const; + + /** The write key for adding CTT score to the jets */ + SG::WriteDecorHandleKey m_jetWriteDecorKey{this,"JetDecorKey","","WriteDecorHandleKey for adding CTT score to Jets"}; + + }; + + + + +} //end namespace +#endif diff --git a/PhysicsAnalysis/JetTagging/JetTagTools/doc/packagedoc.h b/PhysicsAnalysis/JetTagging/JetTagTools/doc/packagedoc.h index cc9b4658794ac95c7b9b2cdacfbec48bf9ecd5b7..d9874435db705b8ea72a0b1114b636ae7421cded 100644 --- a/PhysicsAnalysis/JetTagging/JetTagTools/doc/packagedoc.h +++ b/PhysicsAnalysis/JetTagging/JetTagTools/doc/packagedoc.h @@ -1,5 +1,5 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + Copyright (C) 2002-2022 CERN for the benefit of the ATLAS collaboration */ /** diff --git a/PhysicsAnalysis/JetTagging/JetTagTools/python/CTTDecorCheckInToolConfig.py b/PhysicsAnalysis/JetTagging/JetTagTools/python/CTTDecorCheckInToolConfig.py new file mode 100644 index 0000000000000000000000000000000000000000..c5442ec086bce6e5e225978ec85fa4a8cadffd7b --- /dev/null +++ b/PhysicsAnalysis/JetTagging/JetTagTools/python/CTTDecorCheckInToolConfig.py @@ -0,0 +1,25 @@ +# Copyright (C) 2002-2022 CERN for the benefit of the ATLAS collaboration +# Author: Katharina Voss katharina.voss@cern.ch + +from AthenaConfiguration.ComponentAccumulator import ComponentAccumulator +from AthenaConfiguration.ComponentFactory import CompFactory +from AthenaCommon.Constants import INFO + + +#------------------------------------ +def CTTDecorCheckInToolCfg(flags,name="CTTDecorCheckInTool", **kwargs): + acc = ComponentAccumulator() + + kwargs.setdefault("JetCollection","AntiKt4EMPFlowJets") + from JetTagTools.ClassifiedTrackTaggerToolConfig import ClassifiedTrackTaggerToolCfg + kwargs.setdefault("ClassifiedTrackTaggerTool",acc.popToolsAndMerge(ClassifiedTrackTaggerToolCfg(flags,name="ClassifiedTrackTaggerTool",JetCollection=kwargs["JetCollection"]))) + kwargs.setdefault("OutputLevel", INFO) + + acc.addEventAlgo(CompFactory.CTTDecorCheckInTool(name, **kwargs)) + return acc + + + + + + diff --git a/PhysicsAnalysis/JetTagging/JetTagTools/python/ClassifiedTrackTaggerToolConfig.py b/PhysicsAnalysis/JetTagging/JetTagTools/python/ClassifiedTrackTaggerToolConfig.py new file mode 100644 index 0000000000000000000000000000000000000000..165a53e7fa2e27a0a2408c02a36e24d49153a54a --- /dev/null +++ b/PhysicsAnalysis/JetTagging/JetTagTools/python/ClassifiedTrackTaggerToolConfig.py @@ -0,0 +1,30 @@ +# Copyright (C) 2002-2022 CERN for the benefit of the ATLAS collaboration +# Author: Katharina Voss katharina.voss@cern.ch + +from AthenaConfiguration.ComponentAccumulator import ComponentAccumulator +from AthenaConfiguration.ComponentFactory import CompFactory + +#------------------------------------ +def ClassifiedTrackTaggerToolCfg(flags,name="ClassifiedTrackTaggerTool", **kwargs): + + acc = ComponentAccumulator() + + kwargs.setdefault('useFivePtJetBinTCT',flags.BTagging.TrkClassFiveBinMode) + kwargs.setdefault('JetCollection',"AntiKt4EMPFlowJets") + + from TrkConfig.TrkVKalVrtFitterConfig import TrkVKalVrtFitterCfg + VertexFitterTool = acc.popToolsAndMerge(TrkVKalVrtFitterCfg(flags,"VertexFitterTool")) + from InDetConfig.InDetVKalVxInJetToolConfig import InDetTrkInJetTypeCfg + trackClassificationTool = acc.popToolsAndMerge(InDetTrkInJetTypeCfg(flags,name='TrkInJetType',JetCollection=kwargs["JetCollection"],VertexFitterTool=VertexFitterTool)) + kwargs.setdefault('TrackClassificationTool',trackClassificationTool) + + ClassifiedTrackTagger = CompFactory.Analysis.ClassifiedTrackTaggerTool(name,**kwargs) + acc.setPrivateTools(ClassifiedTrackTagger) + + return acc + + + + + + diff --git a/PhysicsAnalysis/JetTagging/JetTagTools/share/ClassifiedTrackTaggerTool_test.ref b/PhysicsAnalysis/JetTagging/JetTagTools/share/ClassifiedTrackTaggerTool_test.ref new file mode 100644 index 0000000000000000000000000000000000000000..e40e2d8206cf5d0cf1a608378ffae080f1a677e3 --- /dev/null +++ b/PhysicsAnalysis/JetTagging/JetTagTools/share/ClassifiedTrackTaggerTool_test.ref @@ -0,0 +1,33 @@ +JetTagTools/ClassifiedTrackTaggerTool_test + + +Initializing Gaudi ApplicationMgr using job opts /eos/user/k/katharin/FTAG/22_ctt_tct_deco/build/x86_64-centos7-gcc11-opt/jobOptions/JetTagTools/ClassifiedTrackTaggerTool_tests.txt +JobOptionsSvc INFO # =======> /eos/user/k/katharin/FTAG/22_ctt_tct_deco/build/x86_64-centos7-gcc11-opt/jobOptions/JetTagTools/ClassifiedTrackTaggerTool_tests.txt +JobOptionsSvc INFO # (1,1): ApplicationMgr.ExtSvc += ["StoreGateSvc/ConditionStore", "CondSvc"] +JobOptionsSvc INFO Job options successfully read in from /eos/user/k/katharin/FTAG/22_ctt_tct_deco/build/x86_64-centos7-gcc11-opt/jobOptions/JetTagTools/ClassifiedTrackTaggerTool_tests.txt +ApplicationMgr SUCCESS +==================================================================================================================================== + Welcome to ApplicationMgr (GaudiCoreSvc v36r5) + running on lxplus736.cern.ch on Tue Sep 6 07:49:21 2022 +==================================================================================================================================== +ApplicationMgr INFO Application Manager Configured successfully +ClassIDSvc INFO getRegistryEntries: read 4559 CLIDRegistry entries for module ALL +EventLoopMgr WARNING Unable to locate service "EventSelector" +EventLoopMgr WARNING No events will be processed from external input. +ApplicationMgr INFO Application Manager Initialized successfully +ApplicationMgr Ready +JetTagTools/ClassifiedTrackTaggerTool initGaudi +JetTagTools/ClassifiedTrackTaggerTool_test record +ClassIDSvc INFO getRegistryEntries: read 9344 CLIDRegistry entries for module ALL +ClassIDSvc INFO getRegistryEntries: read 1961 CLIDRegistry entries for module ALL +ClassIDSvc INFO getRegistryEntries: read 67 CLIDRegistry entries for module ALL +ToolSvc.Analysi... INFO TrkVKalVrtFitter initialize() successful +JetTagTools/ClassifiedTrackTaggerTool_test retrieve tool +test CTT with default TCT training +[INFO]: Creating test track particle 1 +[INFO]: Creating test track particle 2 +[INFO]: Creating test track particle 3 +[INFO]: Creating test primary vertex +[INFO]: Creating test jet LorentzVector +[INFO]: Retrieving CTT score +testDefaultTCT is OK diff --git a/PhysicsAnalysis/JetTagging/JetTagTools/share/ClassifiedTrackTaggerTool_tests.txt b/PhysicsAnalysis/JetTagging/JetTagTools/share/ClassifiedTrackTaggerTool_tests.txt new file mode 100644 index 0000000000000000000000000000000000000000..5abb41f84bf467f0fe8fa374fde3d4b12126e28c --- /dev/null +++ b/PhysicsAnalysis/JetTagging/JetTagTools/share/ClassifiedTrackTaggerTool_tests.txt @@ -0,0 +1 @@ +ApplicationMgr.ExtSvc += { "StoreGateSvc/ConditionStore", "CondSvc" }; diff --git a/PhysicsAnalysis/JetTagging/JetTagTools/src/CTTDecorCheckInTool.cxx b/PhysicsAnalysis/JetTagging/JetTagTools/src/CTTDecorCheckInTool.cxx new file mode 100644 index 0000000000000000000000000000000000000000..96a13e6707a23c11dfa3f5eb6a56d19dc8497099 --- /dev/null +++ b/PhysicsAnalysis/JetTagging/JetTagTools/src/CTTDecorCheckInTool.cxx @@ -0,0 +1,129 @@ +/* + Copyright (C) 2002-2022 CERN for the benefit of the ATLAS collaboration +*/ + +#include "PathResolver/PathResolver.h" +#include "TLorentzVector.h" +//#include "StoreGate/ReadDecorHandle.h" + +#include +#include "TestTools/FLOATassert.h" +#include + +#include "JetTagTools/CTTDecorCheckInTool.h" +// +//------------------------------------------------- + +//Constructor-------------------------------------------------------------- +CTTDecorCheckInTool::CTTDecorCheckInTool( const std::string& name, + ISvcLocator* pSvcLocator): + AthAlgorithm( name, pSvcLocator ), + m_classifiedTrackTagger("Analysis::ClassifiedTrackTaggerTool",this), + m_jetCollection("AntiKt4EMPFlowJets") + { + declareProperty("ClassifiedTrackTaggerTool", m_classifiedTrackTagger); + declareProperty("JetCollection",m_jetCollection); + } + +//Destructor--------------------------------------------------------------- + CTTDecorCheckInTool::~CTTDecorCheckInTool(){ + ATH_MSG_DEBUG("ClassifiedTrackTaggerTool destructor called"); + } + +//Initialize--------------------------------------------------------------- + StatusCode CTTDecorCheckInTool::initialize(){ + + + ATH_CHECK( m_particlesKey.initialize() ); + ATH_CHECK( m_verticesKey.initialize() ); + ATH_CHECK( m_jetsKey.initialize() ); + + if(m_jetCollection!="") + { + m_jetReadDecorKey = m_jetCollection+".CTTScore"; + ATH_CHECK( m_jetReadDecorKey.initialize()); + } + + //------- + //check that the ClassifiedTrackTaggerTool can be accessed + if (m_classifiedTrackTagger.retrieve().isFailure()) { + ATH_MSG_DEBUG("Could not find Analysis::ClassifiedTrackTaggerTool"); + return StatusCode::SUCCESS; + } else { + ATH_MSG_DEBUG("Analysis::ClassifiedTrackTaggerTool found"); + } + + return StatusCode::SUCCESS; + } + + StatusCode CTTDecorCheckInTool::finalize() + { + ATH_MSG_DEBUG("CTTDecorCheckInTool finalize()"); + return StatusCode::SUCCESS; + } + + StatusCode CTTDecorCheckInTool::execute() + { + ATH_MSG_DEBUG( "Executing..." ); + if(m_jetCollection=="") {ATH_MSG_FATAL("No JetCollection specified! ");} + + SG::ReadDecorHandle< xAOD::JetContainer, float > jetReadDecorHandle (m_jetReadDecorKey); + + // Retrieve the track particles: + SG::ReadHandle trackTES(m_particlesKey); + if ( !trackTES.isValid() ) { + ATH_MSG_WARNING( "No TrackParticle container found in TDS" ); + return StatusCode::SUCCESS; } + ATH_MSG_DEBUG( "TrackParticleContainer successfully retrieved" ); + + SG::ReadHandle pvTES(m_verticesKey); + if ( !pvTES.isValid() ) { + ATH_MSG_WARNING( "No Primary Vertices container found in TDS" ); + return StatusCode::SUCCESS; } + ATH_MSG_DEBUG( "Primary Vertices container successfully retrieved" ); + const xAOD::Vertex *primVertex=*(pvTES->begin()); + + + + //========================================================================== + SG::ReadHandle jetTES(m_jetsKey); + if ( !jetTES.isValid() ) { + ATH_MSG_WARNING( "No AntiKt4EMPflow jet container found in TDS" ); + return StatusCode::SUCCESS; } + ATH_MSG_DEBUG( "AntiKt4EMPflow jet container successfully retrieved" ); + + //save all TrackParticles in an std::vector (needed as input to the CTT tool) + xAOD::TrackParticleContainer::const_iterator trackItr = trackTES->begin(); + xAOD::TrackParticleContainer::const_iterator trackItrE = trackTES->end(); + std::vector trkparticles(0); + + // Loop over all track particles: + for( ; trackItr != trackItrE; ++trackItr ) { + const xAOD::TrackParticle* trackParticle = ( *trackItr ); + trkparticles.push_back(trackParticle); + } + //first decorate all jets with the CTT method + m_classifiedTrackTagger->decorateJets(trkparticles,*primVertex,*jetTES); + + xAOD::JetContainer::const_iterator jetItr = jetTES->begin(); + xAOD::JetContainer::const_iterator jetItrE = jetTES->end(); + + for(jetItr = jetTES->begin(); jetItr != jetItrE; jetItr++) { + /// this Jet + const xAOD::Jet* curjet = ( *jetItr ); + ATH_MSG_DEBUG( " Jet pt: " << curjet->pt()<<" eta: "<eta()<<" phi: "<< curjet->phi() ); + float CTTScore = m_classifiedTrackTagger->bJetWgts(trkparticles, *primVertex, curjet->p4()); + ATH_MSG_DEBUG ("Retrieved CTT score from CTT tool: " << CTTScore); + ATH_MSG_DEBUG("CTT score of decorated xAOD::Jet : " << jetReadDecorHandle(*curjet)); + assert(Athena_test::isEqual(CTTScore,jetReadDecorHandle(*curjet))); + + } + + /** + for (const xAOD::Jet* & decoJet : *jetReadDecorHandle) { // Access the container. + ATH_MSG_INFO("CTT score of decorated xAOD::Jet : " << jetReadDecorHandle (decoJet); ) // Access the decoration. + }**/ + + return StatusCode::SUCCESS; + } + diff --git a/PhysicsAnalysis/JetTagging/JetTagTools/src/ClassifiedTrackTaggerTool.cxx b/PhysicsAnalysis/JetTagging/JetTagTools/src/ClassifiedTrackTaggerTool.cxx new file mode 100644 index 0000000000000000000000000000000000000000..e2e403cc678aba95ec204f1232d38355ddc79b0b --- /dev/null +++ b/PhysicsAnalysis/JetTagging/JetTagTools/src/ClassifiedTrackTaggerTool.cxx @@ -0,0 +1,179 @@ +/* + Copyright (C) 2002-2022 CERN for the benefit of the ATLAS collaboration +*/ + +#include "JetTagTools/ClassifiedTrackTaggerTool.h" +#include "PathResolver/PathResolver.h" +#include "TLorentzVector.h" +//#include "TrkVKalVrtFitter/TrkVKalVrtFitter.h" + +#include "MVAUtils/BDT.h" +#include "TFile.h" +#include "TTree.h" +#include "GaudiKernel/IChronoStatSvc.h" +// +//------------------------------------------------- +namespace Analysis { +// +//Constructor-------------------------------------------------------------- +ClassifiedTrackTaggerTool::ClassifiedTrackTaggerTool(const std::string& type, + const std::string& name, + const IInterface* parent): + base_class(type,name,parent), + m_trackClassificator("InDet::InDetTrkInJetType/TrackClassificationTool",this), + m_deltaRConeSize(0.4), + m_useFivePtJetBinTCT(false), + m_calibFileName("CTT_calib_v00.root"), + m_jetCollection("AntiKt4EMPFlowJets") + { + declareProperty("TrackClassificationTool", m_trackClassificator); + declareProperty("deltaRConeSize", m_deltaRConeSize); + declareProperty("useFivePtJetBinTCT",m_useFivePtJetBinTCT); + declareProperty("JetCollection",m_jetCollection); + m_timingProfile=nullptr; + } + +//Destructor--------------------------------------------------------------- + ClassifiedTrackTaggerTool::~ClassifiedTrackTaggerTool(){ + ATH_MSG_DEBUG("ClassifiedTrackTaggerTool destructor called"); + } + +//Initialize--------------------------------------------------------------- + StatusCode ClassifiedTrackTaggerTool::initialize(){ + m_initialised = 0; +// + //retrieve calibration file and initialize the m_trkClassBDT + std::string fullPathToFile = PathResolverFindCalibFile("BTagging/20221012track/"+m_calibFileName); + + + std::string strBDTName=""; + if(m_useFivePtJetBinTCT) {strBDTName="CTTtrainedWithRetrainedTCT"; } + else {strBDTName="CTTtrainedWithDefaultTCT"; } + + std::unique_ptr rootFile(TFile::Open(fullPathToFile.c_str(), "READ")); + if (!rootFile) { + ATH_MSG_ERROR("Can not retrieve ClassifiedTrackTagger calibration root file: " << fullPathToFile); + return StatusCode::FAILURE; + } + std::unique_ptr training( (TTree*)rootFile->Get(strBDTName.c_str()) ); + m_CTTBDT = std::make_unique(training.get()); + + + //------- + //check that the TrackClassificationTool can be accessed-> InDetTrkInJetType to get TCT weights per TrackParticle + if (m_trackClassificator.retrieve().isFailure()) { + ATH_MSG_DEBUG("Could not find InDet::InDetTrkInJetType - TrackClassificationTool"); + return StatusCode::SUCCESS; + } else { + ATH_MSG_DEBUG("InDet::InDetTrkInJetType - TrackClassificationTool found"); + } + + //check that the fivePtJetBinTCT is actually used, if CTT is configured to do so + if(m_useFivePtJetBinTCT && !m_trackClassificator->usesFivePtJetBinVersion()) {ATH_MSG_ERROR("FivePtJetBin TCT tool is not used, but required by CTT!"); } + if(!m_useFivePtJetBinTCT && m_trackClassificator->usesFivePtJetBinVersion()) {ATH_MSG_ERROR("FivePtJetBin TCT tool is used, but default version required by CTT!"); } + if(m_useFivePtJetBinTCT) {ATH_MSG_DEBUG("FivePtJetBin version of TCT is used"); } + else {ATH_MSG_DEBUG("Default version of TCT is used"); } + + //SG::WriteDecorHandleKey for CTT jet decoration + if(m_jetCollection!="") + { + m_jetWriteDecorKey = m_jetCollection +".CTTScore"; + ATH_CHECK( m_jetWriteDecorKey.initialize()); + } + + + m_initialised = 1; // Tool is initialised successfully. +//----- + if(msgLvl(MSG::DEBUG)) ATH_CHECK(service("ChronoStatSvc", m_timingProfile)); +//----- + return StatusCode::SUCCESS; + } + + StatusCode ClassifiedTrackTaggerTool::finalize() + { + if(m_timingProfile)m_timingProfile->chronoPrint("ClassifiedTrackTaggerTool"); + ATH_MSG_DEBUG("ClassifiedTrackTaggerTool finalize()"); + return StatusCode::SUCCESS; + } + + float ClassifiedTrackTaggerTool::bJetWgts(const std::vector & InpTrk, const xAOD::Vertex & PV, const TLorentzVector & Jet) const + { + if( !m_initialised ) return -999; + std::vector> TCTweights; + //for each track inside a cone of deltaR around the jet direction save the TCT output (wgtB, wgtL,wgtG) + //if it was not rejected by the TCT track quality cuts + for (auto itrk : InpTrk) { + if((itrk->p4()).DeltaR(Jet)<=m_deltaRConeSize) + { + std::vector v_tctScore = m_trackClassificator->trkTypeWgts(itrk,PV,Jet); + bool b_zeroTCTScore = std::all_of(v_tctScore.begin(), v_tctScore.end(), [](float i) { return i==0; }); + if(!b_zeroTCTScore) { TCTweights.push_back(v_tctScore); } + } + } + + ATH_MSG_DEBUG("[ClassifiedTrackTagger]: retrieved TCT score"); + int ntrk = TCTweights.size(); + if(ntrk< 3) {return -5; } //if less than three tracks passing quality cuts of TCT -> return default value of -5 + //get sorted indices w.r.t. wgtB (highest wgtB track -> first index in sorted_indices) + std::vector sorted_indices = GetSortedIndices(TCTweights); + ATH_MSG_DEBUG("[ClassifiedTrackTagger]: ntrk = " << ntrk << " in jet"); + + float ptjet = Jet.Pt(); + float trackMultiplicity = ( ((float)ntrk) / ptjet) * 1.e3; +//--- + if(m_timingProfile)m_timingProfile->chronoStart("ClassifiedTrackTaggerTool"); + //-----Use MVAUtils to save CPU + //order in which variables are given to the BDT wgtB_0,wgtG_0,wgtL_0,wgtB_1,wgtG_1,wgtL_1,wgtB_2,wgtG_2,wgtL_2, (ntrk/ptjet * 1.e3) + // (0: track with highest wgtB), (1: track with 2nd highest wgtB), (2: track with 3rd highest wgtB) + int iwgtB=0, iwgtL=1, iwgtG=2; + ATH_MSG_DEBUG("[ClassifiedTrackTagger]: ordered signal TCT weights = " << TCTweights[sorted_indices[0]][iwgtB] << "," << TCTweights[sorted_indices[1]][iwgtB] << "," << TCTweights[sorted_indices[2]][iwgtB]); + + //change input variable ordering when final BDT model is chosen! + std::vector bdt_vars={TCTweights[sorted_indices[0]][iwgtB],TCTweights[sorted_indices[0]][iwgtG],TCTweights[sorted_indices[0]][iwgtL], + TCTweights[sorted_indices[1]][iwgtB],TCTweights[sorted_indices[1]][iwgtG],TCTweights[sorted_indices[1]][iwgtL], + TCTweights[sorted_indices[2]][iwgtB],TCTweights[sorted_indices[2]][iwgtG],TCTweights[sorted_indices[2]][iwgtL], + trackMultiplicity}; + float score=m_CTTBDT->GetGradBoostMVA(bdt_vars); + + ATH_MSG_DEBUG("[ClassifiedTrackTagger]: CTT classification score = " << score); + + //----- + if(m_timingProfile)m_timingProfile->chronoStop("ClassifiedTrackTaggerTool"); + return score; + } + + +void ClassifiedTrackTaggerTool::decorateJets(const std::vector & InpTrk, const xAOD::Vertex & primVertex, const xAOD::JetContainer & jets) const +{ + if(m_jetCollection=="") {ATH_MSG_FATAL("No JetCollection specified! ");} + SG::WriteDecorHandle< xAOD::JetContainer, float > jetWriteDecorHandle (m_jetWriteDecorKey); + xAOD::JetContainer::const_iterator jetItr = jets.begin(); + xAOD::JetContainer::const_iterator jetItrE = jets.end(); + + for(jetItr = jets.begin(); jetItr != jetItrE; jetItr++) { + /// this Jet + const xAOD::Jet* curjet = ( *jetItr ); + ATH_MSG_DEBUG( " Jet pt: " << curjet->pt()<<" eta: "<eta()<<" phi: "<< curjet->phi() ); + float CTTScore = bJetWgts(InpTrk, primVertex, curjet->p4()); + jetWriteDecorHandle(*curjet) = CTTScore; + } + //return StatusCode::SUCCESS; +} + +std::vector ClassifiedTrackTaggerTool::GetSortedIndices(std::vector> unordered_vec) const +{ + //from https://stackoverflow.com/questions/1577475/c-sorting-and-keeping-track-of-indexes + int ntrk = unordered_vec.size(); + std::vector indices; + indices.clear(); + for(int i=0; i < ntrk; i++) + { + indices.push_back(i); + } + //sort the vector of indices, such that the index corresponding to the highest wgtB stands first, with the lowest last (unordered_vec[itrk][iwgt], wgtB-> iwgt=0) + std::sort(std::begin(indices), std::end(indices),[&unordered_vec](size_t itrk1, size_t itrk2) {return unordered_vec[itrk1][0] > unordered_vec[itrk2][0];}); + + return indices; +} + +}// close namespace diff --git a/PhysicsAnalysis/JetTagging/JetTagTools/src/components/JetTagTools_entries.cxx b/PhysicsAnalysis/JetTagging/JetTagTools/src/components/JetTagTools_entries.cxx index 7abf1b05a312e08434080b63364feab589772d28..72acbeabb70a9a2dc8a81d5cf9fbe90aca842eec 100644 --- a/PhysicsAnalysis/JetTagging/JetTagTools/src/components/JetTagTools_entries.cxx +++ b/PhysicsAnalysis/JetTagging/JetTagTools/src/components/JetTagTools_entries.cxx @@ -22,6 +22,8 @@ #include "JetTagTools/MV2Tag.h" +#include "JetTagTools/ClassifiedTrackTaggerTool.h" +#include "JetTagTools/CTTDecorCheckInTool.h" DECLARE_COMPONENT( Analysis::IPTag ) DECLARE_COMPONENT( Analysis::SVTag ) @@ -41,4 +43,6 @@ DECLARE_COMPONENT( Analysis::SVForIPTool ) DECLARE_COMPONENT( Analysis::BasicTrackGradeFactory ) DECLARE_COMPONENT( Analysis::DetailedTrackGradeFactory ) DECLARE_COMPONENT( Analysis::MV2Tag ) +DECLARE_COMPONENT( Analysis::ClassifiedTrackTaggerTool ) +DECLARE_COMPONENT( CTTDecorCheckInTool ) diff --git a/PhysicsAnalysis/JetTagging/JetTagTools/test/ClassifiedTrackTaggerTool_test.cxx b/PhysicsAnalysis/JetTagging/JetTagTools/test/ClassifiedTrackTaggerTool_test.cxx new file mode 100644 index 0000000000000000000000000000000000000000..eb99f57bf56f07c0f4b6c2e62a0cba2c3f162a33 --- /dev/null +++ b/PhysicsAnalysis/JetTagging/JetTagTools/test/ClassifiedTrackTaggerTool_test.cxx @@ -0,0 +1,192 @@ +/* + * Copyright (C) 2002-2022 CERN for the benefit of the ATLAS collaboration. + */ +/** + * @file JetTagTools/test/ClassifiedTrackTaggerTool_test.cxx + * @author Katharina Voss + * @date May, 2022 + * @brief Simple unit test for the ClassifiedTrackTaggerTool. Adopted from InDetTrkInJetType_test.cxx (Scott Synder, synder@bnl.gov) + */ + + +#undef NDEBUG +#include "JetTagTools/ClassifiedTrackTaggerTool.h" +#include "xAODTracking/Vertex.h" +#include "xAODTracking/TrackParticle.h" +#include "MagFieldConditions/AtlasFieldCacheCondObj.h" +#include "EventPrimitives/EventPrimitivesHelpers.h" +#include "TestTools/initGaudi.h" +#include "TestTools/FLOATassert.h" +#include "CxxUtils/ubsan_suppress.h" +#include "GaudiKernel/ToolHandle.h" +#include "GaudiKernel/Incident.h" +#include "GaudiKernel/IIncidentListener.h" +#include "GaudiKernel/SystemOfUnits.h" +#include "AthenaKernel/DummyRCUSvc.h" +#include "TInterpreter.h" +#include +#include +#include + + +#include "CLHEP/Vector/LorentzVector.h" + +using Gaudi::Units::mm; +using Gaudi::Units::MeV; +using Gaudi::Units::GeV; + + +AmgSymMatrix(5) cov5() +{ + AmgSymMatrix(5) m; + m.setIdentity(); + m(0,0) = 1.e-3; //d0 + m(1,1) = 1.e-2; //Z0 + return m; +} + + +// Copied from TrackParticleCreatorTool. +void setDefiningParameters( xAOD::TrackParticle& tp, + const Trk::Perigee& perigee ) +{ + tp.setDefiningParameters(perigee.parameters()[Trk::d0], + perigee.parameters()[Trk::z0], + perigee.parameters()[Trk::phi0], + perigee.parameters()[Trk::theta], + perigee.parameters()[Trk::qOverP]); + const AmgSymMatrix(5)* covMatrix = perigee.covariance(); + // see https://its.cern.ch/jira/browse/ATLASRECTS-645 for justification to comment out the following line + // assert(covMatrix && covMatrix->rows()==5&& covMatrix->cols()==5); + std::vector covMatrixVec; + if( !covMatrix ) ;//ATH_MSG_WARNING("Setting Defining parameters without error matrix"); + else Amg::compress(*covMatrix,covMatrixVec); + tp.setDefiningParametersCovMatrixVec(covMatrixVec); + const Amg::Vector3D& surfaceCenter = perigee.associatedSurface().center(); + tp.setParametersOrigin(surfaceCenter.x(), surfaceCenter.y(), surfaceCenter.z() ); +} + + +xAOD::TrackParticle makeTP(int i) +{ + std::cout << "[INFO]: Creating test track particle " << i << std::endl; + float posx=0., posy=0., posz=0.; + float momx=0., momy=0., momz=0.; + uint8_t pixelHits=0, sctHits=0; + float chi2=0; float numDof=1; + + if(i==1) {posx=-1.35; posy=-1.23; posz=60.36; momx=5333.7; momy=-6171.29; momz=379.76; pixelHits=4; sctHits=8; chi2= 2.23064; numDof =5; } + else if(i==2) {posx=-0.4; posy=-0.5; posz=59.027; momx=5722.6; momy=-5500.7; momz=3772.28; pixelHits=3; sctHits=7; chi2= 6.233; numDof=10; } + else if(i==3) {posx=-0.3; posy=-0.3; posz=58.9912; momx=14652.3; momy=-15669.5; momz=663.11; pixelHits=3; sctHits=7; chi2 = 11.5077; numDof = 13; } + else {std::cout << "[ERROR ]: Specified TrackParticle " << i << " cannot be created, no rules provided" << std::endl; } + + Amg::Vector3D pos0 { 0, 0, 0 }; + Amg::Vector3D pos { posx*mm, posy*mm, posz*mm }; + Amg::Vector3D mom { momx*MeV, momy*MeV, momz*MeV }; + + Trk::Perigee p (pos, mom, 1, pos0, cov5()); + + xAOD::TrackParticle tp; + tp.makePrivateStore(); + setDefiningParameters (tp, p); + tp.setFitQuality (chi2, numDof); + tp.setSummaryValue (pixelHits, xAOD::numberOfPixelHits); + tp.setSummaryValue (sctHits, xAOD::numberOfSCTHits); + + return tp; +} + + +void testDefaultTCT (Analysis::IClassifiedTrackTaggerTool& cttTool) +{ + std::cout << "test CTT with default TCT training\n"; + xAOD::TrackParticle TP1 = makeTP(1); + xAOD::TrackParticle TP2 = makeTP(2); + xAOD::TrackParticle TP3 = makeTP(3); + + + std::vector v_tp; + v_tp.push_back(& TP1); + v_tp.push_back(& TP2); + v_tp.push_back(& TP3); + + std::cout << "[INFO]: Creating test primary vertex" << std::endl; + xAOD::Vertex pv; + pv.makePrivateStore(); + pv.setPosition ({-0.49*mm, -0.50*mm, 59.0*mm}); + + std::cout << "[INFO]: Creating test jet LorentzVector" << std::endl; + TLorentzVector jet(88424.03*MeV, -63613.38*MeV, 41088.09*MeV, 118046.10*MeV); // ca. 108 GeV + + //float predCTTScore = -0.22773; + float predCTTScore = -0.335793; + std::cout << "[INFO]: Retrieving CTT score "<< std::endl; + float cttScore = cttTool.bJetWgts(v_tp, pv, jet); + assert(Athena_test::isEqual(cttScore,predCTTScore)); + + std::cout << "testDefaultTCT is OK" << std::endl; +} + +EventIDBase timestamp (int t) +{ + return EventIDBase (EventIDBase::UNDEFNUM, // run + EventIDBase::UNDEFEVT, // event + t); +} + + +EventIDBase runlbn (int run, + int lbn) +{ + return EventIDBase (run, // run + EventIDBase::UNDEFEVT, // event + EventIDBase::UNDEFNUM, // timestamp + 0, // ns offset + lbn); +} + + +int main() +{ + std::cout << "JetTagTools/ClassifiedTrackTaggerTool_test\n"; + CxxUtils::ubsan_suppress ([]() { TInterpreter::Instance(); }); + ISvcLocator* svcloc = nullptr; + if (!Athena_test::initGaudi("JetTagTools/ClassifiedTrackTaggerTool_tests.txt", svcloc)) { + return 1; + } + + + std::cout << "JetTagTools/ClassifiedTrackTaggerTool initGaudi \n"; + + + EventContext ctx; + ctx.setExtension (Atlas::ExtendedEventContext()); + EventIDBase eid (1, 0, 0, 0, 20); + ctx.setEventID (eid); + + Gaudi::Hive::setCurrentContext(ctx); + + Athena_test::DummyRCUSvc rcu; + DataObjID id ("fieldCondObj"); + auto cc = std::make_unique > (rcu, id); + const EventIDRange range (runlbn (1, 10), runlbn (1, 100)); + assert( cc->insert (range, std::make_unique(), ctx).isSuccess() ); + + ServiceHandle conditionStore ("ConditionStore", "test"); + assert( conditionStore->record (std::move (cc), "fieldCondObj") ); + + + std::cout << "JetTagTools/ClassifiedTrackTaggerTool_test record \n"; + + + ToolHandle cttTool ("Analysis::ClassifiedTrackTaggerTool"); + assert( cttTool.retrieve().isSuccess() ); + + + std::cout << "JetTagTools/ClassifiedTrackTaggerTool_test retrieve tool \n"; + + + testDefaultTCT (*cttTool); + + return 0; +} diff --git a/Tracking/TrkConfig/python/TrkVKalVrtFitterConfig.py b/Tracking/TrkConfig/python/TrkVKalVrtFitterConfig.py index 1acc7adbad8daf0290ace545b7e06ee43a9b143d..d0e33d1df0224f7861d4d7aa9558fa770fc1ab92 100644 --- a/Tracking/TrkConfig/python/TrkVKalVrtFitterConfig.py +++ b/Tracking/TrkConfig/python/TrkVKalVrtFitterConfig.py @@ -4,6 +4,21 @@ from AthenaConfiguration.ComponentAccumulator import ComponentAccumulator from AthenaConfiguration.ComponentFactory import CompFactory +def TrkVKalVrtFitterBaseCfg(flags, name="TrkVKalVrtFitterBase", **kwargs): + from MagFieldServices.MagFieldServicesConfig import AtlasFieldCacheCondAlgCfg + acc = AtlasFieldCacheCondAlgCfg(flags) # To produce AtlasFieldCacheCondObj + + if "Extrapolator" not in kwargs: + from TrkConfig.AtlasExtrapolatorConfig import AtlasExtrapolatorCfg + kwargs.setdefault("Extrapolator", acc.popToolsAndMerge( + AtlasExtrapolatorCfg(flags))) + kwargs.setdefault("IterationNumber",50) + kwargs.setdefault("Robustness",6) + + acc.setPrivateTools(CompFactory.Trk.TrkVKalVrtFitter(name, **kwargs)) + return acc + + def TrkVKalVrtFitterCfg(flags, name="TrkVKalVrtFitter", **kwargs): from MagFieldServices.MagFieldServicesConfig import AtlasFieldCacheCondAlgCfg acc = AtlasFieldCacheCondAlgCfg(flags) # To produce AtlasFieldCacheCondObj