From 6abfe431bab28708b4f7140438b7bb9d357bbf40 Mon Sep 17 00:00:00 2001
From: Goetz Gaycken <goetz.gaycken@cern.ch>
Date: Thu, 2 Apr 2020 14:39:13 +0200
Subject: [PATCH 01/26] Migrate DiTauTrackParticleThinning to data handles.

---
 .../DiTauTrackParticleThinning.h              | 13 ++++--
 .../src/DiTauTrackParticleThinning.cxx        | 42 +++++++------------
 2 files changed, 25 insertions(+), 30 deletions(-)

diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/DiTauTrackParticleThinning.h b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/DiTauTrackParticleThinning.h
index 0403d39f8c9b..bd5d31fbd8ec 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/DiTauTrackParticleThinning.h
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/DiTauTrackParticleThinning.h
@@ -16,8 +16,11 @@
 #include "DerivationFrameworkInterfaces/IThinningTool.h"
 #include "GaudiKernel/ToolHandle.h"
 #include "DerivationFrameworkInDet/TracksInCone.h"
+#include "xAODTau/DiTauJetContainer.h"
 #include "xAODTracking/TrackParticleContainer.h"
+#include "xAODEgamma/EgammaContainer.h"
 #include "StoreGate/ThinningHandleKey.h"
+#include "StoreGate/ReadHandleKey.h"
 
 namespace ExpressionParsing {
   class ExpressionParser;
@@ -35,13 +38,17 @@ namespace DerivationFramework {
       virtual StatusCode doThinning() const override;
 
     private:
-      mutable std::atomic<unsigned int> m_ntot, m_npass;
+      mutable std::atomic<unsigned int> m_ntot  {};
+      mutable std::atomic<unsigned int> m_npass {};
       StringProperty m_streamName
         { this, "StreamName", "", "Name of the stream being thinned" };
+      SG::ReadHandleKey<xAOD::DiTauJetContainer>          m_ditauKey
+        { this, "DiTauKey","",""};
       SG::ThinningHandleKey<xAOD::TrackParticleContainer> m_inDetSGKey
         { this, "InDetTrackParticlesKey", "InDetTrackParticles", "" };
-      std::string m_ditauSGKey, m_selectionString;
-      ExpressionParsing::ExpressionParser *m_parser;
+      Gaudi::Property<std::string>                        m_selectionString
+         { this, "SelectionString", "", ""};
+     std::unique_ptr<ExpressionParsing::ExpressionParser> m_parser;
   }; 
 }
 
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/DiTauTrackParticleThinning.cxx b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/DiTauTrackParticleThinning.cxx
index cd8ab067c68d..f090c84b42c6 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/DiTauTrackParticleThinning.cxx
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/DiTauTrackParticleThinning.cxx
@@ -14,7 +14,6 @@
 #include "ExpressionEvaluation/SGxAODProxyLoader.h"
 #include "ExpressionEvaluation/MultipleProxyLoader.h"
 #include "ExpressionEvaluation/SGNTUPProxyLoader.h"
-#include "xAODTau/DiTauJetContainer.h"
 #include "xAODTracking/TrackParticleContainer.h"
 #include "StoreGate/ThinningHandle.h"
 #include "GaudiKernel/ThreadLocalContext.h"
@@ -25,16 +24,8 @@
 DerivationFramework::DiTauTrackParticleThinning::DiTauTrackParticleThinning(const std::string& t,
                                                                             const std::string& n,
                                                                             const IInterface* p ) :
-base_class(t,n,p),
-m_ntot(0),
-m_npass(0),
-m_ditauSGKey(""),
-m_selectionString(""),
-m_parser(0)
-{
-    declareProperty("DiTauKey", m_ditauSGKey);
-    declareProperty("SelectionString", m_selectionString);
-}
+base_class(t,n,p)
+{}
 
 // Destructor
 DerivationFramework::DiTauTrackParticleThinning::~DiTauTrackParticleThinning() {
@@ -45,19 +36,17 @@ StatusCode DerivationFramework::DiTauTrackParticleThinning::initialize()
 {
     // Decide which collections need to be checked for ID TrackParticles
     ATH_MSG_VERBOSE("initialize() ...");
+    ATH_CHECK( m_ditauKey.initialize () );
     ATH_CHECK( m_inDetSGKey.initialize (m_streamName) );
     ATH_MSG_INFO("Using " << m_inDetSGKey.key() << "as the source collection for inner detector track particles");
-    if (m_ditauSGKey=="") {
-        ATH_MSG_FATAL("No ditau collection provided for thinning.");
-        return StatusCode::FAILURE;
-    } else { ATH_MSG_INFO("Inner detector track particles associated with objects in " << m_ditauSGKey << " will be retained in this format with the rest being thinned away");}
-    
+    ATH_MSG_INFO("Inner detector track particles associated with objects in " << m_ditauKey.key() << " will be retained in this format with the rest being thinned away");
+
     // Set up the text-parsing machinery for selectiong the ditau directly according to user cuts
     if (m_selectionString!="") {
       ExpressionParsing::MultipleProxyLoader *proxyLoaders = new ExpressionParsing::MultipleProxyLoader();
       proxyLoaders->push_back(new ExpressionParsing::SGxAODProxyLoader(evtStore()));
       proxyLoaders->push_back(new ExpressionParsing::SGNTUPProxyLoader(evtStore()));
-      m_parser = new ExpressionParsing::ExpressionParser(proxyLoaders);
+      m_parser = std::make_unique<ExpressionParsing::ExpressionParser>(proxyLoaders);
       m_parser->loadExpression(m_selectionString);
     }
     return StatusCode::SUCCESS;
@@ -67,10 +56,7 @@ StatusCode DerivationFramework::DiTauTrackParticleThinning::finalize()
 {
     ATH_MSG_VERBOSE("finalize() ...");
     ATH_MSG_INFO("Processed "<< m_ntot <<" tracks, "<< m_npass<< " were retained ");
-    if (m_selectionString!="") {
-        delete m_parser;
-        m_parser = 0;
-    }
+    m_parser.reset();
     return StatusCode::SUCCESS;
 }
 
@@ -95,9 +81,9 @@ StatusCode DerivationFramework::DiTauTrackParticleThinning::doThinning() const
     
     // Retrieve containers
     // ... ditaus
-    const xAOD::DiTauJetContainer* importedDiTaus(0);
-    if (evtStore()->retrieve(importedDiTaus,m_ditauSGKey).isFailure()) {
-        ATH_MSG_ERROR("No ditau collection with name " << m_ditauSGKey << " found in StoreGate!");
+    SG::ReadHandle<xAOD::DiTauJetContainer> importedDiTaus(m_ditauKey,ctx);
+    if (!importedDiTaus.isValid()) {
+        ATH_MSG_ERROR("No ditau collection with name " << m_ditauKey.key() << " found in StoreGate!");
         return StatusCode::FAILURE;
     }
     unsigned int nDiTaus(importedDiTaus->size());
@@ -142,12 +128,14 @@ StatusCode DerivationFramework::DiTauTrackParticleThinning::doThinning() const
           }
         }
     }
-    
+
     // Count up the mask contents
+    unsigned int n_pass=0;
     for (unsigned int i=0; i<nTracks; ++i) {
-        if (mask[i]) ++m_npass;
+        if (mask[i]) ++n_pass;
     }
-    
+    m_npass += n_pass;
+
     // Execute the thinning service based on the mask. Finish.
     importedTrackParticles.keep (mask);
 
-- 
GitLab


From afd6e128867cfa1f070b14d834d4ab5106d419e1 Mon Sep 17 00:00:00 2001
From: Goetz Gaycken <goetz.gaycken@cern.ch>
Date: Thu, 2 Apr 2020 14:58:30 +0200
Subject: [PATCH 02/26] Migrate EgammaTrackParticleThinning to data handles.

---
 .../EgammaTrackParticleThinning.h             | 22 ++++--
 .../src/EgammaTrackParticleThinning.cxx       | 75 ++++++++-----------
 2 files changed, 47 insertions(+), 50 deletions(-)

diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/EgammaTrackParticleThinning.h b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/EgammaTrackParticleThinning.h
index f0a2a1d09d16..548810535fe9 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/EgammaTrackParticleThinning.h
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/EgammaTrackParticleThinning.h
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
+  Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 */
 
 ///////////////////////////////////////////////////////////////////
@@ -36,18 +36,26 @@ namespace DerivationFramework {
       virtual StatusCode doThinning() const override;
 
     private:
-      mutable std::atomic<unsigned int> m_ntot, m_ntotGSF, m_npass, m_nGSFPass;
+      mutable std::atomic<unsigned int> m_ntot {};
+      mutable std::atomic<unsigned int> m_ntotGSF {};
+      mutable std::atomic<unsigned int> m_npass {};
+      mutable std::atomic<unsigned int> m_nGSFPass {};
       StringProperty m_streamName
         { this, "StreamName", "", "Name of the stream being thinned" };
+      SG::ReadHandleKey<xAOD::EgammaContainer> m_egammaKey
+         { this, "SGKey", "" ""};
       SG::ThinningHandleKey<xAOD::TrackParticleContainer> m_inDetSGKey
         { this, "InDetTrackParticlesKey", "InDetTrackParticles", "" };
       SG::ThinningHandleKey<xAOD::TrackParticleContainer> m_gsfSGKey
         { this, "GSFTrackParticlesKey", "GSFTrackParticles", "" };
-      std::string m_sgKey;
-      std::string m_selectionString;
-      bool m_bestMatchOnly;
-      float m_coneSize;
-      ExpressionParsing::ExpressionParser *m_parser;
+      Gaudi::Property<std::string> m_selectionString
+        { this, "SelectionString", "", ""};
+      Gaudi::Property<bool> m_bestMatchOnly
+        { this, "BestMatchOnly", true, ""};
+      Gaudi::Property<float> m_coneSize
+        { this, "ConeSize", -1.0, ""};
+
+      std::unique_ptr<ExpressionParsing::ExpressionParser> m_parser;
       void setPhotonMasks(std::vector<bool>&, std::vector<bool>&, const xAOD::EgammaContainer*, const xAOD::TrackParticleContainer*, const xAOD::TrackParticleContainer*, const bool) const;
       void setPhotonMasks(std::vector<bool>&, std::vector<bool>&, std::vector<const xAOD::Egamma*>&, const xAOD::TrackParticleContainer*, const xAOD::TrackParticleContainer*, const bool) const;
       void setElectronMasks(std::vector<bool>&, std::vector<bool>&, const xAOD::EgammaContainer*, const xAOD::TrackParticleContainer*, const xAOD::TrackParticleContainer*, const bool) const;
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/EgammaTrackParticleThinning.cxx b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/EgammaTrackParticleThinning.cxx
index b8d6d348c559..69ba11ac726a 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/EgammaTrackParticleThinning.cxx
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/EgammaTrackParticleThinning.cxx
@@ -25,22 +25,8 @@
 DerivationFramework::EgammaTrackParticleThinning::EgammaTrackParticleThinning(const std::string& t,
                                                                               const std::string& n,
                                                                               const IInterface* p ) :
-base_class(t,n,p),
-m_ntot(0),
-m_ntotGSF(0),
-m_npass(0),
-m_nGSFPass(0),
-m_sgKey(""),
-m_selectionString(""),
-m_bestMatchOnly(true),
-m_coneSize(-1.0),
-m_parser(0)
-{
-    declareProperty("SGKey", m_sgKey);
-    declareProperty("SelectionString", m_selectionString);
-    declareProperty("BestMatchOnly", m_bestMatchOnly);
-    declareProperty("ConeSize", m_coneSize);
-}
+base_class(t,n,p)
+{}
 
 // Destructor
 DerivationFramework::EgammaTrackParticleThinning::~EgammaTrackParticleThinning() {
@@ -51,26 +37,24 @@ StatusCode DerivationFramework::EgammaTrackParticleThinning::initialize()
 {
     // Decide which collections need to be checked for ID TrackParticles
     ATH_MSG_VERBOSE("initialize() ...");
+    ATH_CHECK( m_egammaKey.initialize());
     ATH_CHECK( m_inDetSGKey.initialize (m_streamName) );
     ATH_MSG_INFO("Using " << m_inDetSGKey.key() << "as the source collection for inner detector track particles");
 
-    if (m_sgKey=="") {
-        ATH_MSG_FATAL("No e-gamma collection provided for thinning.");
-        return StatusCode::FAILURE;
-    } else { ATH_MSG_INFO("Inner detector track particles associated with objects in " << m_sgKey << " will be retained in this format with the rest being thinned away");}
+    ATH_MSG_INFO("Inner detector track particles associated with objects in " << m_egammaKey.key() << " will be retained in this format with the rest being thinned away");
 
     ATH_CHECK( m_gsfSGKey.initialize (m_streamName) );
     ATH_MSG_INFO("GSF track particles associated with objects in " << m_gsfSGKey << " will be retained in this format with the rest being thinned away");
     
     // Set up the text-parsing machinery for selectiong the photon directly according to user cuts
-    if (m_selectionString!="") {
+    if (!m_selectionString.empty()) {
 	    ExpressionParsing::MultipleProxyLoader *proxyLoaders = new ExpressionParsing::MultipleProxyLoader();
 	    proxyLoaders->push_back(new ExpressionParsing::SGxAODProxyLoader(evtStore()));
 	    proxyLoaders->push_back(new ExpressionParsing::SGNTUPProxyLoader(evtStore()));
-	    if (m_selectionString!="") {
-            m_parser = new ExpressionParsing::ExpressionParser(proxyLoaders);
-            m_parser->loadExpression(m_selectionString);
-        }
+	    if (!m_selectionString.empty()) {
+               m_parser = std::make_unique<ExpressionParsing::ExpressionParser>(proxyLoaders);
+               m_parser->loadExpression(m_selectionString);
+            }
     }
     
     return StatusCode::SUCCESS;
@@ -81,10 +65,7 @@ StatusCode DerivationFramework::EgammaTrackParticleThinning::finalize()
     ATH_MSG_VERBOSE("finalize() ...");
     ATH_MSG_INFO("Processed "<< m_ntot <<" tracks, of which "<< m_npass<< " were retained ");
     ATH_MSG_INFO("Processed "<< m_ntotGSF <<" GSF tracks, of which "<< m_nGSFPass << " were retained ");
-    if (m_selectionString!="") {
-        delete m_parser;
-        m_parser = 0;
-    }
+    m_parser.reset();
     
     return StatusCode::SUCCESS;
 }
@@ -112,9 +93,9 @@ StatusCode DerivationFramework::EgammaTrackParticleThinning::doThinning() const
     m_ntotGSF += nGSF;
     
     // Retrieve e-gamma container
-    const xAOD::EgammaContainer* importedEgamma(0);
-    if (evtStore()->retrieve(importedEgamma,m_sgKey).isFailure()) {
-        ATH_MSG_ERROR("No e-gamma collection with name " << m_sgKey << " found in StoreGate!");
+    SG::ReadHandle<xAOD::EgammaContainer> importedEgamma(m_egammaKey,ctx);
+    if (!importedEgamma.isValid()) {
+        ATH_MSG_ERROR("No e-gamma collection with name " << m_egammaKey.key() << " found in StoreGate!");
         return StatusCode::FAILURE;
     }
     unsigned int nEgammas(importedEgamma->size());
@@ -122,7 +103,7 @@ StatusCode DerivationFramework::EgammaTrackParticleThinning::doThinning() const
     std::vector<const xAOD::Egamma*> egToCheck; egToCheck.clear();
     
     // Execute the text parsers if requested
-    if (m_selectionString!="") {
+    if (!m_selectionString.empty()) {
         std::vector<int> entries =  m_parser->evaluateAsVector();
         unsigned int nEntries = entries.size();
         // check the sizes are compatible
@@ -136,27 +117,35 @@ StatusCode DerivationFramework::EgammaTrackParticleThinning::doThinning() const
     }
     
     // Are we dealing with electrons or photons?
-    const xAOD::ElectronContainer* testElectrons = dynamic_cast<const xAOD::ElectronContainer*>(importedEgamma);
-    const xAOD::PhotonContainer* testPhotons = dynamic_cast<const xAOD::PhotonContainer*>(importedEgamma);
+    const xAOD::ElectronContainer* testElectrons = dynamic_cast<const xAOD::ElectronContainer*>(importedEgamma.cptr());
+    const xAOD::PhotonContainer* testPhotons = dynamic_cast<const xAOD::PhotonContainer*>(importedEgamma.cptr());
     bool isElectrons(false), isPhotons(false);
     if (testElectrons) isElectrons = true;
     if (testPhotons) isPhotons = true;
 
     // Set elements in the mask to true if there is a corresponding ElementLink from a reconstructed object
-    if (m_selectionString=="") { // check all objects as user didn't provide a selection string
-        if (isElectrons) setElectronMasks(mask,gsfMask,importedEgamma,importedTrackParticles.cptr(),importedGSFTrackParticles.cptr(),m_bestMatchOnly);
-        if (isPhotons) setPhotonMasks(mask,gsfMask,importedEgamma,importedTrackParticles.cptr(),importedGSFTrackParticles.cptr(),m_bestMatchOnly);
+    if (m_selectionString.empty()) { // check all objects as user didn't provide a selection string
+        if (isElectrons) setElectronMasks(mask,gsfMask,importedEgamma.cptr(),importedTrackParticles.cptr(),importedGSFTrackParticles.cptr(),m_bestMatchOnly);
+        if (isPhotons) setPhotonMasks(mask,gsfMask,importedEgamma.cptr(),importedTrackParticles.cptr(),importedGSFTrackParticles.cptr(),m_bestMatchOnly);
     } else { // check only photons passing user selection string
         if (isElectrons) setElectronMasks(mask,gsfMask,egToCheck,importedTrackParticles.cptr(),importedGSFTrackParticles.cptr(),m_bestMatchOnly);
         if (isPhotons) setPhotonMasks(mask,gsfMask,egToCheck,importedTrackParticles.cptr(),importedGSFTrackParticles.cptr(),m_bestMatchOnly);
     }
-    
+
     // Count up the mask contents
-    for (unsigned int i=0; i<nTracks; ++i) {
-        if (mask[i]) ++m_npass;
+    {
+       unsigned int n_pass=0;
+       for (unsigned int i=0; i<nTracks; ++i) {
+          if (mask[i]) ++n_pass;
+       }
+    m_npass += n_pass;
     }
-    for (unsigned int i=0; i<nGSF; ++i) {
-        if (gsfMask[i]) ++m_nGSFPass;
+    {
+       unsigned int n_gsf_pass=0;
+       for (unsigned int i=0; i<nGSF; ++i) {
+          if (gsfMask[i]) ++n_gsf_pass;
+       }
+       m_nGSFPass += n_gsf_pass;
     }
     
     
-- 
GitLab


From 5ac19295affce057d535d6c928b9b363974cc4c4 Mon Sep 17 00:00:00 2001
From: Goetz Gaycken <goetz.gaycken@cern.ch>
Date: Thu, 2 Apr 2020 16:20:51 +0200
Subject: [PATCH 03/26] Migrate EGammaTracksThinning to data handles.

---
 .../EGammaTracksThinning.h                    | 16 ++++++---
 .../src/EGammaTracksThinning.cxx              | 33 +++++++------------
 2 files changed, 24 insertions(+), 25 deletions(-)

diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/EGammaTracksThinning.h b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/EGammaTracksThinning.h
index 664669342afe..2fb3fca871f0 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/EGammaTracksThinning.h
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/EGammaTracksThinning.h
@@ -20,6 +20,10 @@
 #include "TrkTrack/Track.h" 
 #include "StoreGate/ThinningHandleKey.h"
 #include "StoreGate/ThinningHandle.h"
+#include "StoreGate/ReadHandleKey.h"
+#include "xAODEgamma/PhotonContainer.h"
+#include "xAODEgamma/ElectronContainer.h"
+
 
 namespace DerivationFramework {
 
@@ -40,12 +44,16 @@ namespace DerivationFramework {
     
     StringProperty m_streamName
       { this, "StreamName", "", "Name of the stream being thinned" };
+    SG::ReadHandleKey<xAOD::ElectronContainer> m_electronsContainerKey
+      { this, "electronContainerName", "Electrons", "" };
+    SG::ReadHandleKey<xAOD::PhotonContainer>   m_photonsContainerKey
+      { this, "photonContainerName", "Photons", ""};
     SG::ThinningHandleKey<TrackCollection> m_tracksCollectionName
       { this, "tracksCollectionName", "Tracks", "" };
-    std::string m_electronsContainerName;
-    std::string m_photonsContainerName;
-    double m_dr;
-    double m_minEtEg;
+    Gaudi::Property<double> m_dr
+      { this, "deltaR", 0.5, "" };
+    Gaudi::Property<double> m_minEtEg
+      { this, "minEtEg", 0,""};
 
     std::set<int> findGoodTracks(const TrackCollection* trackCont,
                                  const TLorentzVector& candHepLorentz, 
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/EGammaTracksThinning.cxx b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/EGammaTracksThinning.cxx
index 4c4cd8171d56..b1c2eca94fde 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/EGammaTracksThinning.cxx
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/EGammaTracksThinning.cxx
@@ -4,8 +4,6 @@
 
 #include "DerivationFrameworkInDet/EGammaTracksThinning.h"
 #include "TrkParameters/TrackParameters.h"
-#include "xAODEgamma/PhotonContainer.h"
-#include "xAODEgamma/ElectronContainer.h"
 #include "FourMomUtils/P4Helpers.h"
 #include "StoreGate/ThinningHandle.h"
 #include "GaudiKernel/ThreadLocalContext.h"
@@ -13,20 +11,13 @@
 DerivationFramework::EGammaTracksThinning::EGammaTracksThinning(const std::string& type, 
                                                     const std::string& name, 
                                                     const IInterface* parent) :
-  base_class(type, name, parent),
-  m_electronsContainerName("Electrons"),
-  m_photonsContainerName("Photons"),
-  m_dr(0.5),
-  m_minEtEg(0)
-{
-  declareProperty("electronContainerName", m_electronsContainerName = "Electrons");
-  declareProperty("photonContainerName"  , m_photonsContainerName   = "Photons");
-  declareProperty("deltaR"               , m_dr=0.5);
-  declareProperty("minEtEg"              , m_minEtEg = 0 );
-}
+  base_class(type, name, parent)
+{}
 
 StatusCode DerivationFramework::EGammaTracksThinning::initialize(){
 
+  ATH_CHECK( m_electronsContainerKey.initialize() );
+  ATH_CHECK( m_photonsContainerKey.initialize() );
   ATH_CHECK( m_tracksCollectionName.initialize (m_streamName) );
   return StatusCode::SUCCESS;
 }
@@ -48,31 +39,31 @@ StatusCode DerivationFramework::EGammaTracksThinning::doThinning() const
   
   // retrieve the electron collection
 
-  const xAOD::ElectronContainer* electronContainer = evtStore()->retrieve < const xAOD::ElectronContainer > (m_electronsContainerName);
-  if ( !electronContainer )
+  SG::ReadHandle<xAOD::ElectronContainer> electronContainer(m_electronsContainerKey, ctx);
+  if ( !electronContainer.isValid() )
     {
-      ATH_MSG_WARNING( "Container '" << m_electronsContainerName 
+      ATH_MSG_WARNING( "Container '" << m_electronsContainerKey.key()
                        << "' could not be retrieved from StoreGate!" ); 
       return StatusCode::FAILURE;
     } 
   else
     {
-      ATH_MSG_DEBUG( "Container '" << m_electronsContainerName
+      ATH_MSG_DEBUG( "Container '" << m_electronsContainerKey.key()
                      << "' retrieved from StoreGate" );
     }
 
    // retrieve the photon collection
   
-  const xAOD::PhotonContainer* photonContainer = evtStore()->retrieve < const xAOD::PhotonContainer > (m_photonsContainerName);
-  if ( !photonContainer )
+  SG::ReadHandle<xAOD::PhotonContainer> photonContainer(m_photonsContainerKey,ctx);
+  if ( !photonContainer.isValid() )
     {
-      ATH_MSG_WARNING( "Container '" << m_photonsContainerName 
+      ATH_MSG_WARNING( "Container '" << m_photonsContainerKey.key()
                        << "' could not be retrieved from StoreGate!" ); 
       return StatusCode::FAILURE;
     } 
   else
     {
-      ATH_MSG_DEBUG( "Container '" << m_photonsContainerName
+      ATH_MSG_DEBUG( "Container '" << m_photonsContainerKey.key()
                      << "' retrieved from StoreGate" );
     }
 
-- 
GitLab


From 9926b621dbcdceb0b9ffc9a92778e8b365689ad3 Mon Sep 17 00:00:00 2001
From: Goetz Gaycken <goetz.gaycken@cern.ch>
Date: Thu, 2 Apr 2020 16:38:23 +0200
Subject: [PATCH 04/26] Migrate EventInfoBSErrDecorator to data handles.

---
 .../EventInfoBSErrDecorator.h                 | 15 ++++++++-----
 .../src/EventInfoBSErrDecorator.cxx           | 22 ++++++-------------
 2 files changed, 16 insertions(+), 21 deletions(-)

diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/EventInfoBSErrDecorator.h b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/EventInfoBSErrDecorator.h
index 9323582e1d22..db70d8a2d424 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/EventInfoBSErrDecorator.h
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/EventInfoBSErrDecorator.h
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
+  Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 */
 
 ///////////////////////////////////////////////////////////////////
@@ -19,6 +19,7 @@
 
 #include "xAODEventInfo/EventInfo.h"
 #include "xAODEventInfo/EventAuxInfo.h"
+#include "StoreGate/ReadHandleKey.h"
 
 #include "SCT_ConditionsTools/ISCT_ByteStreamErrorsTool.h"
 #include "SCT_Cabling/ISCT_CablingTool.h"
@@ -38,11 +39,13 @@ namespace DerivationFramework {
       virtual StatusCode addBranches() const;
 
     private:
-    
-      std::string m_sgName;
-      std::string m_containerName;
-    
-      const SCT_ID*          m_sctId;
+
+      Gaudi::Property<std::string> m_sgName
+         { this,"DecorationPrefix", "", "" };
+      SG::ReadHandleKey<xAOD::EventInfo> m_eventInfoKey
+         { this, "ContainerName", "EventInfo", ""};
+
+      const SCT_ID*          m_sctId = nullptr;
 
       ToolHandle<ISCT_ByteStreamErrorsTool> m_byteStreamErrTool{this, "ByteStreamErrTool", "SCT_ByteStreamErrorsTool", "Tool to retrieve SCT ByteStream Errors"};
       ToolHandle<ISCT_CablingTool> m_cabling{this, "SCT_CablingTool", "SCT_CablingTool", "Tool to retrieve SCT Cabling"};
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/EventInfoBSErrDecorator.cxx b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/EventInfoBSErrDecorator.cxx
index c4623164ab38..c7d8ffca6383 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/EventInfoBSErrDecorator.cxx
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/EventInfoBSErrDecorator.cxx
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
+  Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 */
 
 ///////////////////////////////////////////////////////////////////
@@ -20,15 +20,10 @@ namespace DerivationFramework {
 
   EventInfoBSErrDecorator::EventInfoBSErrDecorator(const std::string& type,
       const std::string& name,
-      const IInterface* parent) : 
-    AthAlgTool(type,name,parent),  
-    m_sgName(""),
-    m_containerName(""),
-    m_sctId(0)  
+      const IInterface* parent) :
+    AthAlgTool(type,name,parent)
   {
     declareInterface<DerivationFramework::IAugmentationTool>(this);
-    declareProperty("DecorationPrefix",       m_sgName);
-    declareProperty("ContainerName",          m_containerName="EventInfo");
   }
 
   StatusCode EventInfoBSErrDecorator::initialize()
@@ -37,11 +32,8 @@ namespace DerivationFramework {
     if (m_sgName=="") {
       ATH_MSG_WARNING("No decoration prefix name provided for the output of EventInfoBSErrDecorator!");
     }
-    
-    if (m_containerName=="") {
-      ATH_MSG_ERROR("No TrackParticle collection provided for EventInfoBSErrDecorator!");
-      return StatusCode::FAILURE;
-    }
+
+    ATH_CHECK(m_eventInfoKey.initialize() );
 
     // need Atlas id-helpers to identify sub-detectors, take them from detStore
     if( detStore()->retrieve(m_sctId,"SCT_ID").isFailure() ){
@@ -64,8 +56,8 @@ namespace DerivationFramework {
   {
     ATH_MSG_DEBUG("Adding ByteStream errors to EventInfo");
 
-    const xAOD::EventInfo* eventInfo;
-    CHECK( evtStore()->retrieve( eventInfo, m_containerName ) );
+    SG::ReadHandle<xAOD::EventInfo> eventInfo(m_eventInfoKey);
+    CHECK( eventInfo.isValid() ? StatusCode::SUCCESS : StatusCode::FAILURE );
 
     std::vector<int> scterr_Ntot;
     std::vector<int> scterr_bec;
-- 
GitLab


From 283eb3d4faf849d2062666f7ae77fd48492108d8 Mon Sep 17 00:00:00 2001
From: Goetz Gaycken <goetz.gaycken@cern.ch>
Date: Thu, 2 Apr 2020 17:12:01 +0200
Subject: [PATCH 05/26] Converted end-of-line from Dos to unix in the
 EventInfoPixelDecorator.

---
 .../src/EventInfoPixelDecorator.cxx           | 350 +++++++++---------
 1 file changed, 175 insertions(+), 175 deletions(-)

diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/EventInfoPixelDecorator.cxx b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/EventInfoPixelDecorator.cxx
index a6934eadad39..6402dc6b90a1 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/EventInfoPixelDecorator.cxx
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/EventInfoPixelDecorator.cxx
@@ -1,178 +1,178 @@
 /*
-  Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
+  Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 */
 
-/////////////////////////////////////////////////////////////////
-// EventInfoPixelDecorator.cxx, (c) ATLAS Detector software
-///////////////////////////////////////////////////////////////////
-// Author: David Salek (David.Salek@cern.ch)
-// Decorator tool to store per-module summary information for pixel clusters
-
-#include "DerivationFrameworkInDet/EventInfoPixelDecorator.h"
-#include "AthenaBaseComps/AthMsgStreamMacros.h"
-#include "ExpressionEvaluation/ExpressionParser.h"
-#include "ExpressionEvaluation/SGxAODProxyLoader.h"
-#include "ExpressionEvaluation/SGNTUPProxyLoader.h"
-#include "ExpressionEvaluation/MultipleProxyLoader.h"
-#include "xAODTracking/TrackMeasurementValidationContainer.h"
-#include "xAODEventInfo/EventInfo.h"
-#include "xAODEventInfo/EventAuxInfo.h"
-#include <vector>
-#include <string>
-
-namespace DerivationFramework {
-
-  EventInfoPixelDecorator::EventInfoPixelDecorator(const std::string& type,
-      const std::string& name,
-      const IInterface* parent) : 
-    AthAlgTool(type,name,parent),  
-    m_parser(0),
-    m_selectionString(""),
-    m_ntot(0),
-    m_npass(0),
-    m_eventInfoKey(""),
-    m_decorationPrefix(""),
-    m_pixelKey("")
-  {
-    declareInterface<DerivationFramework::IAugmentationTool>(this);
-    declareProperty("DecorationPrefix",       m_decorationPrefix);
-    declareProperty("EventInfoKey",           m_eventInfoKey="EventInfo");
-    declareProperty("SelectionString", m_selectionString);
-    declareProperty("TrackMeasurementValidationKey", m_pixelKey="PixelClusters");
-  }
-
-  StatusCode EventInfoPixelDecorator::initialize()
-  {
-    ATH_MSG_VERBOSE("initialize() ...");
-
-    if (m_selectionString=="") {
-        ATH_MSG_FATAL("No inner detector track selection string provided!");
-        return StatusCode::FAILURE;
-    } else {ATH_MSG_INFO("Selection string for the per-module pixel cluster decoration: " << m_selectionString);}
-
-    if (m_decorationPrefix=="") {
-      ATH_MSG_WARNING("No decoration prefix name provided for the output of EventInfoPixelDecorator!");
-    }
-    
-    if (m_eventInfoKey=="") {
-      ATH_MSG_ERROR("No collection provided for EventInfoPixelDecorator!");
-      return StatusCode::FAILURE;
-    }
-
-    //check xAOD::TrackMeasurementValidation collection
-    if (m_pixelKey=="") {
-        ATH_MSG_FATAL("No track measurement validation collection provided for EventInfoPixelDecorator.");
-        return StatusCode::FAILURE;
-    } else {ATH_MSG_INFO("Using " << m_pixelKey << " as the source collection for EventInfoPixelDecorator.");}
-
-    // Set up the text-parsing machinery
-    if (m_selectionString!="") {
-	    ExpressionParsing::MultipleProxyLoader *proxyLoaders = new ExpressionParsing::MultipleProxyLoader();
-	    proxyLoaders->push_back(new ExpressionParsing::SGxAODProxyLoader(evtStore()));
-	    proxyLoaders->push_back(new ExpressionParsing::SGNTUPProxyLoader(evtStore()));
-	    m_parser = new ExpressionParsing::ExpressionParser(proxyLoaders);
-	    m_parser->loadExpression(m_selectionString);
-    }
-
-    return StatusCode::SUCCESS;
-  }
-
-  StatusCode EventInfoPixelDecorator::finalize()
-  {
-    ATH_MSG_VERBOSE("finalize() ...");
-    ATH_MSG_INFO("Processed "<< m_ntot <<" measurements, "<< m_npass<< " were used for the per-module summary");
-    if (m_parser) {
-        delete m_parser;
-        m_parser = 0;
-    }
-    return StatusCode::SUCCESS;
-  }
-
-  StatusCode EventInfoPixelDecorator::addBranches() const
-  {
-    ATH_MSG_DEBUG("Adding per-module information to EventInfo");
-
-    const xAOD::EventInfo* eventInfo;
-    CHECK( evtStore()->retrieve( eventInfo, m_eventInfoKey ) );
-
-    // Get the cluster container
-    const xAOD::TrackMeasurementValidationContainer* clusters;
-    if (evtStore()->retrieve(clusters, m_pixelKey).isFailure()) {
-      ATH_MSG_ERROR ("Couldn't retrieve TrackMeasurementValidationContainer with key" << m_pixelKey);
-      return StatusCode::FAILURE;
-    }
-
-    // Check the event contains clusters
-    unsigned int nClusters = clusters->size();
-    if (nClusters==0) return StatusCode::SUCCESS;
-
-    // Set up a mask with the same entries as the full collection
-    std::vector<bool> mask;
-    mask.assign(nClusters,false); // default: don't keep anything
-    m_ntot += nClusters;
-
-    // Execute the text parser and update the mask
-    if (m_parser) {
-        std::vector<int> entries =  m_parser->evaluateAsVector();
-        unsigned int nEntries = entries.size();
-        // check the sizes are compatible
-        if (nClusters != nEntries ) {
-            ATH_MSG_ERROR("Sizes incompatible! Are you sure your selection string used the same collection as the input collection??");
-            return StatusCode::FAILURE;
-        } else {
-            // set mask
-            for (unsigned int i=0; i<nClusters; ++i) if (entries[i]==1) mask[i]=true;
-        }
-    }
-    // Count the mask
-    for (unsigned int i=0; i<nClusters; ++i) {
-        if (mask[i]) ++m_npass;
-    }
- 
-    // fill the per-module information
-    std::vector<int> perModuleMultiplicity;
-    std::vector<int> layer;
-    std::vector<int> eta_module;
-    std::vector<int> phi_module;
-
-    unsigned int i=0;
-    std::vector<int> keys;
-    for (const xAOD::TrackMeasurementValidation* clusIt : *clusters) {
-
-      if( !mask[++i] ) continue;
-
-      static SG::AuxElement::Accessor<int> acc_layer("layer");
-      int clus_layer = acc_layer(*clusIt);
-      static SG::AuxElement::Accessor<int> acc_eta_module("eta_module");
-      int clus_eta_module = acc_eta_module(*clusIt);
-      static SG::AuxElement::Accessor<int> acc_phi_module("phi_module");
-      int clus_phi_module = acc_phi_module(*clusIt);
-
-      int key = clus_layer * 10000 + clus_eta_module * 100 + clus_phi_module;
-      unsigned int index = 9999;
-      for( unsigned int j = 0; j < keys.size() ; j++ )
-        if( key == keys[j] ){
-          index = j;
-          break;
-        }
-      if( index == 9999 ){
-        keys.push_back( key );
-        layer.push_back( clus_layer );
-        eta_module.push_back( clus_eta_module );
-        phi_module.push_back( clus_phi_module );
-        perModuleMultiplicity.push_back( 1 );
-      } else {
-        perModuleMultiplicity[index]++;
-      }
-    }
-
-    // decorate per-layer multiplicity
-    eventInfo->auxdecor< std::vector<int> >(m_decorationPrefix+"_perModuleMultiplicity") = perModuleMultiplicity;
-    eventInfo->auxdecor< std::vector<int> >(m_decorationPrefix+"_layer")                 = layer;
-    eventInfo->auxdecor< std::vector<int> >(m_decorationPrefix+"_eta_module")            = eta_module;
-    eventInfo->auxdecor< std::vector<int> >(m_decorationPrefix+"_phi_module")            = phi_module;
-    
-    return StatusCode::SUCCESS;
-  }  
-  
-}
+/////////////////////////////////////////////////////////////////
+// EventInfoPixelDecorator.cxx, (c) ATLAS Detector software
+///////////////////////////////////////////////////////////////////
+// Author: David Salek (David.Salek@cern.ch)
+// Decorator tool to store per-module summary information for pixel clusters
+
+#include "DerivationFrameworkInDet/EventInfoPixelDecorator.h"
+#include "AthenaBaseComps/AthMsgStreamMacros.h"
+#include "ExpressionEvaluation/ExpressionParser.h"
+#include "ExpressionEvaluation/SGxAODProxyLoader.h"
+#include "ExpressionEvaluation/SGNTUPProxyLoader.h"
+#include "ExpressionEvaluation/MultipleProxyLoader.h"
+#include "xAODTracking/TrackMeasurementValidationContainer.h"
+#include "xAODEventInfo/EventInfo.h"
+#include "xAODEventInfo/EventAuxInfo.h"
+#include <vector>
+#include <string>
+
+namespace DerivationFramework {
+
+  EventInfoPixelDecorator::EventInfoPixelDecorator(const std::string& type,
+      const std::string& name,
+      const IInterface* parent) : 
+    AthAlgTool(type,name,parent),  
+    m_parser(0),
+    m_selectionString(""),
+    m_ntot(0),
+    m_npass(0),
+    m_eventInfoKey(""),
+    m_decorationPrefix(""),
+    m_pixelKey("")
+  {
+    declareInterface<DerivationFramework::IAugmentationTool>(this);
+    declareProperty("DecorationPrefix",       m_decorationPrefix);
+    declareProperty("EventInfoKey",           m_eventInfoKey="EventInfo");
+    declareProperty("SelectionString", m_selectionString);
+    declareProperty("TrackMeasurementValidationKey", m_pixelKey="PixelClusters");
+  }
+
+  StatusCode EventInfoPixelDecorator::initialize()
+  {
+    ATH_MSG_VERBOSE("initialize() ...");
+
+    if (m_selectionString=="") {
+        ATH_MSG_FATAL("No inner detector track selection string provided!");
+        return StatusCode::FAILURE;
+    } else {ATH_MSG_INFO("Selection string for the per-module pixel cluster decoration: " << m_selectionString);}
+
+    if (m_decorationPrefix=="") {
+      ATH_MSG_WARNING("No decoration prefix name provided for the output of EventInfoPixelDecorator!");
+    }
+    
+    if (m_eventInfoKey=="") {
+      ATH_MSG_ERROR("No collection provided for EventInfoPixelDecorator!");
+      return StatusCode::FAILURE;
+    }
+
+    //check xAOD::TrackMeasurementValidation collection
+    if (m_pixelKey=="") {
+        ATH_MSG_FATAL("No track measurement validation collection provided for EventInfoPixelDecorator.");
+        return StatusCode::FAILURE;
+    } else {ATH_MSG_INFO("Using " << m_pixelKey << " as the source collection for EventInfoPixelDecorator.");}
+
+    // Set up the text-parsing machinery
+    if (m_selectionString!="") {
+	    ExpressionParsing::MultipleProxyLoader *proxyLoaders = new ExpressionParsing::MultipleProxyLoader();
+	    proxyLoaders->push_back(new ExpressionParsing::SGxAODProxyLoader(evtStore()));
+	    proxyLoaders->push_back(new ExpressionParsing::SGNTUPProxyLoader(evtStore()));
+	    m_parser = new ExpressionParsing::ExpressionParser(proxyLoaders);
+	    m_parser->loadExpression(m_selectionString);
+    }
+
+    return StatusCode::SUCCESS;
+  }
+
+  StatusCode EventInfoPixelDecorator::finalize()
+  {
+    ATH_MSG_VERBOSE("finalize() ...");
+    ATH_MSG_INFO("Processed "<< m_ntot <<" measurements, "<< m_npass<< " were used for the per-module summary");
+    if (m_parser) {
+        delete m_parser;
+        m_parser = 0;
+    }
+    return StatusCode::SUCCESS;
+  }
+
+  StatusCode EventInfoPixelDecorator::addBranches() const
+  {
+    ATH_MSG_DEBUG("Adding per-module information to EventInfo");
+
+    const xAOD::EventInfo* eventInfo;
+    CHECK( evtStore()->retrieve( eventInfo, m_eventInfoKey ) );
+
+    // Get the cluster container
+    const xAOD::TrackMeasurementValidationContainer* clusters;
+    if (evtStore()->retrieve(clusters, m_pixelKey).isFailure()) {
+      ATH_MSG_ERROR ("Couldn't retrieve TrackMeasurementValidationContainer with key" << m_pixelKey);
+      return StatusCode::FAILURE;
+    }
+
+    // Check the event contains clusters
+    unsigned int nClusters = clusters->size();
+    if (nClusters==0) return StatusCode::SUCCESS;
+
+    // Set up a mask with the same entries as the full collection
+    std::vector<bool> mask;
+    mask.assign(nClusters,false); // default: don't keep anything
+    m_ntot += nClusters;
+
+    // Execute the text parser and update the mask
+    if (m_parser) {
+        std::vector<int> entries =  m_parser->evaluateAsVector();
+        unsigned int nEntries = entries.size();
+        // check the sizes are compatible
+        if (nClusters != nEntries ) {
+            ATH_MSG_ERROR("Sizes incompatible! Are you sure your selection string used the same collection as the input collection??");
+            return StatusCode::FAILURE;
+        } else {
+            // set mask
+            for (unsigned int i=0; i<nClusters; ++i) if (entries[i]==1) mask[i]=true;
+        }
+    }
+    // Count the mask
+    for (unsigned int i=0; i<nClusters; ++i) {
+        if (mask[i]) ++m_npass;
+    }
+ 
+    // fill the per-module information
+    std::vector<int> perModuleMultiplicity;
+    std::vector<int> layer;
+    std::vector<int> eta_module;
+    std::vector<int> phi_module;
+
+    unsigned int i=0;
+    std::vector<int> keys;
+    for (const xAOD::TrackMeasurementValidation* clusIt : *clusters) {
+
+      if( !mask[++i] ) continue;
+
+      static SG::AuxElement::Accessor<int> acc_layer("layer");
+      int clus_layer = acc_layer(*clusIt);
+      static SG::AuxElement::Accessor<int> acc_eta_module("eta_module");
+      int clus_eta_module = acc_eta_module(*clusIt);
+      static SG::AuxElement::Accessor<int> acc_phi_module("phi_module");
+      int clus_phi_module = acc_phi_module(*clusIt);
+
+      int key = clus_layer * 10000 + clus_eta_module * 100 + clus_phi_module;
+      unsigned int index = 9999;
+      for( unsigned int j = 0; j < keys.size() ; j++ )
+        if( key == keys[j] ){
+          index = j;
+          break;
+        }
+      if( index == 9999 ){
+        keys.push_back( key );
+        layer.push_back( clus_layer );
+        eta_module.push_back( clus_eta_module );
+        phi_module.push_back( clus_phi_module );
+        perModuleMultiplicity.push_back( 1 );
+      } else {
+        perModuleMultiplicity[index]++;
+      }
+    }
+
+    // decorate per-layer multiplicity
+    eventInfo->auxdecor< std::vector<int> >(m_decorationPrefix+"_perModuleMultiplicity") = perModuleMultiplicity;
+    eventInfo->auxdecor< std::vector<int> >(m_decorationPrefix+"_layer")                 = layer;
+    eventInfo->auxdecor< std::vector<int> >(m_decorationPrefix+"_eta_module")            = eta_module;
+    eventInfo->auxdecor< std::vector<int> >(m_decorationPrefix+"_phi_module")            = phi_module;
+    
+    return StatusCode::SUCCESS;
+  }  
+  
+}
-- 
GitLab


From 7114275824564e7a48ed1d4de7e37058e4c2685c Mon Sep 17 00:00:00 2001
From: Goetz Gaycken <goetz.gaycken@cern.ch>
Date: Thu, 2 Apr 2020 17:12:58 +0200
Subject: [PATCH 06/26] Migrate EventInfoPixelDecorator to data handles.

---
 .../EventInfoPixelDecorator.h                 | 34 ++++++------
 .../src/EventInfoPixelDecorator.cxx           | 54 +++++++------------
 2 files changed, 39 insertions(+), 49 deletions(-)

diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/EventInfoPixelDecorator.h b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/EventInfoPixelDecorator.h
index 851d532b61a5..773836a1fed8 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/EventInfoPixelDecorator.h
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/EventInfoPixelDecorator.h
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
+  Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 */
 
 ///////////////////////////////////////////////////////////////////
@@ -16,10 +16,10 @@
 #include "DerivationFrameworkInterfaces/IAugmentationTool.h"
 #include "GaudiKernel/ToolHandle.h"
 #include "GaudiKernel/ServiceHandle.h"
-
-namespace ExpressionParsing {
-  class ExpressionParser;
-}
+#include "StoreGate/ReadHandleKey.h"
+#include "xAODTracking/TrackMeasurementValidationContainer.h"
+#include "xAODEventInfo/EventInfo.h"
+#include "ExpressionEvaluation/ExpressionParser.h"
 
 namespace DerivationFramework {
 
@@ -32,16 +32,20 @@ namespace DerivationFramework {
       virtual StatusCode addBranches() const;
 
     private:
-      std::string m_expression;
-      ExpressionParsing::ExpressionParser *m_parser;
-      std::string m_selectionString;
-
-      mutable unsigned int m_ntot;
-      mutable unsigned int m_npass;
-    
-      std::string m_eventInfoKey;
-      std::string m_decorationPrefix;
-      std::string m_pixelKey;
+      std::unique_ptr<ExpressionParsing::ExpressionParser> m_parser;
+      Gaudi::Property<std::string> m_selectionString
+         { this, "SelectionString", "" , "" };
+
+      mutable std::atomic<unsigned int> m_ntot {};
+      mutable std::atomic<unsigned int> m_npass {};
+
+      SG::ReadHandleKey<xAOD::EventInfo> m_eventInfoKey
+         { this, "EventInfoKey", "EventInfo", ""};
+      Gaudi::Property<std::string> m_decorationPrefix
+         { this, "DecorationPrefix", "", ""};
+     SG::ReadHandleKey<xAOD::TrackMeasurementValidationContainer> m_pixelKey
+         { this, "TrackMeasurementValidationKey", "PixelClusters", ""};
+
   }; 
 }
 
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/EventInfoPixelDecorator.cxx b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/EventInfoPixelDecorator.cxx
index 6402dc6b90a1..d6b034520ede 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/EventInfoPixelDecorator.cxx
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/EventInfoPixelDecorator.cxx
@@ -14,8 +14,6 @@
 #include "ExpressionEvaluation/SGxAODProxyLoader.h"
 #include "ExpressionEvaluation/SGNTUPProxyLoader.h"
 #include "ExpressionEvaluation/MultipleProxyLoader.h"
-#include "xAODTracking/TrackMeasurementValidationContainer.h"
-#include "xAODEventInfo/EventInfo.h"
 #include "xAODEventInfo/EventAuxInfo.h"
 #include <vector>
 #include <string>
@@ -25,52 +23,40 @@ namespace DerivationFramework {
   EventInfoPixelDecorator::EventInfoPixelDecorator(const std::string& type,
       const std::string& name,
       const IInterface* parent) : 
-    AthAlgTool(type,name,parent),  
-    m_parser(0),
-    m_selectionString(""),
-    m_ntot(0),
-    m_npass(0),
-    m_eventInfoKey(""),
-    m_decorationPrefix(""),
-    m_pixelKey("")
+    AthAlgTool(type,name,parent)
   {
     declareInterface<DerivationFramework::IAugmentationTool>(this);
-    declareProperty("DecorationPrefix",       m_decorationPrefix);
-    declareProperty("EventInfoKey",           m_eventInfoKey="EventInfo");
-    declareProperty("SelectionString", m_selectionString);
-    declareProperty("TrackMeasurementValidationKey", m_pixelKey="PixelClusters");
   }
 
   StatusCode EventInfoPixelDecorator::initialize()
   {
     ATH_MSG_VERBOSE("initialize() ...");
 
-    if (m_selectionString=="") {
+    if (m_selectionString.empty()) {
         ATH_MSG_FATAL("No inner detector track selection string provided!");
         return StatusCode::FAILURE;
     } else {ATH_MSG_INFO("Selection string for the per-module pixel cluster decoration: " << m_selectionString);}
 
-    if (m_decorationPrefix=="") {
+    if (m_decorationPrefix.empty()) {
       ATH_MSG_WARNING("No decoration prefix name provided for the output of EventInfoPixelDecorator!");
     }
     
-    if (m_eventInfoKey=="") {
+    if (m_eventInfoKey.key().empty()) {
       ATH_MSG_ERROR("No collection provided for EventInfoPixelDecorator!");
       return StatusCode::FAILURE;
     }
+    ATH_CHECK(m_eventInfoKey.initialize());
 
     //check xAOD::TrackMeasurementValidation collection
-    if (m_pixelKey=="") {
-        ATH_MSG_FATAL("No track measurement validation collection provided for EventInfoPixelDecorator.");
-        return StatusCode::FAILURE;
-    } else {ATH_MSG_INFO("Using " << m_pixelKey << " as the source collection for EventInfoPixelDecorator.");}
+    ATH_CHECK(m_pixelKey.initialize());
+    ATH_MSG_INFO("Using " << m_pixelKey.key() << " as the source collection for EventInfoPixelDecorator.");
 
     // Set up the text-parsing machinery
-    if (m_selectionString!="") {
+    if (!m_selectionString.empty()) {
 	    ExpressionParsing::MultipleProxyLoader *proxyLoaders = new ExpressionParsing::MultipleProxyLoader();
 	    proxyLoaders->push_back(new ExpressionParsing::SGxAODProxyLoader(evtStore()));
 	    proxyLoaders->push_back(new ExpressionParsing::SGNTUPProxyLoader(evtStore()));
-	    m_parser = new ExpressionParsing::ExpressionParser(proxyLoaders);
+	    m_parser = std::make_unique<ExpressionParsing::ExpressionParser>(proxyLoaders);
 	    m_parser->loadExpression(m_selectionString);
     }
 
@@ -81,24 +67,22 @@ namespace DerivationFramework {
   {
     ATH_MSG_VERBOSE("finalize() ...");
     ATH_MSG_INFO("Processed "<< m_ntot <<" measurements, "<< m_npass<< " were used for the per-module summary");
-    if (m_parser) {
-        delete m_parser;
-        m_parser = 0;
-    }
+    m_parser.reset();
     return StatusCode::SUCCESS;
   }
 
   StatusCode EventInfoPixelDecorator::addBranches() const
   {
     ATH_MSG_DEBUG("Adding per-module information to EventInfo");
+    const EventContext& ctx = Gaudi::Hive::currentContext();
 
-    const xAOD::EventInfo* eventInfo;
-    CHECK( evtStore()->retrieve( eventInfo, m_eventInfoKey ) );
+    SG::ReadHandle<xAOD::EventInfo> eventInfo(m_eventInfoKey, ctx);
+    CHECK( eventInfo.isValid() ? StatusCode::SUCCESS : StatusCode::FAILURE);
 
     // Get the cluster container
-    const xAOD::TrackMeasurementValidationContainer* clusters;
-    if (evtStore()->retrieve(clusters, m_pixelKey).isFailure()) {
-      ATH_MSG_ERROR ("Couldn't retrieve TrackMeasurementValidationContainer with key" << m_pixelKey);
+    SG::ReadHandle<xAOD::TrackMeasurementValidationContainer> clusters(m_pixelKey, ctx);
+    if (!clusters.isValid()) {
+       ATH_MSG_ERROR ("Couldn't retrieve TrackMeasurementValidationContainer with key" << m_pixelKey.key());
       return StatusCode::FAILURE;
     }
 
@@ -125,10 +109,12 @@ namespace DerivationFramework {
         }
     }
     // Count the mask
+    unsigned int n_pass=0;
     for (unsigned int i=0; i<nClusters; ++i) {
-        if (mask[i]) ++m_npass;
+        if (mask[i]) ++n_pass;
     }
- 
+    m_npass += n_pass;
+
     // fill the per-module information
     std::vector<int> perModuleMultiplicity;
     std::vector<int> layer;
-- 
GitLab


From b81d317203160ee04ee37e688f9d1c5bf68da7d1 Mon Sep 17 00:00:00 2001
From: Goetz Gaycken <goetz.gaycken@cern.ch>
Date: Thu, 2 Apr 2020 17:52:57 +0200
Subject: [PATCH 07/26] Migrate DerivationFrameworkInDet to data handles.

---
 .../JetTrackParticleThinning.h                |  9 ++++--
 .../src/JetTrackParticleThinning.cxx          | 32 +++++++++----------
 2 files changed, 23 insertions(+), 18 deletions(-)

diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/JetTrackParticleThinning.h b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/JetTrackParticleThinning.h
index ec4b428acca0..5b733ce5949b 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/JetTrackParticleThinning.h
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/JetTrackParticleThinning.h
@@ -16,7 +16,9 @@
 #include "DerivationFrameworkInterfaces/IThinningTool.h"
 #include "GaudiKernel/ToolHandle.h"
 #include "xAODTracking/TrackParticleContainer.h"
+#include "xAODJet/JetContainer.h"
 #include "StoreGate/ThinningHandleKey.h"
+#include "StoreGate/ReadHandleKey.h"
 
 namespace ExpressionParsing {
   class ExpressionParser;
@@ -33,8 +35,11 @@ namespace DerivationFramework {
       virtual StatusCode doThinning() const override;
 
     private:
-      mutable std::atomic<unsigned int> m_ntot, m_npass;
-      std::string m_jetSGKey;
+      mutable std::atomic<unsigned int> m_ntot  {};
+      mutable std::atomic<unsigned int> m_npass {};
+      SG::ReadHandleKey<xAOD::JetContainer> m_jetKey
+        { this, "JetKey", "", ""};
+
       StringProperty m_streamName
         { this, "StreamName", "", "Name of the stream being thinned" };
       SG::ThinningHandleKey<xAOD::TrackParticleContainer> m_inDetSGKey
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/JetTrackParticleThinning.cxx b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/JetTrackParticleThinning.cxx
index d04b0fe77887..44c4e14d9534 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/JetTrackParticleThinning.cxx
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/JetTrackParticleThinning.cxx
@@ -25,12 +25,8 @@
 DerivationFramework::JetTrackParticleThinning::JetTrackParticleThinning(const std::string& t,
                                                                         const std::string& n,
                                                                         const IInterface* p ) :
-base_class(t,n,p),
-m_ntot(0),
-m_npass(0),
-m_jetSGKey("")
+base_class(t,n,p)
 {
-    declareProperty("JetKey", m_jetSGKey);
 }
 
 // Destructor
@@ -44,13 +40,15 @@ StatusCode DerivationFramework::JetTrackParticleThinning::initialize()
     ATH_MSG_VERBOSE("initialize() ...");
     ATH_CHECK( m_inDetSGKey.initialize (m_streamName) );
     ATH_MSG_INFO("Using " << m_inDetSGKey << "as the source collection for inner detector track particles");
-    if (m_jetSGKey=="") {
+    if (m_jetKey.key().empty()) {
         ATH_MSG_FATAL("No jet collection provided for thinning.");
         return StatusCode::FAILURE;
-    } else { ATH_MSG_INFO("Inner detector track particles associated with objects in " << m_jetSGKey << " will be retained in this format with the rest being thinned away");}
-    
+    }
+    ATH_CHECK( m_jetKey.initialize() );
+    ATH_MSG_INFO("Inner detector track particles associated with objects in " << m_jetKey.key() << " will be retained in this format with the rest being thinned away");
+
     // Set up the text-parsing machinery for selectiong the jet directly according to user cuts
-    if (m_selectionString!="") {
+    if (!m_selectionString.empty()) {
 	    ExpressionParsing::MultipleProxyLoader *proxyLoaders = new ExpressionParsing::MultipleProxyLoader();
 	    proxyLoaders->push_back(new ExpressionParsing::SGxAODProxyLoader(evtStore()));
 	    proxyLoaders->push_back(new ExpressionParsing::SGNTUPProxyLoader(evtStore()));
@@ -58,7 +56,7 @@ StatusCode DerivationFramework::JetTrackParticleThinning::initialize()
 	    m_parser->loadExpression(m_selectionString);
     }
 
-    if (m_trackSelectionString!="") {
+    if (m_trackSelectionString.empty()) {
 	    ExpressionParsing::MultipleProxyLoader *proxyLoaders = new ExpressionParsing::MultipleProxyLoader();
 	    proxyLoaders->push_back(new ExpressionParsing::SGxAODProxyLoader(evtStore()));
 	    proxyLoaders->push_back(new ExpressionParsing::SGNTUPProxyLoader(evtStore()));
@@ -95,16 +93,16 @@ StatusCode DerivationFramework::JetTrackParticleThinning::doThinning() const
     
     // Retrieve containers
     // ... jets
-    const xAOD::JetContainer* importedJets(0);
-    if (evtStore()->retrieve(importedJets,m_jetSGKey).isFailure()) {
-        ATH_MSG_ERROR("No jet collection with name " << m_jetSGKey << " found in StoreGate!");
+    SG::ReadHandle<xAOD::JetContainer> importedJets(m_jetKey,ctx);
+    if (!importedJets.isValid()) {
+        ATH_MSG_ERROR("No jet collection with name " << m_jetKey.key() << " found in StoreGate!");
         return StatusCode::FAILURE;
     }
     unsigned int nJets(importedJets->size());
     std::vector<const xAOD::Jet*> jetToCheck; jetToCheck.clear();
     
     // Execute the text parser if requested
-    if (m_selectionString!="") {
+    if (!m_selectionString.empty()) {
         std::vector<int> entries =  m_parser->evaluateAsVector();
         unsigned int nEntries = entries.size();
         // check the sizes are compatible
@@ -119,7 +117,7 @@ StatusCode DerivationFramework::JetTrackParticleThinning::doThinning() const
     
     // Set elements in the mask to true if there is a corresponding ElementLink from a reconstructed object
     // ... jets
-    if (m_selectionString=="") { // check all jets as user didn't provide a selection string
+    if (m_selectionString.empty()) { // check all jets as user didn't provide a selection string
         for (xAOD::JetContainer::const_iterator jetIt=importedJets->begin(); jetIt!=importedJets->end(); ++jetIt) {
             std::vector<const xAOD::TrackParticle*> jetTracks;
             bool haveJetTracks = (*jetIt)->getAssociatedObjects(xAOD::JetAttribute::GhostTrack, jetTracks);
@@ -162,9 +160,11 @@ StatusCode DerivationFramework::JetTrackParticleThinning::doThinning() const
     }
     
     // Count up the mask contents
+    unsigned int n_pass=0;
     for (unsigned int i=0; i<nTracks; ++i) {
-        if (mask[i]) ++m_npass;
+        if (mask[i]) ++n_pass;
     }
+    m_npass += n_pass;
     
     // Execute the thinning service based on the mask. Finish.
     importedTrackParticles.keep (mask);
-- 
GitLab


From 6061121d2ad221288362fabb060cf8b929c8a443 Mon Sep 17 00:00:00 2001
From: Goetz Gaycken <goetz.gaycken@cern.ch>
Date: Thu, 2 Apr 2020 18:44:54 +0200
Subject: [PATCH 08/26] Converted end-of-line from Dos to unix in the
 LArCollisionTimeDecorator.

---
 .../src/LArCollisionTimeDecorator.cxx         | 154 +++++++++---------
 1 file changed, 77 insertions(+), 77 deletions(-)

diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/LArCollisionTimeDecorator.cxx b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/LArCollisionTimeDecorator.cxx
index 2739e4d0ac9d..b79f71c4e031 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/LArCollisionTimeDecorator.cxx
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/LArCollisionTimeDecorator.cxx
@@ -1,80 +1,80 @@
 /*
-  Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
+  Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 */
 
-///////////////////////////////////////////////////////////////////
-// LArCollisionTimeDecorator.cxx, (c) ATLAS Detector software
-///////////////////////////////////////////////////////////////////
-// Author: Olivier Arnaez ( olivier.arnaez@cern.ch )
-
-#include "DerivationFrameworkInDet/LArCollisionTimeDecorator.h"
-#include "AthenaBaseComps/AthMsgStreamMacros.h"
-
-#include "LArRecEvent/LArCollisionTime.h"
-
-
-#include <vector>
-#include <utility>
-#include <string>
-
-namespace DerivationFramework {
-
-  LArCollisionTimeDecorator::LArCollisionTimeDecorator(const std::string& type,
-      const std::string& name,
-      const IInterface* parent) : 
-    AthAlgTool(type,name,parent),  
-    m_sgName(""),
-    m_containerName("")
-  {
-    declareInterface<DerivationFramework::IAugmentationTool>(this);
-    declareProperty("DecorationPrefix",       m_sgName);
-    declareProperty("ContainerName",          m_containerName="EventInfo");
-  }
-
-  StatusCode LArCollisionTimeDecorator::initialize()
-  {
-
-    if (m_sgName=="") {
-      ATH_MSG_WARNING("No decoration prefix name provided for the output of LArCollisionTimeDecorator!");
-    }
-    
-    if (m_containerName=="") {
-      ATH_MSG_ERROR("No EventInfo collection provided for LArCollisionTimeDecorator!");
-      return StatusCode::FAILURE;
-    }
-
-    return StatusCode::SUCCESS;
-  }
-
-  StatusCode LArCollisionTimeDecorator::finalize()
-  {
-    return StatusCode::SUCCESS;
-  }
-
-  StatusCode LArCollisionTimeDecorator::addBranches() const
-  {
-    ATH_MSG_DEBUG("Adding LAr time info to EventInfo");
-
-    const xAOD::EventInfo* eventInfo;
-    CHECK( evtStore()->retrieve( eventInfo, m_containerName ) );
-
-    const  LArCollisionTime* tps;
-    CHECK( evtStore()->retrieve(tps,"LArCollisionTime") );
-    
-    if (tps) {
-      eventInfo->auxdecor< int >(m_sgName+"ncellA")     = tps->ncellA();
-      eventInfo->auxdecor< int >(m_sgName+"ncellC")     = tps->ncellC();
-      eventInfo->auxdecor< float >(m_sgName+"energyA")  = tps->energyA();
-      eventInfo->auxdecor< float >(m_sgName+"energyC")  = tps->energyC();
-      eventInfo->auxdecor< float >(m_sgName+"timeA")    = tps->timeA();
-      eventInfo->auxdecor< float >(m_sgName+"timeC")    = tps->timeC();
-      float LArECtimeDiff =   tps->timeA()-tps->timeC();
-      ATH_MSG_DEBUG("Decorating LAr time info, LArECTimeDiff = " << LArECtimeDiff);
-    }
-    else
-      ATH_MSG_WARNING("Missing LArCollisionTime information.");
-    
-    return StatusCode::SUCCESS;
-  }  
-  
-}
+///////////////////////////////////////////////////////////////////
+// LArCollisionTimeDecorator.cxx, (c) ATLAS Detector software
+///////////////////////////////////////////////////////////////////
+// Author: Olivier Arnaez ( olivier.arnaez@cern.ch )
+
+#include "DerivationFrameworkInDet/LArCollisionTimeDecorator.h"
+#include "AthenaBaseComps/AthMsgStreamMacros.h"
+
+#include "LArRecEvent/LArCollisionTime.h"
+
+
+#include <vector>
+#include <utility>
+#include <string>
+
+namespace DerivationFramework {
+
+  LArCollisionTimeDecorator::LArCollisionTimeDecorator(const std::string& type,
+      const std::string& name,
+      const IInterface* parent) : 
+    AthAlgTool(type,name,parent),  
+    m_sgName(""),
+    m_containerName("")
+  {
+    declareInterface<DerivationFramework::IAugmentationTool>(this);
+    declareProperty("DecorationPrefix",       m_sgName);
+    declareProperty("ContainerName",          m_containerName="EventInfo");
+  }
+
+  StatusCode LArCollisionTimeDecorator::initialize()
+  {
+
+    if (m_sgName=="") {
+      ATH_MSG_WARNING("No decoration prefix name provided for the output of LArCollisionTimeDecorator!");
+    }
+    
+    if (m_containerName=="") {
+      ATH_MSG_ERROR("No EventInfo collection provided for LArCollisionTimeDecorator!");
+      return StatusCode::FAILURE;
+    }
+
+    return StatusCode::SUCCESS;
+  }
+
+  StatusCode LArCollisionTimeDecorator::finalize()
+  {
+    return StatusCode::SUCCESS;
+  }
+
+  StatusCode LArCollisionTimeDecorator::addBranches() const
+  {
+    ATH_MSG_DEBUG("Adding LAr time info to EventInfo");
+
+    const xAOD::EventInfo* eventInfo;
+    CHECK( evtStore()->retrieve( eventInfo, m_containerName ) );
+
+    const  LArCollisionTime* tps;
+    CHECK( evtStore()->retrieve(tps,"LArCollisionTime") );
+    
+    if (tps) {
+      eventInfo->auxdecor< int >(m_sgName+"ncellA")     = tps->ncellA();
+      eventInfo->auxdecor< int >(m_sgName+"ncellC")     = tps->ncellC();
+      eventInfo->auxdecor< float >(m_sgName+"energyA")  = tps->energyA();
+      eventInfo->auxdecor< float >(m_sgName+"energyC")  = tps->energyC();
+      eventInfo->auxdecor< float >(m_sgName+"timeA")    = tps->timeA();
+      eventInfo->auxdecor< float >(m_sgName+"timeC")    = tps->timeC();
+      float LArECtimeDiff =   tps->timeA()-tps->timeC();
+      ATH_MSG_DEBUG("Decorating LAr time info, LArECTimeDiff = " << LArECtimeDiff);
+    }
+    else
+      ATH_MSG_WARNING("Missing LArCollisionTime information.");
+    
+    return StatusCode::SUCCESS;
+  }  
+  
+}
-- 
GitLab


From 17b7f3ccd256125bacce208ffe410b5d5922a989 Mon Sep 17 00:00:00 2001
From: Goetz Gaycken <goetz.gaycken@cern.ch>
Date: Fri, 3 Apr 2020 12:07:22 +0200
Subject: [PATCH 09/26] Added decorator handle utilities.

---
 .../DerivationFrameworkInDet/DecoratorUtils.h | 68 +++++++++++++++++++
 1 file changed, 68 insertions(+)
 create mode 100644 PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/DecoratorUtils.h

diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/DecoratorUtils.h b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/DecoratorUtils.h
new file mode 100644
index 000000000000..a9c3ea3800e0
--- /dev/null
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/DecoratorUtils.h
@@ -0,0 +1,68 @@
+/*
+  Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
+*/
+#ifndef _DecoratorUtils_H_
+#define _DecoratorUtils_H_
+#include "StoreGate/ReadHandleKey.h"
+#include "StoreGate/WriteDecorHandleKey.h"
+#include "StoreGate/WriteDecorHandle.h"
+
+#include <string>
+#include <vector>
+#include <stdexcept>
+#include <sstream>
+
+namespace DerivationFramework {
+  // @TODO copied from  InnerDetector/InDetValidation/InDetPhysValMonitoring/src/safeDecorator.h, maybe move to a central place ?
+
+  // convenience method to create several decorators
+  template<class T_Parent, class T_Cont>
+  void createDecoratorKeys(T_Parent &parent,
+                        const SG::ReadHandleKey<T_Cont> &container_key,
+                        const std::string &prefix,
+                        const std::vector<std::string> &decor_names,
+                        std::vector<SG::WriteDecorHandleKey<T_Cont> > &decor_out) {
+    decor_out.clear();
+    decor_out.reserve(decor_names.size());
+    for (const std::string &a_decor_name : decor_names) {
+      assert( !a_decor_name.empty() );
+      decor_out.push_back(SG::WriteDecorHandleKey<T_Cont>(container_key.key()+"."+prefix+a_decor_name) );
+    }
+
+    for (SG::WriteDecorHandleKey<T_Cont> &a_decor_handle_key : decor_out) {
+      // need to declare handles, otherwise the scheduler would not pick up the data dependencies
+      // introduced by the decorations
+      parent.declare(a_decor_handle_key);
+      a_decor_handle_key.setOwner(&parent);
+      if (a_decor_handle_key.initialize().isFailure()) {
+         std::stringstream msg;
+         msg << "Failed to initialize " << a_decor_handle_key.key() << " after initializing: ";
+         for (SG::WriteDecorHandleKey<T_Cont> &b_decor_handle_key : decor_out) {
+            if (&b_decor_handle_key == &a_decor_handle_key) break;
+            msg << " " << b_decor_handle_key.key();
+         }
+         throw std::runtime_error(msg.str());
+      }
+    }
+  }
+
+  template <class T_Cont, class T>
+  std::vector<SG::WriteDecorHandle<T_Cont,T> >
+  createDecorators(  const std::vector<SG::WriteDecorHandleKey<T_Cont> > &keys,
+                     const EventContext &ctx) {
+    std::vector<SG::WriteDecorHandle<T_Cont,T> > out;
+    out.reserve(keys.size());
+    for( const SG::WriteDecorHandleKey<T_Cont> &a_key : keys) {
+      out.push_back(SG::WriteDecorHandle<T_Cont,T>(a_key,ctx));
+      if (not out.back().isValid()) {
+        std::stringstream msg;
+        msg << "Failed to create decorator handdle " << a_key.key();
+        throw std::runtime_error( msg.str() );
+      }
+    }
+    return out;
+  }
+
+
+}
+#endif
-- 
GitLab


From 756bcd540837b701b11ad3539de4b8ed7d49b266 Mon Sep 17 00:00:00 2001
From: Goetz Gaycken <goetz.gaycken@cern.ch>
Date: Fri, 3 Apr 2020 12:09:53 +0200
Subject: [PATCH 10/26] Migrate LArCollisionTimeDecorator to data handles.

---
 .../LArCollisionTimeDecorator.h               | 28 ++++++--
 .../src/LArCollisionTimeDecorator.cxx         | 68 ++++++++++++-------
 2 files changed, 64 insertions(+), 32 deletions(-)

diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/LArCollisionTimeDecorator.h b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/LArCollisionTimeDecorator.h
index 9a02c5506ded..779d3449ec44 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/LArCollisionTimeDecorator.h
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/LArCollisionTimeDecorator.h
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
+  Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 */
 
 ///////////////////////////////////////////////////////////////////
@@ -18,13 +18,17 @@
 #include "GaudiKernel/ServiceHandle.h"
 #include "AthLinks/ElementLink.h"
 
+#include "StoreGate/ReadHandleKey.h"
+#include "StoreGate/WriteDecorHandleKey.h"
+
 #include "xAODEventInfo/EventInfo.h"
 #include "xAODEventInfo/EventAuxInfo.h"
+#include "LArRecEvent/LArCollisionTime.h"
 
 namespace DerivationFramework {
 
   class LArCollisionTimeDecorator : public AthAlgTool, public IAugmentationTool {
-    public: 
+    public:
       LArCollisionTimeDecorator(const std::string& type, const std::string& name, const IInterface* parent);
 
       StatusCode initialize();
@@ -32,11 +36,21 @@ namespace DerivationFramework {
       virtual StatusCode addBranches() const;
 
     private:
-    
-      std::string m_sgName;
-      std::string m_containerName;
-    
-  }; 
+
+      Gaudi::Property<std::string> m_sgName
+        { this, "DecorationPrefix", "", ""};
+      SG::ReadHandleKey<xAOD::EventInfo> m_eventInfoKey
+        { this, "ContainerName", "EventInfo", "" };
+      SG::ReadHandleKey<LArCollisionTime> m_larCollisionTimeKey
+        { this, "LArCollisionTimeKey", "LArCollisionTime", ""};
+
+      enum EIntDecor   {kncellA, kncellC, kNIntDecor };
+      enum EFloatDecor {kenergyA,kenergyC,ktimeA,ktimeC, kNFloatDecor };
+
+      std::vector<SG::WriteDecorHandleKey<xAOD::EventInfo> > m_intDecorKeys;
+      std::vector<SG::WriteDecorHandleKey<xAOD::EventInfo> > m_floatDecorKeys;
+
+  };
 }
 
 #endif // DERIVATIONFRAMEWORK_LARCOLLISIONTIMEDECORATOR_H
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/LArCollisionTimeDecorator.cxx b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/LArCollisionTimeDecorator.cxx
index b79f71c4e031..d3b6de25b760 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/LArCollisionTimeDecorator.cxx
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/LArCollisionTimeDecorator.cxx
@@ -8,10 +8,9 @@
 // Author: Olivier Arnaez ( olivier.arnaez@cern.ch )
 
 #include "DerivationFrameworkInDet/LArCollisionTimeDecorator.h"
+#include "DerivationFrameworkInDet/DecoratorUtils.h"
 #include "AthenaBaseComps/AthMsgStreamMacros.h"
-
-#include "LArRecEvent/LArCollisionTime.h"
-
+#include "StoreGate/WriteDecorHandle.h"
 
 #include <vector>
 #include <utility>
@@ -21,27 +20,42 @@ namespace DerivationFramework {
 
   LArCollisionTimeDecorator::LArCollisionTimeDecorator(const std::string& type,
       const std::string& name,
-      const IInterface* parent) : 
-    AthAlgTool(type,name,parent),  
-    m_sgName(""),
-    m_containerName("")
+      const IInterface* parent) :
+    AthAlgTool(type,name,parent)
   {
     declareInterface<DerivationFramework::IAugmentationTool>(this);
-    declareProperty("DecorationPrefix",       m_sgName);
-    declareProperty("ContainerName",          m_containerName="EventInfo");
   }
 
   StatusCode LArCollisionTimeDecorator::initialize()
   {
 
-    if (m_sgName=="") {
+    if (m_sgName.empty()) {
       ATH_MSG_WARNING("No decoration prefix name provided for the output of LArCollisionTimeDecorator!");
     }
     
-    if (m_containerName=="") {
+    if (m_eventInfoKey.key().empty()) {
       ATH_MSG_ERROR("No EventInfo collection provided for LArCollisionTimeDecorator!");
       return StatusCode::FAILURE;
     }
+    ATH_CHECK(m_eventInfoKey.initialize() );
+    ATH_CHECK(m_larCollisionTimeKey.initialize() );
+    {
+       std::vector<std::string> names;
+       names.resize(kNIntDecor);
+       names[kncellA]="ncellA";
+       names[kncellC]="ncellC";
+       createDecoratorKeys(*this,m_eventInfoKey,"" /* common prefix */,names, m_intDecorKeys);
+    }
+
+    {
+       std::vector<std::string> names;
+       names.resize(kNFloatDecor);
+       names[kenergyA] = "energyA";
+       names[kenergyC] = "energyC";
+       names[ktimeA]   = "timeA";
+       names[ktimeC]   = "timeC";
+       createDecoratorKeys(*this,m_eventInfoKey,"" /* common prefix */,names, m_floatDecorKeys);
+    }
 
     return StatusCode::SUCCESS;
   }
@@ -54,26 +68,30 @@ namespace DerivationFramework {
   StatusCode LArCollisionTimeDecorator::addBranches() const
   {
     ATH_MSG_DEBUG("Adding LAr time info to EventInfo");
+    const EventContext& ctx = Gaudi::Hive::currentContext();
+    SG::ReadHandle<xAOD::EventInfo> eventInfo(m_eventInfoKey,ctx);
+    CHECK( eventInfo.isValid() ? StatusCode::SUCCESS : StatusCode::FAILURE);
 
-    const xAOD::EventInfo* eventInfo;
-    CHECK( evtStore()->retrieve( eventInfo, m_containerName ) );
+    SG::ReadHandle<LArCollisionTime> tps(m_larCollisionTimeKey,ctx);
 
-    const  LArCollisionTime* tps;
-    CHECK( evtStore()->retrieve(tps,"LArCollisionTime") );
-    
-    if (tps) {
-      eventInfo->auxdecor< int >(m_sgName+"ncellA")     = tps->ncellA();
-      eventInfo->auxdecor< int >(m_sgName+"ncellC")     = tps->ncellC();
-      eventInfo->auxdecor< float >(m_sgName+"energyA")  = tps->energyA();
-      eventInfo->auxdecor< float >(m_sgName+"energyC")  = tps->energyC();
-      eventInfo->auxdecor< float >(m_sgName+"timeA")    = tps->timeA();
-      eventInfo->auxdecor< float >(m_sgName+"timeC")    = tps->timeC();
+    std::vector<SG::WriteDecorHandle<xAOD::EventInfo,int> >   int_decor_handles(createDecorators<xAOD::EventInfo,int>(m_intDecorKeys,ctx));
+    std::vector<SG::WriteDecorHandle<xAOD::EventInfo,float> > float_decor_handles(createDecorators<xAOD::EventInfo,float>(m_floatDecorKeys,ctx));
+    assert( int_decor_handles.size() == kNIntDecor);
+    assert( float_decor_handles.size() == kNFloatDecor);
+    if (tps.isValid()) {
+      int_decor_handles[kncellA](*eventInfo) = tps->ncellA();
+      int_decor_handles[kncellC](*eventInfo)  = tps->ncellC();
+      float_decor_handles[kenergyA](*eventInfo)  = tps->energyA();
+      float_decor_handles[kenergyC](*eventInfo)  = tps->energyC();
+      float_decor_handles[ktimeA](*eventInfo)  = tps->timeA();
+      float_decor_handles[ktimeC](*eventInfo)  = tps->timeC();
       float LArECtimeDiff =   tps->timeA()-tps->timeC();
       ATH_MSG_DEBUG("Decorating LAr time info, LArECTimeDiff = " << LArECtimeDiff);
     }
-    else
+    else {
       ATH_MSG_WARNING("Missing LArCollisionTime information.");
-    
+    }
+
     return StatusCode::SUCCESS;
   }  
   
-- 
GitLab


From 13f5c4295b46c5cb7abd804e5d14ae55ec54fbcb Mon Sep 17 00:00:00 2001
From: Goetz Gaycken <goetz.gaycken@cern.ch>
Date: Fri, 3 Apr 2020 20:15:53 +0200
Subject: [PATCH 11/26] Migrate EventInfoBSErrDecorator to decorator handles.

---
 .../EventInfoBSErrDecorator.h                 | 17 ++++-
 .../src/EventInfoBSErrDecorator.cxx           | 65 ++++++++++---------
 2 files changed, 49 insertions(+), 33 deletions(-)

diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/EventInfoBSErrDecorator.h b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/EventInfoBSErrDecorator.h
index db70d8a2d424..2c7eecbf37fa 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/EventInfoBSErrDecorator.h
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/EventInfoBSErrDecorator.h
@@ -40,7 +40,7 @@ namespace DerivationFramework {
 
     private:
 
-      Gaudi::Property<std::string> m_sgName
+      Gaudi::Property<std::string> m_prefix
          { this,"DecorationPrefix", "", "" };
       SG::ReadHandleKey<xAOD::EventInfo> m_eventInfoKey
          { this, "ContainerName", "EventInfo", ""};
@@ -50,7 +50,20 @@ namespace DerivationFramework {
       ToolHandle<ISCT_ByteStreamErrorsTool> m_byteStreamErrTool{this, "ByteStreamErrTool", "SCT_ByteStreamErrorsTool", "Tool to retrieve SCT ByteStream Errors"};
       ToolHandle<ISCT_CablingTool> m_cabling{this, "SCT_CablingTool", "SCT_CablingTool", "Tool to retrieve SCT Cabling"};
 
-  }; 
+      enum EIntDecor {kSCT_BSErr_Ntot,
+                      kSCT_BSErr_bec,
+                      kSCT_BSErr_layer,
+                      kSCT_BSErr_eta,
+                      kSCT_BSErr_phi,
+                      kSCT_BSErr_side,
+                      kSCT_BSErr_rodid,
+                      kSCT_BSErr_channel,
+                      kSCT_BSErr_type,
+                      kNIntDecor};
+
+      std::vector<SG::WriteDecorHandleKey<xAOD::EventInfo> > m_intDecorKeys;
+
+  };
 }
 
 #endif // DERIVATIONFRAMEWORK_EVENTINFOBSERRDECORATOR_H
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/EventInfoBSErrDecorator.cxx b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/EventInfoBSErrDecorator.cxx
index c7d8ffca6383..acf9409dbcc2 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/EventInfoBSErrDecorator.cxx
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/EventInfoBSErrDecorator.cxx
@@ -8,6 +8,7 @@
 // Author: Daiki Hayakawa ( daiki.hayakawa@cern.ch )
 
 #include "DerivationFrameworkInDet/EventInfoBSErrDecorator.h"
+#include "DerivationFrameworkInDet/DecoratorUtils.h"
 #include "AthenaBaseComps/AthMsgStreamMacros.h"
 
 #include "InDetIdentifier/SCT_ID.h"
@@ -29,7 +30,7 @@ namespace DerivationFramework {
   StatusCode EventInfoBSErrDecorator::initialize()
   {
 
-    if (m_sgName=="") {
+    if (m_prefix.empty()) {
       ATH_MSG_WARNING("No decoration prefix name provided for the output of EventInfoBSErrDecorator!");
     }
 
@@ -44,6 +45,21 @@ namespace DerivationFramework {
     CHECK ( m_byteStreamErrTool.retrieve() );
     CHECK ( m_cabling.retrieve() );
 
+    {
+       std::vector<std::string> names;
+       names.resize(kNIntDecor);
+       names[kSCT_BSErr_Ntot]    ="SCT_BSErr_Ntot";
+       names[kSCT_BSErr_bec]     ="SCT_BSErr_bec";
+       names[kSCT_BSErr_layer]   ="SCT_BSErr_layer";
+       names[kSCT_BSErr_eta]     ="SCT_BSErr_eta";
+       names[kSCT_BSErr_phi]     ="SCT_BSErr_phi";
+       names[kSCT_BSErr_side]    ="SCT_BSErr_side";
+       names[kSCT_BSErr_rodid]   ="SCT_BSErr_rodid";
+       names[kSCT_BSErr_channel] ="SCT_BSErr_channel";
+       names[kSCT_BSErr_type]    ="SCT_BSErr_type";
+       createDecoratorKeys(*this,m_eventInfoKey,m_prefix.value()+"_",names, m_intDecorKeys);
+    }
+
     return StatusCode::SUCCESS;
   }
 
@@ -56,18 +72,11 @@ namespace DerivationFramework {
   {
     ATH_MSG_DEBUG("Adding ByteStream errors to EventInfo");
 
-    SG::ReadHandle<xAOD::EventInfo> eventInfo(m_eventInfoKey);
+    const EventContext& ctx = Gaudi::Hive::currentContext();
+    SG::ReadHandle<xAOD::EventInfo> eventInfo(m_eventInfoKey,ctx);
     CHECK( eventInfo.isValid() ? StatusCode::SUCCESS : StatusCode::FAILURE );
 
-    std::vector<int> scterr_Ntot;
-    std::vector<int> scterr_bec;
-    std::vector<int> scterr_layer;
-    std::vector<int> scterr_eta;
-    std::vector<int> scterr_phi;
-    std::vector<int> scterr_side;
-    std::vector<int> scterr_rodid;
-    std::vector<int> scterr_channel;
-    std::vector<int> scterr_type;
+    std::array<std::vector<int>,kNIntDecor> scterr;
     int totalNumErrors=0;
 
     // fill BS error information
@@ -76,7 +85,7 @@ namespace DerivationFramework {
       int eta=0,phi=0,bec=0,layer=0,side=0;
       // add totalNumErrors to vector
       totalNumErrors += errorSet.size();
-      scterr_Ntot.push_back(totalNumErrors);
+      scterr[kSCT_BSErr_Ntot].push_back(totalNumErrors);
 
       // loop in errorSet
       for(const auto error : errorSet) {
@@ -91,34 +100,28 @@ namespace DerivationFramework {
         bec = m_sctId->barrel_ec(itId);
 
         // add variables to vector
-        scterr_bec.push_back(bec);
-        scterr_layer.push_back(layer);
-        scterr_eta.push_back(eta);
-        scterr_phi.push_back(phi);
-        scterr_side.push_back(side);
-        scterr_type.push_back(n_type);
+        scterr[kSCT_BSErr_bec].push_back(bec);
+        scterr[kSCT_BSErr_layer].push_back(layer);
+        scterr[kSCT_BSErr_eta].push_back(eta);
+        scterr[kSCT_BSErr_phi].push_back(phi);
+        scterr[kSCT_BSErr_side].push_back(side);
+        scterr[kSCT_BSErr_type].push_back(n_type);
 
         uint32_t onlineID = m_cabling->getOnlineIdFromHash(error);
         SCT_OnlineId online(onlineID);
         uint32_t rod = online.rod();
         uint32_t fibre = online.fibre();
-        scterr_rodid.push_back((int)rod);
-        scterr_channel.push_back((int)fibre);
+        scterr[kSCT_BSErr_rodid].push_back((int)rod);
+        scterr[kSCT_BSErr_channel].push_back((int)fibre);
       }
-      
     }
+    std::vector<SG::WriteDecorHandle<xAOD::EventInfo,std::vector<int> > >   int_decor_handles(createDecorators<xAOD::EventInfo,std::vector<int> >(m_intDecorKeys,ctx));
 
+    assert(int_decor_handles.size() == kNIntDecor);
     // decorate SCT BS error
-    eventInfo->auxdecor< std::vector<int> >(m_sgName+"_SCT_BSErr_Ntot")    = scterr_Ntot;
-    eventInfo->auxdecor< std::vector<int> >(m_sgName+"_SCT_BSErr_bec")     = scterr_bec;
-    eventInfo->auxdecor< std::vector<int> >(m_sgName+"_SCT_BSErr_layer")   = scterr_layer;
-    eventInfo->auxdecor< std::vector<int> >(m_sgName+"_SCT_BSErr_eta")     = scterr_eta;
-    eventInfo->auxdecor< std::vector<int> >(m_sgName+"_SCT_BSErr_phi")     = scterr_phi;
-    eventInfo->auxdecor< std::vector<int> >(m_sgName+"_SCT_BSErr_side")    = scterr_side;
-    eventInfo->auxdecor< std::vector<int> >(m_sgName+"_SCT_BSErr_rodid")   = scterr_rodid;
-    eventInfo->auxdecor< std::vector<int> >(m_sgName+"_SCT_BSErr_channel") = scterr_channel;
-    eventInfo->auxdecor< std::vector<int> >(m_sgName+"_SCT_BSErr_type")    = scterr_type;
-    
+    for(unsigned int decorate_i=0; decorate_i<int_decor_handles.size(); ++decorate_i) {
+       int_decor_handles[decorate_i](*eventInfo) = std::move(scterr[decorate_i]);
+    }
     return StatusCode::SUCCESS;
   }  
   
-- 
GitLab


From 3aa3ba712173613d7cbb6bc73d173697153be939 Mon Sep 17 00:00:00 2001
From: Goetz Gaycken <goetz.gaycken@cern.ch>
Date: Fri, 3 Apr 2020 20:18:48 +0200
Subject: [PATCH 12/26] Migrate EventInfoPixelDecorator to decorator handles.

---
 .../EventInfoPixelDecorator.h                 | 10 ++++-
 .../src/EventInfoPixelDecorator.cxx           | 40 +++++++++++--------
 2 files changed, 32 insertions(+), 18 deletions(-)

diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/EventInfoPixelDecorator.h b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/EventInfoPixelDecorator.h
index 773836a1fed8..e6cfb8c0b85e 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/EventInfoPixelDecorator.h
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/EventInfoPixelDecorator.h
@@ -43,10 +43,16 @@ namespace DerivationFramework {
          { this, "EventInfoKey", "EventInfo", ""};
       Gaudi::Property<std::string> m_decorationPrefix
          { this, "DecorationPrefix", "", ""};
-     SG::ReadHandleKey<xAOD::TrackMeasurementValidationContainer> m_pixelKey
+      SG::ReadHandleKey<xAOD::TrackMeasurementValidationContainer> m_pixelKey
          { this, "TrackMeasurementValidationKey", "PixelClusters", ""};
 
-  }; 
+      enum EIntDecor {kperModuleMultiplicity,
+                      klayer,
+                      keta_module,
+                      kphi_module,
+                      kNIntDecor};
+      std::vector<SG::WriteDecorHandleKey<xAOD::EventInfo> > m_intDecorKeys;
+  };
 }
 
 #endif // DERIVATIONFRAMEWORK_EVENTINFOPIXELDECORATOR_H
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/EventInfoPixelDecorator.cxx b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/EventInfoPixelDecorator.cxx
index d6b034520ede..672e17df5047 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/EventInfoPixelDecorator.cxx
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/EventInfoPixelDecorator.cxx
@@ -9,8 +9,8 @@
 // Decorator tool to store per-module summary information for pixel clusters
 
 #include "DerivationFrameworkInDet/EventInfoPixelDecorator.h"
+#include "DerivationFrameworkInDet/DecoratorUtils.h"
 #include "AthenaBaseComps/AthMsgStreamMacros.h"
-#include "ExpressionEvaluation/ExpressionParser.h"
 #include "ExpressionEvaluation/SGxAODProxyLoader.h"
 #include "ExpressionEvaluation/SGNTUPProxyLoader.h"
 #include "ExpressionEvaluation/MultipleProxyLoader.h"
@@ -60,6 +60,16 @@ namespace DerivationFramework {
 	    m_parser->loadExpression(m_selectionString);
     }
 
+    {
+       std::vector<std::string> names;
+       names.resize(kNIntDecor);
+       names[kperModuleMultiplicity] ="perModuleMultiplicity";
+       names[klayer]                 ="layer";
+       names[keta_module]            ="eta_module";
+       names[kphi_module]            ="phi_module";
+       createDecoratorKeys(*this,m_eventInfoKey,m_decorationPrefix.value()+"_",names, m_intDecorKeys);
+    }
+
     return StatusCode::SUCCESS;
   }
 
@@ -116,10 +126,7 @@ namespace DerivationFramework {
     m_npass += n_pass;
 
     // fill the per-module information
-    std::vector<int> perModuleMultiplicity;
-    std::vector<int> layer;
-    std::vector<int> eta_module;
-    std::vector<int> phi_module;
+    std::array<std::vector<int>,kNIntDecor> vec;
 
     unsigned int i=0;
     std::vector<int> keys;
@@ -143,21 +150,22 @@ namespace DerivationFramework {
         }
       if( index == 9999 ){
         keys.push_back( key );
-        layer.push_back( clus_layer );
-        eta_module.push_back( clus_eta_module );
-        phi_module.push_back( clus_phi_module );
-        perModuleMultiplicity.push_back( 1 );
+        vec[klayer].push_back( clus_layer );
+        vec[keta_module].push_back( clus_eta_module );
+        vec[kphi_module].push_back( clus_phi_module );
+        vec[kperModuleMultiplicity].push_back( 1 );
       } else {
-        perModuleMultiplicity[index]++;
+        assert(index < vec[kperModuleMultiplicity].size());
+        vec[kperModuleMultiplicity][index]++;
       }
     }
 
-    // decorate per-layer multiplicity
-    eventInfo->auxdecor< std::vector<int> >(m_decorationPrefix+"_perModuleMultiplicity") = perModuleMultiplicity;
-    eventInfo->auxdecor< std::vector<int> >(m_decorationPrefix+"_layer")                 = layer;
-    eventInfo->auxdecor< std::vector<int> >(m_decorationPrefix+"_eta_module")            = eta_module;
-    eventInfo->auxdecor< std::vector<int> >(m_decorationPrefix+"_phi_module")            = phi_module;
-    
+    std::vector<SG::WriteDecorHandle<xAOD::EventInfo,std::vector<int> > >   int_decor_handles(createDecorators<xAOD::EventInfo,std::vector<int> >(m_intDecorKeys,ctx));
+    assert(int_decor_handles.size() == kNIntDecor);
+    for(unsigned int decorate_i=0; decorate_i<int_decor_handles.size(); ++decorate_i) {
+       int_decor_handles[decorate_i](*eventInfo) = std::move(vec[decorate_i]);
+    }
+
     return StatusCode::SUCCESS;
   }  
   
-- 
GitLab


From dfde6a82d0881ec3279ab3b80b74d1ddf527a698 Mon Sep 17 00:00:00 2001
From: Goetz Gaycken <goetz.gaycken@cern.ch>
Date: Fri, 3 Apr 2020 20:20:15 +0200
Subject: [PATCH 13/26] Migrate MuonTrackParticleThinning to data handles.

---
 .../MuonTrackParticleThinning.h               | 18 ++++++---
 .../src/MuonTrackParticleThinning.cxx         | 39 +++++++------------
 2 files changed, 25 insertions(+), 32 deletions(-)

diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/MuonTrackParticleThinning.h b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/MuonTrackParticleThinning.h
index a1bbddb5d15a..476eaa73257b 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/MuonTrackParticleThinning.h
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/MuonTrackParticleThinning.h
@@ -17,7 +17,9 @@
 #include "GaudiKernel/ToolHandle.h"
 #include "DerivationFrameworkInDet/TracksInCone.h"
 #include "xAODTracking/TrackParticleContainer.h"
+#include "xAODMuon/MuonContainer.h"
 #include "StoreGate/ThinningHandleKey.h"
+#include "ExpressionEvaluation/ExpressionParser.h"
 
 namespace ExpressionParsing {
   class ExpressionParser;
@@ -35,16 +37,20 @@ namespace DerivationFramework {
       virtual StatusCode doThinning() const override;
 
     private:
-      mutable std::atomic<unsigned int> m_ntot, m_npass;
+      mutable std::atomic<unsigned int> m_ntot {};
+      mutable std::atomic<unsigned int> m_npass {};
       StringProperty m_streamName
         { this, "StreamName", "", "Name of the stream being thinned" };
       SG::ThinningHandleKey<xAOD::TrackParticleContainer> m_inDetSGKey
         { this, "InDetTrackParticlesKey", "InDetTrackParticles", "" };
-      std::string m_muonSGKey;
-      std::string m_selectionString; 
-      float m_coneSize;	
-      ExpressionParsing::ExpressionParser *m_parser;
-  }; 
+      SG::ReadHandleKey<xAOD::MuonContainer> m_muonKey
+        { this, "MuonKey", "",""};
+      Gaudi::Property<std::string> m_selectionString
+        { this, "SelectionString","",""};
+      Gaudi::Property<float> m_coneSize
+        { this, "ConeSize", -1.0, ""};
+     std::unique_ptr<ExpressionParsing::ExpressionParser> m_parser;
+  };
 }
 
 #endif // DERIVATIONFRAMEWORK_MUONTRACKPARTICLETHINNING_H
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/MuonTrackParticleThinning.cxx b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/MuonTrackParticleThinning.cxx
index af0f39e9e909..b6c39712636c 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/MuonTrackParticleThinning.cxx
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/MuonTrackParticleThinning.cxx
@@ -10,12 +10,9 @@
 // which removes all ID tracks which do not pass a user-defined cut
 
 #include "DerivationFrameworkInDet/MuonTrackParticleThinning.h"
-#include "ExpressionEvaluation/ExpressionParser.h"
 #include "ExpressionEvaluation/SGxAODProxyLoader.h"
 #include "ExpressionEvaluation/SGNTUPProxyLoader.h"
 #include "ExpressionEvaluation/MultipleProxyLoader.h"
-#include "xAODMuon/MuonContainer.h"
-#include "xAODTracking/TrackParticleContainer.h"
 #include "StoreGate/ThinningHandle.h"
 #include "GaudiKernel/ThreadLocalContext.h"
 #include <vector>
@@ -25,17 +22,8 @@
 DerivationFramework::MuonTrackParticleThinning::MuonTrackParticleThinning(const std::string& t,
                                                                           const std::string& n,
                                                                           const IInterface* p ) :
-base_class(t,n,p),
-m_ntot(0),
-m_npass(0),
-m_muonSGKey(""),
-m_selectionString(""),
-m_coneSize(-1.0),
-m_parser(0)
+base_class(t,n,p)
 {
-    declareProperty("MuonKey", m_muonSGKey);
-    declareProperty("SelectionString", m_selectionString);
-    declareProperty("ConeSize", m_coneSize);
 }
 
 // Destructor
@@ -49,17 +37,17 @@ StatusCode DerivationFramework::MuonTrackParticleThinning::initialize()
     ATH_MSG_VERBOSE("initialize() ...");
     ATH_CHECK( m_inDetSGKey.initialize (m_streamName) );
     ATH_MSG_INFO("Using " << m_inDetSGKey.key() << "as the source collection for inner detector track particles");
-    if (m_muonSGKey=="") {
+    if (m_muonKey.key().empty()) {
         ATH_MSG_FATAL("No muon collection provided for thinning.");
         return StatusCode::FAILURE;
-    } else { ATH_MSG_INFO("Inner detector track particles associated with objects in " << m_muonSGKey << " will be retained in this format with the rest being thinned away");}
-   
+    } else { ATH_MSG_INFO("Inner detector track particles associated with objects in " << m_muonKey.key() << " will be retained in this format with the rest being thinned away");}
+    ATH_CHECK(m_muonKey.initialize());
     // Set up the text-parsing machinery for selectiong the muon directly according to user cuts
-    if (m_selectionString!="") {
+    if (!m_selectionString.empty()) {
 	    ExpressionParsing::MultipleProxyLoader *proxyLoaders = new ExpressionParsing::MultipleProxyLoader();
 	    proxyLoaders->push_back(new ExpressionParsing::SGxAODProxyLoader(evtStore()));
 	    proxyLoaders->push_back(new ExpressionParsing::SGNTUPProxyLoader(evtStore()));
-	    m_parser = new ExpressionParsing::ExpressionParser(proxyLoaders);
+	    m_parser = std::make_unique<ExpressionParsing::ExpressionParser>(proxyLoaders);
 	    m_parser->loadExpression(m_selectionString);
     }
     return StatusCode::SUCCESS;
@@ -69,10 +57,7 @@ StatusCode DerivationFramework::MuonTrackParticleThinning::finalize()
 {
     ATH_MSG_VERBOSE("finalize() ...");
     ATH_MSG_INFO("Processed "<< m_ntot <<" tracks, "<< m_npass<< " were retained ");
-    if (m_selectionString!="") {
-        delete m_parser;
-        m_parser = 0;
-    }
+    m_parser.reset();
     return StatusCode::SUCCESS;
 }
 
@@ -96,9 +81,9 @@ StatusCode DerivationFramework::MuonTrackParticleThinning::doThinning() const
     
     // Retrieve containers
     // ... muons
-    const xAOD::MuonContainer* importedMuons(0);
-    if (evtStore()->retrieve(importedMuons,m_muonSGKey).isFailure()) {
-        ATH_MSG_ERROR("No muon collection with name " << m_muonSGKey << " found in StoreGate!");
+    SG::ReadHandle<xAOD::MuonContainer> importedMuons( m_muonKey, ctx);
+    if (!importedMuons.isValid()) {
+        ATH_MSG_ERROR("No muon collection with name " << m_muonKey.key() << " found in StoreGate!");
         return StatusCode::FAILURE;
     }
     unsigned int nMuons(importedMuons->size());
@@ -154,9 +139,11 @@ StatusCode DerivationFramework::MuonTrackParticleThinning::doThinning() const
     }
 
     // Count up the mask contents
+    unsigned int n_pass=0;
     for (unsigned int i=0; i<nTracks; ++i) {
-        if (mask[i]) ++m_npass;
+        if (mask[i]) ++n_pass;
     }
+    m_npass+=n_pass;
     // Execute the thinning service based on the mask. Finish.
     importedTrackParticles.keep (mask);
 
-- 
GitLab


From b9c9ba2d15832ef0a3877ef4852abbab55e4ab3c Mon Sep 17 00:00:00 2001
From: Goetz Gaycken <goetz.gaycken@cern.ch>
Date: Fri, 3 Apr 2020 20:20:43 +0200
Subject: [PATCH 14/26] Migrate PixelNtupleMaker to data handles.

---
 .../PixelNtupleMaker.h                        |  14 ++-
 .../src/PixelNtupleMaker.cxx                  | 112 +++++++++---------
 2 files changed, 66 insertions(+), 60 deletions(-)

diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/PixelNtupleMaker.h b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/PixelNtupleMaker.h
index ff8ad29b146b..3d27117568fe 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/PixelNtupleMaker.h
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/PixelNtupleMaker.h
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 2002-2018 CERN for the benefit of the ATLAS collaboration
+  Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 */
 
 #ifndef DERIVATIONFRAMEWORK_PIXELNTUPLEMAKER_H
@@ -12,6 +12,10 @@
 #include "TrigDecisionTool/TrigDecisionTool.h"
 #include "DerivationFrameworkInterfaces/ISkimmingTool.h"
 
+#include "StoreGate/ReadHandleKey.h"
+#include "StoreGate/WriteHandleKey.h"
+#include "StoreGate/WriteDecorHandleKey.h"
+
 #include "xAODTracking/TrackParticleContainer.h"
 #include "xAODTracking/TrackStateValidationContainer.h"
 #include "xAODTracking/TrackMeasurementValidationContainer.h"
@@ -34,7 +38,13 @@ namespace DerivationFramework {
       void GetLayerEtaPhiFromId(uint64_t id,int *barrelEC, int *layer, int *eta, int *phi) const;
 
     private:
-      std::string m_containerName;
+      SG::ReadHandleKey<xAOD::TrackParticleContainer> m_containerKey
+         { this, "ContainerName", "InDetTrackParticles", "" };
+      SG::ReadHandleKey<xAOD::TrackMeasurementValidationContainer> m_measurementContainerKey
+         { this, "MeasurementValidationKey","PixelClusters", ""};
+
+      SG::WriteHandleKey<xAOD::TrackParticleContainer> m_monitoringTracks
+         { this, "PixelMonitoringTracksKey", "PixelMonitoringTrack","" };
 
       typedef std::vector<ElementLink< xAOD::TrackStateValidationContainer > > MeasurementsOnTrack;
       typedef std::vector<ElementLink< xAOD::TrackStateValidationContainer > >::const_iterator MeasurementsOnTrackIter;
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/PixelNtupleMaker.cxx b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/PixelNtupleMaker.cxx
index 270597c2552e..2b5d4e6b446f 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/PixelNtupleMaker.cxx
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/PixelNtupleMaker.cxx
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 2002-2018 CERN for the benefit of the ATLAS collaboration
+  Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 */
 
 #include "DerivationFrameworkInDet/PixelNtupleMaker.h"
@@ -13,17 +13,18 @@
 #include "TLorentzVector.h"
 
 DerivationFramework::PixelNtupleMaker::PixelNtupleMaker(const std::string& t, const std::string& n, const IInterface* p) : 
-  AthAlgTool(t,n,p),
-  m_containerName("InDetTrackParticles")
+  AthAlgTool(t,n,p)
 {
   declareInterface<DerivationFramework::ISkimmingTool>(this);
-  declareProperty("ContainerName", m_containerName="InDetTrackParticles");
 }
 
 DerivationFramework::PixelNtupleMaker::~PixelNtupleMaker() {
-}  
+}
 
 StatusCode DerivationFramework::PixelNtupleMaker::initialize() {
+  ATH_CHECK(m_containerKey.initialize());
+  ATH_CHECK(m_measurementContainerKey.initialize());
+  ATH_CHECK(m_monitoringTracks.initialize());
   return StatusCode::SUCCESS;
 }
 
@@ -33,30 +34,25 @@ StatusCode DerivationFramework::PixelNtupleMaker::finalize()
 }
 
 bool DerivationFramework::PixelNtupleMaker::eventPassesFilter() const {
+  const EventContext& ctx = Gaudi::Hive::currentContext();
 
-  const xAOD::TrackParticleContainer* tracks=0;
+  SG::ReadHandle<xAOD::TrackParticleContainer> tracks(m_containerKey,ctx);
 //  ATH_CHECK(evtStore()->retrieve(tracks, m_containerName));
-  if (!evtStore()->retrieve(tracks, m_containerName).isSuccess()) { return false; }
+  if (!tracks.isValid()) { return false; }
 
   // Check the event contains tracks
   unsigned int nTracks = tracks->size();
 //  if (nTracks==0) return StatusCode::SUCCESS;
   if (nTracks==0) { return false; }
 
-  const xAOD::TrackMeasurementValidationContainer* pixClustersOrig = 0;
-//  ATH_CHECK(evtStore()->retrieve(pixClustersOrig,"PixelClusters"));
-  if (!evtStore()->retrieve(pixClustersOrig,"PixelClusters").isSuccess()) { return false; }
+  SG::ReadHandle<xAOD::TrackMeasurementValidationContainer> pixClusters(m_measurementContainerKey,ctx);
+  if (!pixClusters.isValid()) { return false; }
 
-  std::pair< xAOD::TrackMeasurementValidationContainer*, xAOD::ShallowAuxContainer* > pixClustersPair = xAOD::shallowCopyContainer( *pixClustersOrig );
-  xAOD::TrackMeasurementValidationContainer* pixClusters =  pixClustersPair.first;
-
-  xAOD::TrackParticleContainer* PixelMonitoringTrack = new xAOD::TrackParticleContainer();
-  xAOD::TrackParticleAuxContainer* PixelMonitoringTrackAux = new xAOD::TrackParticleAuxContainer();
-  PixelMonitoringTrack->setStore(PixelMonitoringTrackAux);
-//  ATH_CHECK(evtStore()->record(PixelMonitoringTrack,"PixelMonitoringTrack"));
-//  ATH_CHECK(evtStore()->record(PixelMonitoringTrackAux,"PixelMonitoringTrackAux."));
-  if (!evtStore()->record(PixelMonitoringTrack,"PixelMonitoringTrack").isSuccess()) { return false; }
-  if (!evtStore()->record(PixelMonitoringTrackAux,"PixelMonitoringTrackAux.").isSuccess()) { return false; }
+  SG::WriteHandle<xAOD::TrackParticleContainer> PixelMonitoringTrack(m_monitoringTracks,ctx);
+  if (PixelMonitoringTrack.record(std::make_unique<xAOD::TrackParticleContainer>(),
+                                  std::make_unique<xAOD::TrackParticleAuxContainer>()).isFailure())  {
+     return false;
+  }
 
   std::vector<float> tmpCov(15,0.);
   static SG::AuxElement::ConstAccessor<MeasurementsOnTrack>  acc_MeasurementsOnTrack("msosLink");
@@ -127,7 +123,7 @@ bool DerivationFramework::PixelNtupleMaker::eventPassesFilter() const {
           } // not a hole
           const xAOD::TrackMeasurementValidation* msosClus =  *(msos->trackMeasurementValidationLink());        
 
-          for (xAOD::TrackMeasurementValidationContainer::iterator clus_itr=(pixClusters)->begin(); clus_itr!=(pixClusters)->end(); ++clus_itr) {
+          for (xAOD::TrackMeasurementValidationContainer::const_iterator clus_itr=pixClusters->begin(); clus_itr!=pixClusters->end(); ++clus_itr) {
             if ((*clus_itr)->identifier()!=(msosClus)->identifier()) { continue; }
             if ((*clus_itr)->auxdata<float>("charge")!=(msosClus)->auxdata<float>("charge")) { continue; }
 
@@ -163,7 +159,7 @@ bool DerivationFramework::PixelNtupleMaker::eventPassesFilter() const {
             int numNeighborCluster20x4 = 0;
             int nTotalClustersPerModule = 0;
             int nTotalPixelsPerModule = 0;
-            for (xAOD::TrackMeasurementValidationContainer::iterator clus_neighbor=(pixClusters)->begin(); clus_neighbor!=(pixClusters)->end(); ++clus_neighbor) {
+            for (xAOD::TrackMeasurementValidationContainer::const_iterator clus_neighbor=pixClusters->begin(); clus_neighbor!=pixClusters->end(); ++clus_neighbor) {
               if ((*clus_neighbor)->auxdata<int>("layer")==(*clus_itr)->auxdata<int>("layer")
                   && (*clus_neighbor)->auxdata<int>("bec")==(*clus_itr)->auxdata<int>("bec")
                   && (*clus_neighbor)->auxdata<int>("phi_module")==(*clus_itr)->auxdata<int>("phi_module")
@@ -301,42 +297,42 @@ bool DerivationFramework::PixelNtupleMaker::eventPassesFilter() const {
       static SG::AuxElement::Decorator<std::vector<std::vector<int>>>   RdoEta("RdoEta");
       d0err(*tp)             = (*trk)->definingParametersCovMatrixVec().at(0);
       z0err(*tp)             = (*trk)->definingParametersCovMatrixVec().at(2);
-      HoleIndex(*tp)         = holeIndex;
-      ClusterLayer(*tp)      = clusterLayer;
-      ClusterBEC(*tp)        = clusterBEC;
-      ClusterModulePhi(*tp)  = clusterModulePhi;
-      ClusterModuleEta(*tp)  = clusterModuleEta;
-      ClusterCharge(*tp)     = clusterCharge;
-      ClusterToT(*tp)        = clusterToT;
-      ClusterL1A(*tp)        = clusterL1A;
-      ClusterIsSplit(*tp)    = clusterIsSplit;
-      ClusterSize(*tp)       = clusterSize;
-      ClusterSizePhi(*tp)    = clusterSizePhi;
-      ClusterSizeZ(*tp)      = clusterSizeZ;
-      ClusterIsEdge(*tp)     = isEdge;
-      ClusterIsOverflow(*tp) = isOverflow;
-      TrackLocalPhi(*tp)     = trackPhi;
-      TrackLocalTheta(*tp)   = trackTheta;
-      TrackLocalX(*tp)       = trackX;
-      TrackLocalY(*tp)       = trackY;
-      ClusterLocalX(*tp)     = localX;
-      ClusterLocalY(*tp)     = localY;
-      ClusterGlobalX(*tp)    = globalX;
-      ClusterGlobalY(*tp)    = globalY;
-      ClusterGlobalZ(*tp)    = globalZ;
-      UnbiasedResidualX(*tp) = unbiasedResidualX;
-      UnbiasedResidualY(*tp) = unbiasedResidualY;
-      ClusterIsolation10x2(*tp) = clusterIsolation10x2;
-      ClusterIsolation20x4(*tp) = clusterIsolation20x4;
-      NumTotalClustersPerModule(*tp) = numTotalClustersPerModule;
-      NumTotalPixelsPerModule(*tp)   = numTotalPixelsPerModule;
-      ModuleBiasVoltage(*tp)  = moduleBiasVoltage;
-      ModuleTemperature(*tp)  = moduleTemperature;
-      ModuleLorentzShift(*tp) = moduleLorentzShift;
-      RdoToT(*tp)    = rdoToT;
-      RdoCharge(*tp) = rdoCharge;
-      RdoPhi(*tp)    = rdoPhi;
-      RdoEta(*tp)    = rdoEta;
+      HoleIndex(*tp)         = std::move(holeIndex);
+      ClusterLayer(*tp)      = std::move(clusterLayer);
+      ClusterBEC(*tp)        = std::move(clusterBEC);
+      ClusterModulePhi(*tp)  = std::move(clusterModulePhi);
+      ClusterModuleEta(*tp)  = std::move(clusterModuleEta);
+      ClusterCharge(*tp)     = std::move(clusterCharge);
+      ClusterToT(*tp)        = std::move(clusterToT);
+      ClusterL1A(*tp)        = std::move(clusterL1A);
+      ClusterIsSplit(*tp)    = std::move(clusterIsSplit);
+      ClusterSize(*tp)       = std::move(clusterSize);
+      ClusterSizePhi(*tp)    = std::move(clusterSizePhi);
+      ClusterSizeZ(*tp)      = std::move(clusterSizeZ);
+      ClusterIsEdge(*tp)     = std::move(isEdge);
+      ClusterIsOverflow(*tp) = std::move(isOverflow);
+      TrackLocalPhi(*tp)     = std::move(trackPhi);
+      TrackLocalTheta(*tp)   = std::move(trackTheta);
+      TrackLocalX(*tp)       = std::move(trackX);
+      TrackLocalY(*tp)       = std::move(trackY);
+      ClusterLocalX(*tp)     = std::move(localX);
+      ClusterLocalY(*tp)     = std::move(localY);
+      ClusterGlobalX(*tp)    = std::move(globalX);
+      ClusterGlobalY(*tp)    = std::move(globalY);
+      ClusterGlobalZ(*tp)    = std::move(globalZ);
+      UnbiasedResidualX(*tp) = std::move(unbiasedResidualX);
+      UnbiasedResidualY(*tp) = std::move(unbiasedResidualY);
+      ClusterIsolation10x2(*tp) = std::move(clusterIsolation10x2);
+      ClusterIsolation20x4(*tp) = std::move(clusterIsolation20x4);
+      NumTotalClustersPerModule(*tp) = std::move(numTotalClustersPerModule);
+      NumTotalPixelsPerModule(*tp)   = std::move(numTotalPixelsPerModule);
+      ModuleBiasVoltage(*tp)  = std::move(moduleBiasVoltage);
+      ModuleTemperature(*tp)  = std::move(moduleTemperature);
+      ModuleLorentzShift(*tp) = std::move(moduleLorentzShift);
+      RdoToT(*tp)    = std::move(rdoToT);
+      RdoCharge(*tp) = std::move(rdoCharge);
+      RdoPhi(*tp)    = std::move(rdoPhi);
+      RdoEta(*tp)    = std::move(rdoEta);
 
       PixelMonitoringTrack->push_back(tp);
     }
-- 
GitLab


From 80fb0abdd29292446d01006eb63671ad1dee2f7b Mon Sep 17 00:00:00 2001
From: Goetz Gaycken <goetz.gaycken@cern.ch>
Date: Fri, 3 Apr 2020 20:32:54 +0200
Subject: [PATCH 15/26] Migrate TauTrackParticleThinning to data handles.

---
 .../TauTrackParticleThinning.h                | 20 +++++++---
 .../src/TauTrackParticleThinning.cxx          | 40 +++++++------------
 2 files changed, 30 insertions(+), 30 deletions(-)

diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/TauTrackParticleThinning.h b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/TauTrackParticleThinning.h
index 01b07c491ac4..985c7a9bf366 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/TauTrackParticleThinning.h
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/TauTrackParticleThinning.h
@@ -17,7 +17,10 @@
 #include "GaudiKernel/ToolHandle.h"
 #include "DerivationFrameworkInDet/TracksInCone.h"
 #include "xAODTracking/TrackParticleContainer.h"
+#include "xAODTau/TauJetContainer.h"
+
 #include "StoreGate/ThinningHandleKey.h"
+#include "StoreGate/ReadHandleKey.h"
 
 namespace ExpressionParsing {
   class ExpressionParser;
@@ -35,15 +38,22 @@ namespace DerivationFramework {
       virtual StatusCode doThinning() const override;
 
     private:
-      mutable std::atomic<unsigned int> m_ntot, m_npass;
+      mutable std::atomic<unsigned int> m_ntot {};
+      mutable std::atomic<unsigned int> m_npass {};
       StringProperty m_streamName
         { this, "StreamName", "", "Name of the stream being thinned" };
       SG::ThinningHandleKey<xAOD::TrackParticleContainer> m_inDetSGKey
         { this, "InDetTrackParticlesKey", "InDetTrackParticles", "" };
-      std::string m_tauSGKey, m_selectionString;
-      float m_coneSize;
-      ExpressionParsing::ExpressionParser *m_parser;
-  }; 
+      SG::ReadHandleKey<xAOD::TauJetContainer> m_tauKey
+         { this, "TauKey", "", ""};
+
+      Gaudi::Property<std::string> m_selectionString
+         { this, "SelectionString", "",""};
+      Gaudi::Property<float> m_coneSize
+         { this, "ConeSize", -1.0,  ""};
+
+      std::unique_ptr<ExpressionParsing::ExpressionParser> m_parser;
+  };
 }
 
 #endif // DERIVATIONFRAMEWORK_TAUTRACKPARTICLETHINNING_H
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/TauTrackParticleThinning.cxx b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/TauTrackParticleThinning.cxx
index 6bbdff0ca5bb..38e13682229a 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/TauTrackParticleThinning.cxx
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/TauTrackParticleThinning.cxx
@@ -14,7 +14,6 @@
 #include "ExpressionEvaluation/SGxAODProxyLoader.h"
 #include "ExpressionEvaluation/MultipleProxyLoader.h"
 #include "ExpressionEvaluation/SGNTUPProxyLoader.h"
-#include "xAODTau/TauJetContainer.h"
 #include "xAODTau/TauxAODHelpers.h"
 #include "xAODTracking/TrackParticleContainer.h"
 #include "StoreGate/ThinningHandle.h"
@@ -26,17 +25,8 @@
 DerivationFramework::TauTrackParticleThinning::TauTrackParticleThinning(const std::string& t,
                                                                         const std::string& n,
                                                                         const IInterface* p ) :
-base_class(t,n,p),
-m_ntot(0),
-m_npass(0),
-m_tauSGKey(""),
-m_selectionString(""),
-m_coneSize(-1.0),
-m_parser(0)
+base_class(t,n,p)
 {
-    declareProperty("TauKey", m_tauSGKey);
-    declareProperty("SelectionString", m_selectionString);
-    declareProperty("ConeSize", m_coneSize);
 }
 
 // Destructor
@@ -50,17 +40,18 @@ StatusCode DerivationFramework::TauTrackParticleThinning::initialize()
     ATH_MSG_VERBOSE("initialize() ...");
     ATH_CHECK( m_inDetSGKey.initialize (m_streamName) );
     ATH_MSG_INFO("Using " << m_inDetSGKey << "as the source collection for inner detector track particles");
-    if (m_tauSGKey=="") {
+    if (m_tauKey.key().empty()) {
         ATH_MSG_FATAL("No tau collection provided for thinning.");
         return StatusCode::FAILURE;
-    } else { ATH_MSG_INFO("Inner detector track particles associated with objects in " << m_tauSGKey << " will be retained in this format with the rest being thinned away");}
-    
+    } else { ATH_MSG_INFO("Inner detector track particles associated with objects in " << m_tauKey.key() << " will be retained in this format with the rest being thinned away");}
+    ATH_CHECK(m_tauKey.initialize());
+
     // Set up the text-parsing machinery for selectiong the tau directly according to user cuts
-    if (m_selectionString!="") {
+    if (!m_selectionString.empty()) {
 	    ExpressionParsing::MultipleProxyLoader *proxyLoaders = new ExpressionParsing::MultipleProxyLoader();
 	    proxyLoaders->push_back(new ExpressionParsing::SGxAODProxyLoader(evtStore()));
 	    proxyLoaders->push_back(new ExpressionParsing::SGNTUPProxyLoader(evtStore()));
-	    m_parser = new ExpressionParsing::ExpressionParser(proxyLoaders);
+	    m_parser = std::make_unique<ExpressionParsing::ExpressionParser>(proxyLoaders);
 	    m_parser->loadExpression(m_selectionString);
     }
     return StatusCode::SUCCESS;
@@ -70,10 +61,7 @@ StatusCode DerivationFramework::TauTrackParticleThinning::finalize()
 {
     ATH_MSG_VERBOSE("finalize() ...");
     ATH_MSG_INFO("Processed "<< m_ntot <<" tracks, "<< m_npass<< " were retained ");
-    if (m_selectionString!="") {
-        delete m_parser;
-        m_parser = 0;
-    }
+    m_parser.reset();
     return StatusCode::SUCCESS;
 }
 
@@ -97,9 +85,9 @@ StatusCode DerivationFramework::TauTrackParticleThinning::doThinning() const
     
     // Retrieve containers
     // ... taus
-    const xAOD::TauJetContainer* importedTaus(0);
-    if (evtStore()->retrieve(importedTaus,m_tauSGKey).isFailure()) {
-        ATH_MSG_ERROR("No tau collection with name " << m_tauSGKey << " found in StoreGate!");
+    SG::ReadHandle<xAOD::TauJetContainer> importedTaus(m_tauKey,ctx);
+    if (!importedTaus.isValid()) {
+        ATH_MSG_ERROR("No tau collection with name " << m_tauKey.key() << " found in StoreGate!");
         return StatusCode::FAILURE;
     }
     unsigned int nTaus(importedTaus->size());
@@ -149,10 +137,12 @@ StatusCode DerivationFramework::TauTrackParticleThinning::doThinning() const
     }
     
     // Count up the mask contents
+    unsigned int n_pass=0;
     for (unsigned int i=0; i<nTracks; ++i) {
-        if (mask[i]) ++m_npass;
+        if (mask[i]) ++n_pass;
     }
-    
+    m_npass += n_pass;
+
     // Execute the thinning service based on the mask. Finish.
     importedTrackParticles.keep (mask);
 
-- 
GitLab


From 051284d37201c9e298bed9f227d58dbadeac6f1b Mon Sep 17 00:00:00 2001
From: Goetz Gaycken <goetz.gaycken@cern.ch>
Date: Fri, 3 Apr 2020 20:58:11 +0200
Subject: [PATCH 16/26] Cleanup TrackMeasurementThinning.

---
 .../TrackMeasurementThinning.h                | 11 +++++-----
 .../src/TrackMeasurementThinning.cxx          | 22 +++++++------------
 2 files changed, 13 insertions(+), 20 deletions(-)

diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/TrackMeasurementThinning.h b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/TrackMeasurementThinning.h
index ba8ece45f47f..876776277c67 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/TrackMeasurementThinning.h
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/TrackMeasurementThinning.h
@@ -48,13 +48,12 @@ namespace DerivationFramework {
     virtual StatusCode doThinning() const override;
  
   private:
-    //Expression for object thinning selection
-    std::string m_expression;
-    ExpressionParsing::ExpressionParser *m_parser;
-    std::string m_selectionString;
+    std::unique_ptr<ExpressionParsing::ExpressionParser> m_parser;
+    Gaudi::Property<std::string> m_selectionString
+      { this, "SelectionString", "", ""};
 
-    mutable std::atomic<unsigned int> m_ntot;
-    mutable std::atomic<unsigned int> m_npass;
+    mutable std::atomic<unsigned int> m_ntot {};
+    mutable std::atomic<unsigned int> m_npass {};
     StringProperty m_streamName
       { this, "StreamName", "", "Name of the stream being thinned" };
 
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/TrackMeasurementThinning.cxx b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/TrackMeasurementThinning.cxx
index 16f68e92768f..33e14560519e 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/TrackMeasurementThinning.cxx
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/TrackMeasurementThinning.cxx
@@ -23,13 +23,8 @@
 DerivationFramework::TrackMeasurementThinning::TrackMeasurementThinning( 	const std::string& t,
                                                  		const std::string& n,
                                                  		const IInterface* p ) : 
-  base_class(t,n,p),
-  m_parser(0),
-  m_selectionString(""),
-  m_ntot(0),
-  m_npass(0)
+  base_class(t,n,p)
   {
-    declareProperty("SelectionString", m_selectionString);
   }
   
 // Destructor
@@ -40,7 +35,7 @@ DerivationFramework::TrackMeasurementThinning::~TrackMeasurementThinning() {
 StatusCode DerivationFramework::TrackMeasurementThinning::initialize()
 {
     ATH_MSG_VERBOSE("initialize() ...");
-    if (m_selectionString=="") {
+    if (m_selectionString.empty()) {
         ATH_MSG_FATAL("No inner detector track selection string provided!");
         return StatusCode::FAILURE;
     } else {ATH_MSG_INFO("Track thinning selection string: " << m_selectionString);}
@@ -50,11 +45,11 @@ StatusCode DerivationFramework::TrackMeasurementThinning::initialize()
     ATH_MSG_INFO("Using " << m_SGKey << "as the source collection for thinning.");
 
     // Set up the text-parsing machinery for thinning the tracks directly according to user cuts
-    if (m_selectionString!="") {
+    if (!m_selectionString.empty()) {
 	    ExpressionParsing::MultipleProxyLoader *proxyLoaders = new ExpressionParsing::MultipleProxyLoader();
 	    proxyLoaders->push_back(new ExpressionParsing::SGxAODProxyLoader(evtStore()));
 	    proxyLoaders->push_back(new ExpressionParsing::SGNTUPProxyLoader(evtStore()));
-	    m_parser = new ExpressionParsing::ExpressionParser(proxyLoaders);
+	    m_parser = std::make_unique<ExpressionParsing::ExpressionParser>(proxyLoaders);
 	    m_parser->loadExpression(m_selectionString);
     }
     return StatusCode::SUCCESS;
@@ -63,10 +58,7 @@ StatusCode DerivationFramework::TrackMeasurementThinning::finalize()
 {
     ATH_MSG_VERBOSE("finalize() ...");
     ATH_MSG_INFO("Processed "<< m_ntot <<" measurements, "<< m_npass<< " were retained ");
-    if (m_parser) {
-        delete m_parser;
-        m_parser = 0;
-    }
+    m_parser.reset();
     return StatusCode::SUCCESS;
 }
 
@@ -102,9 +94,11 @@ StatusCode DerivationFramework::TrackMeasurementThinning::doThinning() const
         }
     }
     // Count the mask
+    unsigned int n_pass=0;
     for (unsigned int i=0; i<nClusters; ++i) {
-        if (mask[i]) ++m_npass;
+        if (mask[i]) ++n_pass;
     }
+    m_npass += n_pass;
  
     // Execute the thinning service based on the mask. Finish.
     clusters.keep (mask);
-- 
GitLab


From db3218baff6db0f8d216c8542d03756d34eb465d Mon Sep 17 00:00:00 2001
From: Goetz Gaycken <goetz.gaycken@cern.ch>
Date: Fri, 3 Apr 2020 21:01:36 +0200
Subject: [PATCH 17/26] Converted end-of-line from Dos to unix in
 TrackParametersAtPV.

---
 .../TrackParametersAtPV.h                     | 102 ++++----
 .../src/TrackParametersAtPV.cxx               | 218 +++++++++---------
 2 files changed, 160 insertions(+), 160 deletions(-)

diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/TrackParametersAtPV.h b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/TrackParametersAtPV.h
index cbefe92e0c02..afab5dc447bf 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/TrackParametersAtPV.h
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/TrackParametersAtPV.h
@@ -1,54 +1,54 @@
 /*
-  Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
+  Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 */
 
-///////////////////////////////////////////////////////////
-// TrackParametersAtPV.h  (c) ATLAS Detector software
-///////////////////////////////////////////////////////////////////
-
-#ifndef DERIVATIONFRAMEWORK_TRACKPARAMETERSATPV_H
-#define DERIVATIONFRAMEWORK_TRACKPARAMETERSATPV_H 
-
-#include<string>
-
-// Gaudi & Athena basics
-#include "AthenaBaseComps/AthAlgTool.h"
-
-// DerivationFramework includes
-#include "DerivationFrameworkInterfaces/IAugmentationTool.h"
-
-namespace DerivationFramework {
-
-  /** @class TrackParametersAtPV
- 
-      the code used in this implementation is kindly stolen from:
-      atlasoff:: ISF/ISF_Core/ISF_Tools
-
-      @author James Catmore -at- cern.ch
-     */
-  class TrackParametersAtPV : public AthAlgTool, public IAugmentationTool {
-   
-  public: 
-    /** Constructor with parameters */
-    TrackParametersAtPV( const std::string& t, const std::string& n, const IInterface* p );
-   
-    /** Destructor */
-    ~TrackParametersAtPV();
-   
-    // Athena algtool's Hooks
-    StatusCode  initialize();
-    StatusCode  finalize();
- 
-    /** Check that the current event passes this filter */
-    virtual StatusCode addBranches() const;
-
-  private:
-    std::string m_collTrackName;
-    std::string m_collVertexName;
-    std::string m_sgKey1;
-
-  }; 
- 
-}
-
-#endif
+///////////////////////////////////////////////////////////
+// TrackParametersAtPV.h  (c) ATLAS Detector software
+///////////////////////////////////////////////////////////////////
+
+#ifndef DERIVATIONFRAMEWORK_TRACKPARAMETERSATPV_H
+#define DERIVATIONFRAMEWORK_TRACKPARAMETERSATPV_H 
+
+#include<string>
+
+// Gaudi & Athena basics
+#include "AthenaBaseComps/AthAlgTool.h"
+
+// DerivationFramework includes
+#include "DerivationFrameworkInterfaces/IAugmentationTool.h"
+
+namespace DerivationFramework {
+
+  /** @class TrackParametersAtPV
+ 
+      the code used in this implementation is kindly stolen from:
+      atlasoff:: ISF/ISF_Core/ISF_Tools
+
+      @author James Catmore -at- cern.ch
+     */
+  class TrackParametersAtPV : public AthAlgTool, public IAugmentationTool {
+   
+  public: 
+    /** Constructor with parameters */
+    TrackParametersAtPV( const std::string& t, const std::string& n, const IInterface* p );
+   
+    /** Destructor */
+    ~TrackParametersAtPV();
+   
+    // Athena algtool's Hooks
+    StatusCode  initialize();
+    StatusCode  finalize();
+ 
+    /** Check that the current event passes this filter */
+    virtual StatusCode addBranches() const;
+
+  private:
+    std::string m_collTrackName;
+    std::string m_collVertexName;
+    std::string m_sgKey1;
+
+  }; 
+ 
+}
+
+#endif
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/TrackParametersAtPV.cxx b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/TrackParametersAtPV.cxx
index 2e3b5fda63fe..40e44386e306 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/TrackParametersAtPV.cxx
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/TrackParametersAtPV.cxx
@@ -1,112 +1,112 @@
 /*
-  Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
+  Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 */
 
-///////////////////////////////////////////////////////////////////
-// TrackParametersAtPV.cxx, (c) ATLAS Detector software
-///////////////////////////////////////////////////////////////////
-// Author: Tomoe Kishimoto (Tomoe.Kishimoto@cern.ch)
-// Wrapper around the passSelection() method of xAOD egamma
-// Writes result to SG for later selection by string parser
-
-#include "DerivationFrameworkInDet/TrackParametersAtPV.h"
-#include "xAODTracking/TrackParticleContainer.h"
-#include "xAODTracking/VertexContainer.h"
-#include <vector>
-#include <string>
-
-// Constructor
-DerivationFramework::TrackParametersAtPV::TrackParametersAtPV( const std::string& t,
-                                                 const std::string& n,
-                                                 const IInterface* p ) :
-  AthAlgTool(t,n,p),
-  m_collTrackName("InDetTrackParticles"),
-  m_collVertexName("PrimaryVertices"),
-  m_sgKey1("")
-  {
-    declareInterface<DerivationFramework::IAugmentationTool>(this);
-    declareProperty("TrackParticleContainerName", m_collTrackName);
-    declareProperty("VertexContainerName", m_collVertexName);
-    declareProperty("Z0SGEntryName", m_sgKey1);
-  }
- 
-// Destructor
-DerivationFramework::TrackParametersAtPV::~TrackParametersAtPV() {
-} 
-
-// Athena initialize and finalize
-StatusCode DerivationFramework::TrackParametersAtPV::initialize()
-{
-  if (m_collTrackName == "" || m_collVertexName == "") {
-    ATH_MSG_ERROR("No selection variables for the TrackParametersAtPV tool!");
-    return StatusCode::FAILURE;
-  }
-  
-  if (m_sgKey1 == "") {
-    ATH_MSG_ERROR("No Store Gate Keys for the TrackParametersAtPV tool!");
-    return StatusCode::FAILURE;
-  }
-  
-  ATH_MSG_VERBOSE("initialize() ...");
-  return StatusCode::SUCCESS;
-}
-
-StatusCode DerivationFramework::TrackParametersAtPV::finalize()
-{
-  ATH_MSG_VERBOSE("finalize() ...");
-  return StatusCode::SUCCESS;
-}
-
-// Augmentation
-StatusCode DerivationFramework::TrackParametersAtPV::addBranches() const
-{
-  std::unique_ptr<std::vector<float> > track_z0_PV(new std::vector<float>());  
-
-  // Get Primary vertex
-  const xAOD::VertexContainer* vertices = 
-    evtStore()->retrieve< const xAOD::VertexContainer >(m_collVertexName);
-    
-  if(!vertices) {
-    ATH_MSG_ERROR ("Couldn't retrieve VertexContainer with key: " << m_collVertexName);
-    return StatusCode::FAILURE;
-  }
-
-  const xAOD::Vertex* pv(0);
-  for (const xAOD::Vertex* vx : *vertices) {
-    if (vx->vertexType() == xAOD::VxType::PriVtx) {
-      pv = vx;
-      break;
-    }
-  }
-
-  // Get the track container
-  const xAOD::TrackParticleContainer* tracks = 
-    evtStore()->retrieve< const xAOD::TrackParticleContainer >(m_collTrackName);
-  
-  if(!tracks) {
-    ATH_MSG_ERROR ("Couldn't retrieve TrackParticleContainer with key: " << m_collTrackName);
-    return StatusCode::FAILURE;
-  }
-
-  // Get track z0 w.r.t PV
-  for (xAOD::TrackParticleContainer::const_iterator trackIt=tracks->begin(); trackIt!=tracks->end(); ++trackIt) {
-    if (pv) {
-      float z0wrtPV = (*trackIt)->z0() + (*trackIt)->vz() - pv->z();
-      track_z0_PV->push_back(z0wrtPV);
-
-    } else {
-      track_z0_PV->push_back(999.);
-    }
-  }
-
-  // Write decision to SG for access by downstream algs 
-  if (evtStore()->contains<std::vector<float> >(m_sgKey1)) {
-      ATH_MSG_ERROR("Tool is attempting to write StoreGate keys which already exists. Please use a different key");
-      return StatusCode::FAILURE;
-  } else {
-    CHECK(evtStore()->record(std::move(track_z0_PV), m_sgKey1));       
-  }
-
-  return StatusCode::SUCCESS;
-}
-
+///////////////////////////////////////////////////////////////////
+// TrackParametersAtPV.cxx, (c) ATLAS Detector software
+///////////////////////////////////////////////////////////////////
+// Author: Tomoe Kishimoto (Tomoe.Kishimoto@cern.ch)
+// Wrapper around the passSelection() method of xAOD egamma
+// Writes result to SG for later selection by string parser
+
+#include "DerivationFrameworkInDet/TrackParametersAtPV.h"
+#include "xAODTracking/TrackParticleContainer.h"
+#include "xAODTracking/VertexContainer.h"
+#include <vector>
+#include <string>
+
+// Constructor
+DerivationFramework::TrackParametersAtPV::TrackParametersAtPV( const std::string& t,
+                                                 const std::string& n,
+                                                 const IInterface* p ) :
+  AthAlgTool(t,n,p),
+  m_collTrackName("InDetTrackParticles"),
+  m_collVertexName("PrimaryVertices"),
+  m_sgKey1("")
+  {
+    declareInterface<DerivationFramework::IAugmentationTool>(this);
+    declareProperty("TrackParticleContainerName", m_collTrackName);
+    declareProperty("VertexContainerName", m_collVertexName);
+    declareProperty("Z0SGEntryName", m_sgKey1);
+  }
+ 
+// Destructor
+DerivationFramework::TrackParametersAtPV::~TrackParametersAtPV() {
+} 
+
+// Athena initialize and finalize
+StatusCode DerivationFramework::TrackParametersAtPV::initialize()
+{
+  if (m_collTrackName == "" || m_collVertexName == "") {
+    ATH_MSG_ERROR("No selection variables for the TrackParametersAtPV tool!");
+    return StatusCode::FAILURE;
+  }
+  
+  if (m_sgKey1 == "") {
+    ATH_MSG_ERROR("No Store Gate Keys for the TrackParametersAtPV tool!");
+    return StatusCode::FAILURE;
+  }
+  
+  ATH_MSG_VERBOSE("initialize() ...");
+  return StatusCode::SUCCESS;
+}
+
+StatusCode DerivationFramework::TrackParametersAtPV::finalize()
+{
+  ATH_MSG_VERBOSE("finalize() ...");
+  return StatusCode::SUCCESS;
+}
+
+// Augmentation
+StatusCode DerivationFramework::TrackParametersAtPV::addBranches() const
+{
+  std::unique_ptr<std::vector<float> > track_z0_PV(new std::vector<float>());  
+
+  // Get Primary vertex
+  const xAOD::VertexContainer* vertices = 
+    evtStore()->retrieve< const xAOD::VertexContainer >(m_collVertexName);
+    
+  if(!vertices) {
+    ATH_MSG_ERROR ("Couldn't retrieve VertexContainer with key: " << m_collVertexName);
+    return StatusCode::FAILURE;
+  }
+
+  const xAOD::Vertex* pv(0);
+  for (const xAOD::Vertex* vx : *vertices) {
+    if (vx->vertexType() == xAOD::VxType::PriVtx) {
+      pv = vx;
+      break;
+    }
+  }
+
+  // Get the track container
+  const xAOD::TrackParticleContainer* tracks = 
+    evtStore()->retrieve< const xAOD::TrackParticleContainer >(m_collTrackName);
+  
+  if(!tracks) {
+    ATH_MSG_ERROR ("Couldn't retrieve TrackParticleContainer with key: " << m_collTrackName);
+    return StatusCode::FAILURE;
+  }
+
+  // Get track z0 w.r.t PV
+  for (xAOD::TrackParticleContainer::const_iterator trackIt=tracks->begin(); trackIt!=tracks->end(); ++trackIt) {
+    if (pv) {
+      float z0wrtPV = (*trackIt)->z0() + (*trackIt)->vz() - pv->z();
+      track_z0_PV->push_back(z0wrtPV);
+
+    } else {
+      track_z0_PV->push_back(999.);
+    }
+  }
+
+  // Write decision to SG for access by downstream algs 
+  if (evtStore()->contains<std::vector<float> >(m_sgKey1)) {
+      ATH_MSG_ERROR("Tool is attempting to write StoreGate keys which already exists. Please use a different key");
+      return StatusCode::FAILURE;
+  } else {
+    CHECK(evtStore()->record(std::move(track_z0_PV), m_sgKey1));       
+  }
+
+  return StatusCode::SUCCESS;
+}
+
-- 
GitLab


From 3ca37dc8426ef1fd87150b9e770c98e8e868389a Mon Sep 17 00:00:00 2001
From: Goetz Gaycken <goetz.gaycken@cern.ch>
Date: Fri, 3 Apr 2020 21:59:51 +0200
Subject: [PATCH 18/26] Migrate TrackParametersAtPV to data handles.

---
 .../TrackParametersAtPV.h                     | 18 +++++--
 .../src/TrackParametersAtPV.cxx               | 54 +++++++------------
 2 files changed, 33 insertions(+), 39 deletions(-)

diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/TrackParametersAtPV.h b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/TrackParametersAtPV.h
index afab5dc447bf..a6171f0794a0 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/TrackParametersAtPV.h
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/TrackParametersAtPV.h
@@ -13,6 +13,12 @@
 
 // Gaudi & Athena basics
 #include "AthenaBaseComps/AthAlgTool.h"
+#include "xAODTracking/TrackParticleContainer.h"
+#include "xAODTracking/VertexContainer.h"
+#include <vector>
+
+#include <StoreGate/ReadHandleKey.h>
+#include <StoreGate/WriteHandleKey.h>
 
 // DerivationFramework includes
 #include "DerivationFrameworkInterfaces/IAugmentationTool.h"
@@ -43,11 +49,15 @@ namespace DerivationFramework {
     virtual StatusCode addBranches() const;
 
   private:
-    std::string m_collTrackName;
-    std::string m_collVertexName;
-    std::string m_sgKey1;
+    SG::ReadHandleKey<xAOD::TrackParticleContainer> m_collTrackKey
+       { this, "TrackParticleContainerName", "InDetTrackParticles", ""};
+    SG::ReadHandleKey<xAOD::VertexContainer>        m_collVertexKey
+       { this, "VertexContainerName", "PrimaryVertices", ""};
+
+    SG::WriteHandleKey< std::vector<float> > m_trackZ0PVKey
+       { this, "Z0SGEntryName", "", "" };
 
-  }; 
+  };
  
 }
 
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/TrackParametersAtPV.cxx b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/TrackParametersAtPV.cxx
index 40e44386e306..1294189adeae 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/TrackParametersAtPV.cxx
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/TrackParametersAtPV.cxx
@@ -10,43 +10,37 @@
 // Writes result to SG for later selection by string parser
 
 #include "DerivationFrameworkInDet/TrackParametersAtPV.h"
-#include "xAODTracking/TrackParticleContainer.h"
-#include "xAODTracking/VertexContainer.h"
-#include <vector>
 #include <string>
 
 // Constructor
 DerivationFramework::TrackParametersAtPV::TrackParametersAtPV( const std::string& t,
                                                  const std::string& n,
                                                  const IInterface* p ) :
-  AthAlgTool(t,n,p),
-  m_collTrackName("InDetTrackParticles"),
-  m_collVertexName("PrimaryVertices"),
-  m_sgKey1("")
+  AthAlgTool(t,n,p)
   {
     declareInterface<DerivationFramework::IAugmentationTool>(this);
-    declareProperty("TrackParticleContainerName", m_collTrackName);
-    declareProperty("VertexContainerName", m_collVertexName);
-    declareProperty("Z0SGEntryName", m_sgKey1);
   }
- 
+
 // Destructor
 DerivationFramework::TrackParametersAtPV::~TrackParametersAtPV() {
-} 
+}
 
 // Athena initialize and finalize
 StatusCode DerivationFramework::TrackParametersAtPV::initialize()
 {
-  if (m_collTrackName == "" || m_collVertexName == "") {
+   if (m_collTrackKey.key().empty() || m_collVertexKey.key().empty()) {
     ATH_MSG_ERROR("No selection variables for the TrackParametersAtPV tool!");
     return StatusCode::FAILURE;
   }
-  
-  if (m_sgKey1 == "") {
+  ATH_CHECK( m_collTrackKey.initialize() );
+  ATH_CHECK( m_collVertexKey.initialize() );
+
+  if (m_trackZ0PVKey.key().empty()) {
     ATH_MSG_ERROR("No Store Gate Keys for the TrackParametersAtPV tool!");
     return StatusCode::FAILURE;
   }
-  
+  ATH_CHECK( m_trackZ0PVKey.initialize() );
+
   ATH_MSG_VERBOSE("initialize() ...");
   return StatusCode::SUCCESS;
 }
@@ -60,14 +54,14 @@ StatusCode DerivationFramework::TrackParametersAtPV::finalize()
 // Augmentation
 StatusCode DerivationFramework::TrackParametersAtPV::addBranches() const
 {
-  std::unique_ptr<std::vector<float> > track_z0_PV(new std::vector<float>());  
+  const EventContext& ctx = Gaudi::Hive::currentContext();
+  SG::WriteHandle< std::vector<float> >track_z0_PV(m_trackZ0PVKey,ctx);
+  ATH_CHECK(track_z0_PV.record(std::make_unique< std::vector<float> >()));
 
   // Get Primary vertex
-  const xAOD::VertexContainer* vertices = 
-    evtStore()->retrieve< const xAOD::VertexContainer >(m_collVertexName);
-    
-  if(!vertices) {
-    ATH_MSG_ERROR ("Couldn't retrieve VertexContainer with key: " << m_collVertexName);
+  SG::ReadHandle<xAOD::VertexContainer> vertices(m_collVertexKey,ctx);
+  if(!vertices.isValid()) {
+    ATH_MSG_ERROR ("Couldn't retrieve VertexContainer with key: " << m_collVertexKey.key());
     return StatusCode::FAILURE;
   }
 
@@ -80,11 +74,9 @@ StatusCode DerivationFramework::TrackParametersAtPV::addBranches() const
   }
 
   // Get the track container
-  const xAOD::TrackParticleContainer* tracks = 
-    evtStore()->retrieve< const xAOD::TrackParticleContainer >(m_collTrackName);
-  
-  if(!tracks) {
-    ATH_MSG_ERROR ("Couldn't retrieve TrackParticleContainer with key: " << m_collTrackName);
+  SG::ReadHandle<xAOD::TrackParticleContainer> tracks(m_collTrackKey,ctx);
+  if(!tracks.isValid()) {
+    ATH_MSG_ERROR ("Couldn't retrieve TrackParticleContainer with key: " << m_collTrackKey.key());
     return StatusCode::FAILURE;
   }
 
@@ -99,14 +91,6 @@ StatusCode DerivationFramework::TrackParametersAtPV::addBranches() const
     }
   }
 
-  // Write decision to SG for access by downstream algs 
-  if (evtStore()->contains<std::vector<float> >(m_sgKey1)) {
-      ATH_MSG_ERROR("Tool is attempting to write StoreGate keys which already exists. Please use a different key");
-      return StatusCode::FAILURE;
-  } else {
-    CHECK(evtStore()->record(std::move(track_z0_PV), m_sgKey1));       
-  }
-
   return StatusCode::SUCCESS;
 }
 
-- 
GitLab


From 2daca2c208f72742feaa565a1427014d13ddfe32 Mon Sep 17 00:00:00 2001
From: Goetz Gaycken <goetz.gaycken@cern.ch>
Date: Mon, 6 Apr 2020 14:18:41 +0200
Subject: [PATCH 19/26] Use truth decoration algorithm rather than
 TrackParametersForTruthParticles tool.

The latter uses a decoration tool which has no implementation anymore. Thus,
it is not functional anymore and has to be replaced.
Remove the non-functional TrackParametersForTruthParticles tool.
---
 .../share/InDetDxAOD.py                       | 17 +++-
 .../TrackParametersForTruthParticles.h        | 62 ---------------
 .../src/TrackParametersForTruthParticles.cxx  | 79 -------------------
 .../DerivationFrameworkInDet_entries.cxx      |  2 -
 4 files changed, 16 insertions(+), 144 deletions(-)
 delete mode 100644 PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/TrackParametersForTruthParticles.h
 delete mode 100644 PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/TrackParametersForTruthParticles.cxx

diff --git a/InnerDetector/InDetEventCnv/InDetPrepRawDataToxAOD/share/InDetDxAOD.py b/InnerDetector/InDetEventCnv/InDetPrepRawDataToxAOD/share/InDetDxAOD.py
index 2da7e9a1d9f3..f24cb1cf383f 100644
--- a/InnerDetector/InDetEventCnv/InDetPrepRawDataToxAOD/share/InDetDxAOD.py
+++ b/InnerDetector/InDetEventCnv/InDetPrepRawDataToxAOD/share/InDetDxAOD.py
@@ -601,7 +601,7 @@ if skimmingExpression:
 
 #minimumbiasTrig = '(L1_RD0_FILLED)'
 #
-#if not IsMonteCarlo:
+#if not DerivationFrameworkIsMonteCarlo:
 #  from DerivationFrameworkTools.DerivationFrameworkToolsConf import DerivationFramework__xAODStringSkimmingTool
 #  TrigSkimmingTool = DerivationFramework__xAODStringSkimmingTool(name = "TrigSkimmingTool", expression = minimumbiasTrig)
 #  ToolSvc += TrigSkimmingTool
@@ -673,6 +673,21 @@ if (printIdTrkDxAODConf):
     print IDDerivationSequence 
     print IDDerivationSequence.properties()
 
+if DerivationFrameworkIsMonteCarlo:
+  # add track parameter decorations to truth particles but only if the decorations have not been applied already
+  import InDetPhysValMonitoring.InDetPhysValDecoration
+  meta_data = InDetPhysValMonitoring.InDetPhysValDecoration.getMetaData()
+  from AthenaCommon.Logging import logging
+  logger = logging.getLogger( "DerivationFramework" )
+  if len(meta_data) == 0 :
+    truth_track_param_decor_alg = InDetPhysValMonitoring.InDetPhysValDecoration.getInDetPhysValTruthDecoratorAlg()
+    if  InDetPhysValMonitoring.InDetPhysValDecoration.findAlg(truth_track_param_decor_alg.getName()) == None :
+      IDDerivationSequence.append( truth_track_param_decor_alg )
+    else :
+      logger.info('Decorator %s already present not adding again.' % (truth_track_param_decor_alg.getName() ))
+  else :
+    logger.info('IDPVM decorations to track particles already applied to input file not adding again.')
+
 #################
 ### Steer output file content
 #################
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/TrackParametersForTruthParticles.h b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/TrackParametersForTruthParticles.h
deleted file mode 100644
index 5bd272732329..000000000000
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/TrackParametersForTruthParticles.h
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
-  Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration
-*/
-
-///////////////////////////////////////////////////////////
-// TrackParametersForTruthParticles.h  (c) ATLAS Detector software
-///////////////////////////////////////////////////////////////////
-
-#ifndef DERIVATIONFRAMEWORK_TrackParametersForTruthParticles_H
-#define DERIVATIONFRAMEWORK_TrackParametersForTruthParticles_H 
-
-#include<string>
-
-// Gaudi & Athena basics
-#include "AthenaBaseComps/AthAlgTool.h"
-
-// DerivationFramework includes
-#include "DerivationFrameworkInterfaces/IAugmentationTool.h"
-#include "GaudiKernel/ToolHandle.h"
-
-class IInDetPhysValDecoratorTool;
-
-namespace DerivationFramework {
-
-  /** @class TrackParametersForTruthParticles
- 
-
-     */
-  class TrackParametersForTruthParticles : public AthAlgTool, public IAugmentationTool {
-   
-  public: 
-    /** Constructor with parameters */
-    TrackParametersForTruthParticles( const std::string& t, const std::string& n, const IInterface* p );
-   
-    /** Destructor */
-    ~TrackParametersForTruthParticles();
-   
-    // Athena algtool's Hooks
-    StatusCode  initialize();
-    StatusCode  finalize();
- 
-    /** Check that the current event passes this filter */
-    virtual StatusCode addBranches() const;
-
-  private:
-    std::string m_collTruthName;
-    std::string m_sgKey1;
-		
-		ToolHandle<IInDetPhysValDecoratorTool> m_decoTool;
-    
-		/**  Pt cut on truth particles to be dressed  [MeV] */
-    float m_ptCut;
-
-    /**  Only dress primary truth particles */
-    bool  m_doPrimary;
-
-
-  }; 
- 
-}
-
-#endif
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/TrackParametersForTruthParticles.cxx b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/TrackParametersForTruthParticles.cxx
deleted file mode 100644
index f2007ba80f0b..000000000000
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/TrackParametersForTruthParticles.cxx
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
-  Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration
-*/
-
-///////////////////////////////////////////////////////////////////
-// TrackParametersForTruthParticles.cxx, (c) ATLAS Detector software
-///////////////////////////////////////////////////////////////////
-// Author: Tomoe Kishimoto (Tomoe.Kishimoto@cern.ch)
-// Wrapper around the passSelection() method of xAOD egamma
-// Writes result to SG for later selection by string parser
-
-#include "DerivationFrameworkInDet/TrackParametersForTruthParticles.h"
-#include "xAODTruth/TruthParticleContainer.h"
-#include <vector>
-#include <string>
-
-#include "InDetPhysValMonitoring/IInDetPhysValDecoratorTool.h"
-
-// Constructor
-DerivationFramework::TrackParametersForTruthParticles::TrackParametersForTruthParticles( const std::string& t,
-                                                 const std::string& n,
-                                                 const IInterface* p ) :
-  AthAlgTool(t,n,p),
-  m_collTruthName("TruthParticles"),
-  m_sgKey1(""),
-  m_decoTool("InDetPhysValTruthDecoratorTool")
-	{
-    declareInterface<DerivationFramework::IAugmentationTool>(this);
-    declareProperty("TruthParticleContainerName", m_collTruthName);
-    declareProperty("DecorationPrefix",m_sgKey1);
-    declareProperty("PtCut",m_ptCut = 400);
-    declareProperty("OnlyDressPrimaryTracks", m_doPrimary = true);
-  }
- 
-// Destructor
-DerivationFramework::TrackParametersForTruthParticles::~TrackParametersForTruthParticles() {
-} 
-
-// Athena initialize and finalize
-StatusCode DerivationFramework::TrackParametersForTruthParticles::initialize()
-{
-  
-  ATH_MSG_VERBOSE("initialize() ...");
-  
-	ATH_CHECK(m_decoTool.retrieve());
-
-	return StatusCode::SUCCESS;
-}
-
-StatusCode DerivationFramework::TrackParametersForTruthParticles::finalize()
-{
-  ATH_MSG_VERBOSE("finalize() ...");
-  return StatusCode::SUCCESS;
-}
-
-// Augmentation
-StatusCode DerivationFramework::TrackParametersForTruthParticles::addBranches() const
-{
-
-  // Get the track container
-  const xAOD::TruthParticleContainer* tracks = 
-    evtStore()->retrieve< const xAOD::TruthParticleContainer >(m_collTruthName);
-  
-  if(!tracks) {
-    ATH_MSG_ERROR ("Couldn't retrieve TrackParticleContainer with key: " << m_collTruthName);
-    return StatusCode::FAILURE;
-  }
-
-  for ( const auto truth: *tracks) {
-		if( truth->status() != 1 || truth->charge() == 0 ) continue;   
-		if( m_doPrimary && truth->barcode() > 200e3 ) continue;
-    if( truth->pt() < m_ptCut ) continue;
-    m_decoTool->decorateTruth(*truth, m_sgKey1);
-	}
-
-
-  return StatusCode::SUCCESS;
-}
-
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/components/DerivationFrameworkInDet_entries.cxx b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/components/DerivationFrameworkInDet_entries.cxx
index 81bcf2aeedb9..68df09c97aae 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/components/DerivationFrameworkInDet_entries.cxx
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/components/DerivationFrameworkInDet_entries.cxx
@@ -15,7 +15,6 @@
 #include "DerivationFrameworkInDet/TrackMeasurementThinning.h"
 #include "DerivationFrameworkInDet/EventInfoPixelDecorator.h"
 #include "DerivationFrameworkInDet/PixelNtupleMaker.h"
-#include "DerivationFrameworkInDet/TrackParametersForTruthParticles.h"
 
 using namespace DerivationFramework;
 
@@ -36,4 +35,3 @@ DECLARE_COMPONENT( EGammaTracksThinning )
 DECLARE_COMPONENT( TrackMeasurementThinning )
 DECLARE_COMPONENT( EventInfoPixelDecorator )
 DECLARE_COMPONENT( PixelNtupleMaker )
-DECLARE_COMPONENT( TrackParametersForTruthParticles ) 
-- 
GitLab


From 5173ca8ca3d6d74f7d0587d716b6c244458fc400 Mon Sep 17 00:00:00 2001
From: Goetz Gaycken <goetz.gaycken@cern.ch>
Date: Tue, 7 Apr 2020 18:30:48 +0200
Subject: [PATCH 20/26] Migrate TrackStateOnSurfaceDecorator to data handles.

---
 .../TrackStateOnSurfaceDecorator.h            |  67 +++-
 .../src/TrackStateOnSurfaceDecorator.cxx      | 352 +++++++++---------
 2 files changed, 230 insertions(+), 189 deletions(-)

diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/TrackStateOnSurfaceDecorator.h b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/TrackStateOnSurfaceDecorator.h
index 086c029dce32..f5cb72085312 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/TrackStateOnSurfaceDecorator.h
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/TrackStateOnSurfaceDecorator.h
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
+  Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 */
 
 ///////////////////////////////////////////////////////////////////
@@ -26,6 +26,13 @@
 #include "TrkToolInterfaces/IUpdator.h"
 #include "InDetReadoutGeometry/SiDetectorElementCollection.h"
 #include "StoreGate/ReadCondHandleKey.h"
+#include "StoreGate/ReadHandleKey.h"
+#include "StoreGate/WriteDecorHandleKey.h"
+
+#include "xAODEventInfo/EventInfo.h"
+#include "xAODTracking/TrackParticleContainer.h"
+#include "xAODTracking/TrackStateValidationContainer.h"
+#include "CommissionEvent/ComTime.h"
 
 class AtlasDetectorID;
 class PixelID;
@@ -68,20 +75,35 @@ namespace DerivationFramework {
       bool    m_addExtraEventInfo;
 
       // --- Configuration keys
-      std::string m_sgName;
-      std::string m_containerName;
-    
-      std::string m_pixelMapName;
-      std::string m_sctMapName;
-      std::string m_trtMapName;
-      
-      std::string m_pixelClustersName;
-      std::string m_sctClustersName;
-      std::string m_trtDCName;      
-      
-      std::string m_pixelMsosName;
-      std::string m_sctMsosName;
-      std::string m_trtMsosName;
+      SG::ReadHandleKey<xAOD::EventInfo> m_eventInfoKey
+        { this, "EventInfoKey", "EventInfo", "" };
+      Gaudi::Property<std::string> m_sgName
+         { this, "DecorationPrefix", "IDDET1_",""};
+      SG::ReadHandleKey<xAOD::TrackParticleContainer> m_containerName
+         { this, "ContainerName", "InDetTrackParticles", "" };
+      SG::ReadHandleKey<ComTime> m_trtPhaseKey
+         { this,"TRTPhaseKey","TRT_Phase", ""};
+
+      SG::ReadHandleKey<std::vector<unsigned int> > m_pixelMapName
+         { this, "PixelMapName", "PixelClustersOffsets" , ""};
+      SG::ReadHandleKey<std::vector<unsigned int> >  m_sctMapName
+         { this, "SctMapName",   "SCT_ClustersOffsets" , ""};
+      SG::ReadHandleKey<std::vector<unsigned int> >  m_trtMapName
+         { this, "TrtMapName",   "TRT_DriftCirclesOffsets" , ""};
+
+      SG::ReadHandleKey<xAOD::TrackMeasurementValidationContainer > m_pixelClustersName
+         {this, "PixelClustersName", "PixelClusters" ,"" };
+      SG::ReadHandleKey<xAOD::TrackMeasurementValidationContainer > m_sctClustersName
+        {this, "SctClustersName", "SCT_Clusters" ,"" };
+      SG::ReadHandleKey<xAOD::TrackMeasurementValidationContainer> m_trtDCName
+         {this, "TrtDriftCirclesName", "TRT_DriftCircles" ,"" };
+
+      SG::WriteHandleKey<xAOD::TrackStateValidationContainer> m_pixelMsosName
+         { this, "PixelMsosName", "PixelMSOSs", "" };
+      SG::WriteHandleKey<xAOD::TrackStateValidationContainer> m_sctMsosName
+         { this, "SctMsosName", "SCT_MSOSs", "" };
+      SG::WriteHandleKey<xAOD::TrackStateValidationContainer> m_trtMsosName
+         { this, "TrtMsosName",  "TRT_MSOSs", ""};
 
       // --- Read Cond Handle Key
       // For P->T converter of SCT_Clusters
@@ -102,6 +124,21 @@ namespace DerivationFramework {
       ToolHandle<ITRT_ToT_dEdx>    m_TRTdEdxTool;
       ToolHandle< Trk::IPRD_AssociationTool >  m_assoTool;
       // --- Private other members
+      std::vector<SG::WriteDecorHandleKey<xAOD::EventInfo> > m_trtPhaseDecorKey;
+      enum ETRTFloatDecor {kTRTdEdxDecor,
+                           kTRTusedHitsDecor,
+                           kTRTdEdx_noHT_divByLDecor,
+                           kTRTusedHits_noHT_divByLDecor,
+                           kNTRTFloatDecor};
+     std::vector<SG::WriteDecorHandleKey<xAOD::TrackParticleContainer> > m_trackTRTFloatDecorKeys;
+     enum EPixFloatDecorKeys {kTrkIBLXDecor, kTrkIBLYDecor, kTrkIBLZDecor,
+                              kTrkBLXDecor,  kTrkBLYDecor,  kTrkBLZDecor,
+                              kTrkL1XDecor,  kTrkL1YDecor,  kTrkL1ZDecor,
+                              kTrkL2XDecor,  kTrkL2YDecor,  kTrkL2ZDecor,
+                              kNPixFloatDecor };
+     std::vector<SG::WriteDecorHandleKey<xAOD::TrackParticleContainer> > m_trackPixFloatDecorKeys;
+
+
   }; 
 }
 
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/TrackStateOnSurfaceDecorator.cxx b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/TrackStateOnSurfaceDecorator.cxx
index 70b342b35673..d70f773b561b 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/TrackStateOnSurfaceDecorator.cxx
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/TrackStateOnSurfaceDecorator.cxx
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
+  Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 */
 
 ///////////////////////////////////////////////////////////////////
@@ -9,7 +9,6 @@
 //
 
 #include "DerivationFrameworkInDet/TrackStateOnSurfaceDecorator.h"
-#include "xAODTracking/TrackParticleContainer.h"
 #include "xAODTracking/TrackMeasurementValidationContainer.h"
 
 #include "xAODTracking/TrackStateValidationContainer.h"
@@ -38,8 +37,6 @@
 
 #include "TRT_ConditionsServices/ITRT_CalDbTool.h"
 
-#include "xAODEventInfo/EventInfo.h"
-#include "CommissionEvent/ComTime.h"
 
 #include "InDetReadoutGeometry/SiDetectorElement.h"
 
@@ -52,6 +49,11 @@
 #include "TRT_ElectronPidTools/ITRT_ToT_dEdx.h"  
 #include "TrkToolInterfaces/IPRD_AssociationTool.h"
 
+#include "StoreGate/ReadHandle.h"
+#include "StoreGate/WriteDecorHandle.h"
+#include "StoreGate/WriteDecorHandleKey.h"
+#include "DerivationFrameworkInDet/DecoratorUtils.h"
+
 #include <vector>
 #include <string>
 
@@ -87,19 +89,6 @@ namespace DerivationFramework {
     declareProperty("AddPRD",                 m_addPRD =true);
     declareProperty("AddExtraEventInfo",      m_addExtraEventInfo=true);
 
-    // --- Configuration keys
-    declareProperty("DecorationPrefix",       m_sgName="IDDET1_");
-    declareProperty("ContainerName",          m_containerName="InDetTrackParticles");
-    declareProperty("PixelMapName",           m_pixelMapName = "PixelClustersOffsets");
-    declareProperty("SctMapName",             m_sctMapName = "SCT_ClustersOffsets");
-    declareProperty("TrtMapName",             m_trtMapName = "TRT_DriftCirclesOffsets");
-    declareProperty("PixelClustersName",      m_pixelClustersName = "PixelClusters");
-    declareProperty("SctClustersName",        m_sctClustersName = "SCT_Clusters");
-    declareProperty("TrtDriftCirclesName",    m_trtDCName = "TRT_DriftCircles");
-    declareProperty("PixelMsosName",          m_pixelMsosName = "PixelMSOSs");
-    declareProperty("SctMsosName",            m_sctMsosName = "SCT_MSOSs");
-    declareProperty("TrtMsosName",            m_trtMsosName = "TRT_MSOSs");
-
     // -- Tools 
     declareProperty("Updator",                m_updator);   
     declareProperty("ResidualPullCalculator", m_residualPullCalculator);
@@ -114,16 +103,18 @@ namespace DerivationFramework {
   {
     ATH_MSG_DEBUG("Initialize");
 
-    if (m_sgName=="") {
+    if (m_sgName.empty()) {
       ATH_MSG_WARNING("No decoration prefix name provided for the output of TrackStateOnSurfaceDecorator!");
     }
     ATH_MSG_DEBUG("Prefix for decoration: " << m_sgName);
-    
-    if (m_containerName=="") {
+
+    ATH_CHECK(m_eventInfoKey.initialize( m_addExtraEventInfo ));
+    if (m_containerName.key().empty()) {
       ATH_MSG_ERROR("No TrackParticle collection provided for TrackStateOnSurfaceDecorator!");
       return StatusCode::FAILURE;
     }
-    ATH_MSG_DEBUG("Input TrackParticle container: " << m_containerName);
+    ATH_MSG_DEBUG("Input TrackParticle container: " << m_containerName.key());
+    ATH_CHECK( m_containerName.initialize() );
 
     // need Atlas id-helpers to identify sub-detectors, take them from detStore
     if (detStore()->retrieve(m_idHelper, "AtlasID").isFailure()) {
@@ -144,34 +135,68 @@ namespace DerivationFramework {
     if( m_storeTRT && detStore()->retrieve(m_trtId,"TRT_ID").isFailure() ){
       ATH_MSG_ERROR("Could not retrieve TRT helper");
       return StatusCode::FAILURE; 
-    } 
-    
-    if( m_storeTRT){
-      CHECK(m_trtcaldbTool.retrieve());
-      CHECK(m_assoTool.retrieve());
     }
 
-    if( m_addPulls ){
-      CHECK(m_updator.retrieve());
-      CHECK(m_residualPullCalculator.retrieve());
-    }
-    
-    if( m_storeHoles ) {
-      CHECK( m_holeSearchTool.retrieve() );
-    }
+    ATH_CHECK( m_trtcaldbTool.retrieve(DisableTool{ !m_storeTRT }));
+    ATH_CHECK( m_assoTool.retrieve(DisableTool{ !m_storeTRT }));
 
-    if ( m_storeTRT && !m_TRTdEdxTool.empty() ) {
-      CHECK( m_TRTdEdxTool.retrieve() );
-    }
+    ATH_CHECK( m_updator.retrieve(DisableTool{ !m_addPulls }));
+    ATH_CHECK( m_residualPullCalculator.retrieve(DisableTool{ !m_addPulls }));
 
-    CHECK(m_extrapolator.retrieve());
+    ATH_CHECK( m_holeSearchTool.retrieve( DisableTool{ !m_storeHoles}) );
+
+    ATH_CHECK( m_TRTdEdxTool.retrieve( DisableTool{!m_storeTRT || m_TRTdEdxTool.empty()}) );
+
+    ATH_CHECK(m_extrapolator.retrieve());
 
-    if ( m_storeTRT && !m_TRTdEdxTool.empty() ) {
-      CHECK( m_TRTdEdxTool.retrieve() );
-	}
 
-    if (m_storeSCT) {
-      CHECK( m_SCTDetEleCollKey.initialize() );
+    ATH_CHECK( m_SCTDetEleCollKey.initialize( m_storeSCT ));
+
+    if (m_addExtraEventInfo) {
+       std::vector<std::string> decor_names{"TrtPhaseTime"};
+       std::vector<SG::WriteDecorHandleKey<xAOD::EventInfo> > decor_key_out;
+       createDecoratorKeys(*this,m_eventInfoKey, m_sgName, decor_names,m_trtPhaseDecorKey);
+       assert(m_trtPhaseDecorKey.size() == 1);
+    }
+    if (m_storeTRT && m_TRTdEdxTool.isEnabled()) {
+       std::vector<std::string> names;
+       names.resize(kNTRTFloatDecor);
+       names[kTRTdEdxDecor]="ToT_dEdx";
+       names[kTRTusedHitsDecor]="ToT_usedHits";
+       names[kTRTdEdx_noHT_divByLDecor]="ToT_dEdx_noHT_divByL";
+       names[kTRTusedHits_noHT_divByLDecor]="ToT_usedHits_noHT_divByL";
+       createDecoratorKeys(*this,m_containerName, m_sgName, names, m_trackTRTFloatDecorKeys);
+    }
+    ATH_CHECK( m_trtPhaseKey.initialize() );
+    ATH_CHECK( m_containerName.initialize() );
+    ATH_CHECK( m_pixelMapName.initialize() );
+    ATH_CHECK( m_sctMapName.initialize() );
+    ATH_CHECK( m_trtMapName.initialize() );
+
+    ATH_CHECK( m_pixelClustersName.initialize() );
+    ATH_CHECK( m_sctClustersName.initialize() );
+    ATH_CHECK( m_trtDCName.initialize() );
+
+    ATH_CHECK( m_pixelMsosName.initialize() );
+    ATH_CHECK( m_sctMsosName.initialize() );
+    ATH_CHECK( m_trtMsosName.initialize() );
+
+    {
+       std::vector<std::string> names;
+       names.resize(kNPixFloatDecor);
+       names[kTrkIBLXDecor]="TrkIBLX";
+       names[kTrkIBLYDecor]="TrkIBLY";
+       names[kTrkIBLZDecor]="TrkIBLZ";
+       names[kTrkBLXDecor]="TrkBLX";
+       names[kTrkBLYDecor]="TrkBLY";
+       names[kTrkBLZDecor]="TrkBLZ";
+       names[kTrkL1XDecor]="TrkL1X";
+       names[kTrkL1YDecor]="TrkL1Y";
+       names[kTrkL1ZDecor]="TrkL1Z";
+       names[kTrkL2XDecor]="TrkL2X";
+       names[kTrkL2YDecor]="TrkL2Y";
+       names[kTrkL2ZDecor]="TrkL2Z";
+       createDecoratorKeys(*this,m_containerName, m_sgName, names, m_trackPixFloatDecorKeys);
     }
 
     ATH_MSG_DEBUG("Initialization finished.");
@@ -187,33 +212,32 @@ namespace DerivationFramework {
 
   StatusCode TrackStateOnSurfaceDecorator::addBranches() const
   {
+    const EventContext& ctx = Gaudi::Hive::currentContext();
     ATH_MSG_DEBUG("Adding TSOS decorations the track particles");
 
     static SG::AuxElement::Decorator< std::vector< ElementLink< xAOD::TrackStateValidationContainer > > >  dectsos_msosLink(m_sgName+"msosLink");
 
- 
     // --- Retrieve track container (absolutely needed for decoration)
-    const xAOD::TrackParticleContainer* tracks=0;
-    CHECK( evtStore()->retrieve( tracks, m_containerName ) );
-    if( ! tracks ) {
-        ATH_MSG_ERROR ("Couldn't retrieve TrackParticles with key: " << m_containerName );
+    SG::ReadHandle<xAOD::TrackParticleContainer> tracks(m_containerName,ctx);
+    if( ! tracks.isValid() ) {
+        ATH_MSG_ERROR ("Couldn't retrieve TrackParticles with key: " << m_containerName.key() );
         return StatusCode::FAILURE;
     }
     
     
-    const std::vector<unsigned int>*  pixelClusterOffsets(0);
-    const std::vector<unsigned int>*  sctClusterOffsets(0);
-    const std::vector<unsigned int>*  trtClusterOffsets(0);
+    SG::ReadHandle<std::vector<unsigned int> > pixelClusterOffsets;
+    SG::ReadHandle<std::vector<unsigned int> > sctClusterOffsets;
+    SG::ReadHandle<std::vector<unsigned int> > trtDCOffsets;
     
-    const xAOD::TrackMeasurementValidationContainer* pixelClusters(0);
-    const xAOD::TrackMeasurementValidationContainer* sctClusters(0);
-    const xAOD::TrackMeasurementValidationContainer* trtDCs(0);
+    SG::ReadHandle<xAOD::TrackMeasurementValidationContainer> pixelClusters;
+    SG::ReadHandle<xAOD::TrackMeasurementValidationContainer> sctClusters;
+    SG::ReadHandle<xAOD::TrackMeasurementValidationContainer> trtDCs;
  
     
     // Create the xAOD container and its auxiliary store
-    xAOD::TrackStateValidationContainer*    msosPixel=0; 
-    xAOD::TrackStateValidationContainer*    msosSCT=0; 
-    xAOD::TrackStateValidationContainer*    msosTRT=0;
+    SG::WriteHandle<xAOD::TrackStateValidationContainer>    msosPixel;
+    SG::WriteHandle<xAOD::TrackStateValidationContainer>    msosSCT;
+    SG::WriteHandle<xAOD::TrackStateValidationContainer>    msosTRT;
 
     int nPixelMSOS(0);
     int nSCT_MSOS(0);
@@ -222,68 +246,73 @@ namespace DerivationFramework {
     // --- Add event-level information
     if (m_addExtraEventInfo) {
       ATH_MSG_DEBUG("Adding EventInfo decorations");
-      const xAOD::EventInfo* eventInfo = 0;
-      if (evtStore()->retrieve(eventInfo).isFailure()) {
+      SG::ReadHandle<xAOD::EventInfo> eventInfo(m_eventInfoKey,ctx);
+      if (!eventInfo.isValid()) {
         ATH_MSG_ERROR(" Cannot access to event info.");
         return StatusCode::FAILURE;
       }
 
       //Add TRT event phase
-      const ComTime *trtPhase = 0;
-      float trtPhase_time=0.0;
-      if ( evtStore()->contains<ComTime>("TRT_Phase") ){
-        StatusCode sc = evtStore()->retrieve(trtPhase, "TRT_Phase");  
-        if (sc.isFailure() || !trtPhase) {
-          //do not throw errors, since it could not be there
-          ATH_MSG_DEBUG("Failed to retrieve TRT phase information.");
-        } else {
-          trtPhase_time = trtPhase->getTime();
-        } 
+      SG::ReadHandle<ComTime> trtPhase(m_trtPhaseKey, ctx);
+      float trtPhase_time=0.;
+      if (!trtPhase.isValid()) {
+         ATH_MSG_DEBUG("Failed to retrieve TRT phase information.");
+      } else {
+         trtPhase_time = trtPhase->getTime();
       } //TRT phase
-      eventInfo->auxdecor<float>(m_sgName+"TrtPhaseTime") = trtPhase_time;
-      
+      SG::WriteDecorHandle<xAOD::EventInfo,float> decorTRTPhase(*(m_trtPhaseDecorKey.begin()),ctx);
+      decorTRTPhase(*eventInfo) = trtPhase_time;
     } //extra event info
 
-    
+
     // --- Add track states containers
     if(m_addPRD){
       // Get clusters and the mapping between xAOD::PRD and Trk::PRD
       // Store the MSOS's in a conatiner based on the type of the detector 
       if(m_storePixel){
         ATH_MSG_DEBUG("Creating Pixel track state container");
-        CHECK( evtStore()->retrieve( pixelClusterOffsets, m_pixelMapName ) );
-        CHECK( evtStore()->retrieve( pixelClusters, m_pixelClustersName ) );
-      
-        msosPixel = new xAOD::TrackStateValidationContainer();
-        xAOD::TrackStateValidationAuxContainer* aux = new xAOD::TrackStateValidationAuxContainer();
-        CHECK( evtStore()->record( msosPixel, m_pixelMsosName ) );
-        CHECK( evtStore()->record( aux, m_pixelMsosName + "Aux." ) );
-        msosPixel->setStore( aux );
+        pixelClusterOffsets=SG::ReadHandle<std::vector<unsigned int> >(m_pixelMapName,ctx);
+        pixelClusters=SG::ReadHandle<xAOD::TrackMeasurementValidationContainer >(m_pixelClustersName,ctx);
+
+        msosPixel = SG::WriteHandle<xAOD::TrackStateValidationContainer>(m_pixelMsosName,ctx);
+        if (msosPixel.record(std::make_unique<xAOD::TrackStateValidationContainer>(),
+                             std::make_unique<xAOD::TrackStateValidationAuxContainer>()).isFailure()) {
+           ATH_MSG_ERROR("Failed to record " << m_pixelMsosName.key() );
+           return StatusCode::FAILURE;
+        }
       }
       if(m_storeSCT){
         ATH_MSG_DEBUG("Creating SCT track state container");
-        CHECK( evtStore()->retrieve( sctClusterOffsets, m_sctMapName ) );
-        CHECK( evtStore()->retrieve( sctClusters, m_sctClustersName ) );
-
-        msosSCT = new xAOD::TrackStateValidationContainer();
-        xAOD::TrackStateValidationAuxContainer* aux = new xAOD::TrackStateValidationAuxContainer();
-        CHECK( evtStore()->record( msosSCT, m_sctMsosName ) );
-        CHECK( evtStore()->record( aux, m_sctMsosName + "Aux." ) );
-        msosSCT->setStore( aux );
+        sctClusterOffsets=SG::ReadHandle<std::vector<unsigned int> >(m_sctMapName,ctx);
+        sctClusters=SG::ReadHandle<xAOD::TrackMeasurementValidationContainer >(m_sctClustersName,ctx);
+
+        msosSCT = SG::WriteHandle<xAOD::TrackStateValidationContainer>(m_sctMsosName,ctx);
+        if (msosSCT.record(std::make_unique<xAOD::TrackStateValidationContainer>(),
+                             std::make_unique<xAOD::TrackStateValidationAuxContainer>()).isFailure()) {
+           ATH_MSG_ERROR("Failed to record " << m_sctMsosName.key() );
+           return StatusCode::FAILURE;
+        }
       }
       if(m_storeTRT){
         ATH_MSG_DEBUG("Creating TRT track state container");
-        CHECK( evtStore()->retrieve( trtClusterOffsets, m_trtMapName ) );    
-        CHECK( evtStore()->retrieve( trtDCs, m_trtDCName ) );
-
-        msosTRT = new xAOD::TrackStateValidationContainer();
-        xAOD::TrackStateValidationAuxContainer* aux = new xAOD::TrackStateValidationAuxContainer();
-        CHECK( evtStore()->record( msosTRT, m_trtMsosName ) );
-        CHECK( evtStore()->record( aux, m_trtMsosName + "Aux." ) );
-        msosTRT->setStore( aux );
+        trtDCOffsets=SG::ReadHandle<std::vector<unsigned int> >(m_trtMapName,ctx);
+        trtDCs=SG::ReadHandle<xAOD::TrackMeasurementValidationContainer >(m_trtDCName,ctx);
+
+        msosTRT = SG::WriteHandle<xAOD::TrackStateValidationContainer>(m_trtMsosName,ctx);
+        if (msosTRT.record(std::make_unique<xAOD::TrackStateValidationContainer>(),
+                             std::make_unique<xAOD::TrackStateValidationAuxContainer>()).isFailure()) {
+           ATH_MSG_ERROR("Failed to record " << m_trtMsosName.key() );
+           return StatusCode::FAILURE;
+        }
       }
     }
 
+    std::vector<SG::WriteDecorHandle<xAOD::TrackParticleContainer,float> > trackTRTFloatDecorators;
+    if (m_storeTRT && m_TRTdEdxTool.isEnabled()) {
+       trackTRTFloatDecorators = createDecorators<xAOD::TrackParticleContainer,float>(m_trackTRTFloatDecorKeys,ctx);
+    }
+    std::vector<SG::WriteDecorHandle<xAOD::TrackParticleContainer,float> >
+       trackPixFloatDecorators = createDecorators<xAOD::TrackParticleContainer,float>(m_trackPixFloatDecorKeys,ctx);
     // -- Run over each track and decorate it
     for (const auto& track : *tracks) {
       //-- Start with things that do not need a Trk::Track object
@@ -301,21 +330,21 @@ namespace DerivationFramework {
       //  This is the vector in which we will store the element links to the MSOS's
       std::vector< ElementLink< xAOD::TrackStateValidationContainer > > msosLink;
 
-      if ( m_storeTRT && !m_TRTdEdxTool.empty() ) {
+      if ( m_storeTRT && m_TRTdEdxTool.isEnabled() ) {
 	// for dEdx studies
-	SG::AuxElement::Decorator< float > decoratorTRTdEdx("ToT_dEdx");
-	SG::AuxElement::Decorator< float > decoratorTRTusedHits("ToT_usedHits");    
-	SG::AuxElement::Decorator< float > decoratorTRTdEdx_noHT_divByL("ToT_dEdx_noHT_divByL");
-	SG::AuxElement::Decorator< float > decoratorTRTusedHits_noHT_divByL("ToT_usedHits_noHT_divByL");    
-	
-        decoratorTRTdEdx (*track)     = m_TRTdEdxTool->dEdx( trkTrack, true, true, true);
-        decoratorTRTusedHits (*track) = m_TRTdEdxTool->usedHits( trkTrack, true, true);
-        decoratorTRTdEdx_noHT_divByL (*track)     = m_TRTdEdxTool->dEdx( trkTrack, true, false, true);
-        decoratorTRTusedHits_noHT_divByL (*track) = m_TRTdEdxTool->usedHits( trkTrack, true, false);
+        trackTRTFloatDecorators[kTRTdEdxDecor] (*track)                 = m_TRTdEdxTool->dEdx( trkTrack, true, true, true);
+        trackTRTFloatDecorators[kTRTusedHitsDecor] (*track)             = m_TRTdEdxTool->usedHits( trkTrack, true, true);
+        trackTRTFloatDecorators[kTRTdEdx_noHT_divByLDecor] (*track)     = m_TRTdEdxTool->dEdx( trkTrack, true, false, true);
+        trackTRTFloatDecorators[kTRTusedHits_noHT_divByLDecor] (*track) = m_TRTdEdxTool->usedHits( trkTrack, true, false);
       }
 
       // Track extrapolation
-      std::unique_ptr<const Trk::TrackParameters> perigee( m_extrapolator->extrapolate(*trkTrack,(trkTrack->perigeeParameters())->associatedSurface(),Trk::oppositeMomentum,true, Trk::pion, Trk::addNoise));
+      std::unique_ptr<const Trk::TrackParameters> perigee( m_extrapolator->extrapolate(*trkTrack,
+                                                                                       (trkTrack->perigeeParameters())->associatedSurface(),
+                                                                                       Trk::oppositeMomentum,
+                                                                                       true,
+                                                                                       Trk::pion,
+                                                                                       Trk::addNoise));
 
       Trk::CylinderSurface cylSurfIBL(29.5,3000.0);
       Trk::CylinderSurface cylSurfBL(50.5,3000.0);
@@ -326,79 +355,51 @@ namespace DerivationFramework {
       std::unique_ptr<const Trk::TrackParameters> outputParamsL1(m_extrapolator->extrapolate(*perigee,cylSurfL1,Trk::alongMomentum,true,Trk::pion,Trk::removeNoise));
       std::unique_ptr<const Trk::TrackParameters> outputParamsL2(m_extrapolator->extrapolate(*perigee,cylSurfL2,Trk::alongMomentum,true,Trk::pion,Trk::removeNoise));
 
-      SG::AuxElement::Decorator<float> decoratorTrkIBLX("TrkIBLX");
-      SG::AuxElement::Decorator<float> decoratorTrkIBLY("TrkIBLY");
-      SG::AuxElement::Decorator<float> decoratorTrkIBLZ("TrkIBLZ");
       if (outputParamsIBL.get()) {
-        decoratorTrkIBLX(*track) = outputParamsIBL->position().x();
-        decoratorTrkIBLY(*track) = outputParamsIBL->position().y();
-        decoratorTrkIBLZ(*track) = outputParamsIBL->position().z();
+        trackPixFloatDecorators[kTrkIBLXDecor](*track) = outputParamsIBL->position().x();
+        trackPixFloatDecorators[kTrkIBLYDecor](*track) = outputParamsIBL->position().y();
+        trackPixFloatDecorators[kTrkIBLZDecor](*track) = outputParamsIBL->position().z();
       }
       else {
-        decoratorTrkIBLX(*track) = 0.0;
-        decoratorTrkIBLY(*track) = 0.0;
-        decoratorTrkIBLZ(*track) = 0.0;
+         trackPixFloatDecorators[kTrkIBLXDecor](*track) = 0.0;
+         trackPixFloatDecorators[kTrkIBLYDecor](*track) = 0.0;
+         trackPixFloatDecorators[kTrkIBLZDecor](*track) = 0.0;
       }
 
-      SG::AuxElement::Decorator<float> decoratorTrkBLX("TrkBLX");
-      SG::AuxElement::Decorator<float> decoratorTrkBLY("TrkBLY");
-      SG::AuxElement::Decorator<float> decoratorTrkBLZ("TrkBLZ");
       if (outputParamsBL.get()) {
-        decoratorTrkBLX(*track) = outputParamsBL->position().x();
-        decoratorTrkBLY(*track) = outputParamsBL->position().y();
-        decoratorTrkBLZ(*track) = outputParamsBL->position().z();
+        trackPixFloatDecorators[kTrkBLXDecor](*track) = outputParamsBL->position().x();
+        trackPixFloatDecorators[kTrkBLYDecor](*track) = outputParamsBL->position().y();
+        trackPixFloatDecorators[kTrkBLZDecor](*track) = outputParamsBL->position().z();
       }
       else {
-        decoratorTrkBLX(*track) = 0.0;
-        decoratorTrkBLY(*track) = 0.0;
-        decoratorTrkBLZ(*track) = 0.0;
+        trackPixFloatDecorators[kTrkBLXDecor](*track) = 0.0;
+        trackPixFloatDecorators[kTrkBLYDecor](*track) = 0.0;
+        trackPixFloatDecorators[kTrkBLZDecor](*track) = 0.0;
       }
 
-      SG::AuxElement::Decorator<float> decoratorTrkL1X("TrkL1X");
-      SG::AuxElement::Decorator<float> decoratorTrkL1Y("TrkL1Y");
-      SG::AuxElement::Decorator<float> decoratorTrkL1Z("TrkL1Z");
       if (outputParamsL1.get()) {
-        decoratorTrkL1X(*track) = outputParamsL1->position().x();
-        decoratorTrkL1Y(*track) = outputParamsL1->position().y();
-        decoratorTrkL1Z(*track) = outputParamsL1->position().z();
+        trackPixFloatDecorators[kTrkL1XDecor](*track) = outputParamsL1->position().x();
+        trackPixFloatDecorators[kTrkL1YDecor](*track) = outputParamsL1->position().y();
+        trackPixFloatDecorators[kTrkL1ZDecor](*track) = outputParamsL1->position().z();
       }
       else {
-        decoratorTrkL1X(*track) = 0.0;
-        decoratorTrkL1Y(*track) = 0.0;
-        decoratorTrkL1Z(*track) = 0.0;
+        trackPixFloatDecorators[kTrkL1XDecor](*track) = 0.0;
+        trackPixFloatDecorators[kTrkL1YDecor](*track) = 0.0;
+        trackPixFloatDecorators[kTrkL1ZDecor](*track) = 0.0;
       }
 
-      SG::AuxElement::Decorator<float> decoratorTrkL2X("TrkL2X");
-      SG::AuxElement::Decorator<float> decoratorTrkL2Y("TrkL2Y");
-      SG::AuxElement::Decorator<float> decoratorTrkL2Z("TrkL2Z");
       if (outputParamsL2.get()) {
-        decoratorTrkL2X(*track) = outputParamsL2->position().x();
-        decoratorTrkL2Y(*track) = outputParamsL2->position().y();
-        decoratorTrkL2Z(*track) = outputParamsL2->position().z();
+        trackPixFloatDecorators[kTrkL2XDecor](*track) = outputParamsL2->position().x();
+        trackPixFloatDecorators[kTrkL2YDecor](*track) = outputParamsL2->position().y();
+        trackPixFloatDecorators[kTrkL2ZDecor](*track) = outputParamsL2->position().z();
       }
       else {
-        decoratorTrkL2X(*track) = 0.0;
-        decoratorTrkL2Y(*track) = 0.0;
-        decoratorTrkL2Z(*track) = 0.0;
+        trackPixFloatDecorators[kTrkL2XDecor](*track) = 0.0;
+        trackPixFloatDecorators[kTrkL2YDecor](*track) = 0.0;
+        trackPixFloatDecorators[kTrkL2ZDecor](*track) = 0.0;
       }
 
 
-
-      
-
-      if ( m_storeTRT && !m_TRTdEdxTool.empty() ) {
-	// for dEdx studies
-	SG::AuxElement::Decorator< float > decoratorTRTdEdx("ToT_dEdx");
-	SG::AuxElement::Decorator< float > decoratorTRTusedHits("ToT_usedHits");    
-	SG::AuxElement::Decorator< float > decoratorTRTdEdx_noHT_divByL("ToT_dEdx_noHT_divByL");
-	SG::AuxElement::Decorator< float > decoratorTRTusedHits_noHT_divByL("ToT_usedHits_noHT_divByL");    
-
-	decoratorTRTdEdx (*track)     = m_TRTdEdxTool->dEdx( trkTrack, true, true, true);
-	decoratorTRTusedHits (*track) = m_TRTdEdxTool->usedHits( trkTrack, true, true);
-	decoratorTRTdEdx_noHT_divByL (*track)     = m_TRTdEdxTool->dEdx( trkTrack, true, false, true);
-	decoratorTRTusedHits_noHT_divByL (*track) = m_TRTdEdxTool->usedHits( trkTrack, true, false);
-      }
-
       // -- Add Track states to the current track, filtering on their type
       std::vector<const Trk::TrackStateOnSurface*> tsoss;
       for (const auto& trackState: *(trkTrack->trackStateOnSurfaces())){
@@ -510,6 +511,11 @@ namespace DerivationFramework {
           msosLink.push_back(elink);
           ++nPixelMSOS;
         }
+        else {
+           ATH_MSG_WARNING("NOT a pixel, SCT or TRT track state on surface.");
+           delete msos;
+           continue;
+        }
 
         //fill type
         if( trackState->types()[Trk::TrackStateOnSurface::Hole] ){   
@@ -657,11 +663,11 @@ namespace DerivationFramework {
           const Trk::PrepRawData* prd = hit->prepRawData();
           if(prd && prd->getHashAndIndex().isValid() ){            
             if(isTRT){
-              msos->setTrackMeasurementValidationLink( buildElementLink( prd, trtClusterOffsets, trtDCs) );
+              msos->setTrackMeasurementValidationLink( buildElementLink( prd, trtDCOffsets.cptr(), trtDCs.cptr()) );
             }else if(isSCT){
-              msos->setTrackMeasurementValidationLink( buildElementLink( prd, sctClusterOffsets, sctClusters) );
+              msos->setTrackMeasurementValidationLink( buildElementLink( prd, sctClusterOffsets.cptr(), sctClusters.cptr()) );
             }else if(isPixel){
-              msos->setTrackMeasurementValidationLink( buildElementLink( prd, pixelClusterOffsets, pixelClusters) );
+              msos->setTrackMeasurementValidationLink( buildElementLink( prd, pixelClusterOffsets.cptr(), pixelClusters.cptr()) );
             }
           } 
         }
@@ -705,24 +711,24 @@ namespace DerivationFramework {
 
         if (m_addPulls) {
 
-          const Trk::ResidualPull *biased = 0;
-          const Trk::ResidualPull *unbiased = 0;
+          std::unique_ptr<const Trk::ResidualPull> biased;
+          std::unique_ptr<const Trk::ResidualPull> unbiased;
           if (tp) { 
-            biased   = m_residualPullCalculator->residualPull(measurement, tp, Trk::ResidualPull::Biased);
+            biased.reset(m_residualPullCalculator->residualPull(measurement, tp, Trk::ResidualPull::Biased));
 	    if (m_storeTRT) msos->auxdata<float>("TrackError_biased") = sqrt(fabs((*tp->covariance())(Trk::locX,Trk::locX)));
 
 	    if (m_storeTRT) msos->auxdata<float>("TrackError_biased") = sqrt(fabs((*tp->covariance())(Trk::locX,Trk::locX)));
-            std::unique_ptr<const Trk::TrackParameters> unbiasedTp( m_updator->removeFromState(*tp, measurement->localParameters(), measurement->localCovariance()) );   
-	      if(unbiasedTp.get()) {
-	      if (m_storeTRT) msos->auxdata<float>("TrackError_unbiased") = sqrt(fabs((*unbiasedTp.get()->covariance())(Trk::locX,Trk::locX)));
-		unbiased = m_residualPullCalculator->residualPull(measurement, unbiasedTp.get(), Trk::ResidualPull::Unbiased);
-		  }
+            std::unique_ptr<const Trk::TrackParameters> unbiasedTp( m_updator->removeFromState(*tp, measurement->localParameters(), measurement->localCovariance()) );
+            if(unbiasedTp.get()) {
+               if (m_storeTRT) msos->auxdata<float>("TrackError_unbiased") = sqrt(fabs((*unbiasedTp.get()->covariance())(Trk::locX,Trk::locX)));
+               unbiased.reset(m_residualPullCalculator->residualPull(measurement, unbiasedTp.get(), Trk::ResidualPull::Unbiased));
+            }
           }
           else {
             if (extrap.get()) {
 	      if (m_storeTRT) msos->auxdata<float>("TrackError_unbiased") = sqrt(fabs((*extrap.get()->covariance())(Trk::locX,Trk::locX)));
-              biased   = m_residualPullCalculator->residualPull(measurement, extrap.get(), Trk::ResidualPull::Biased);
-              unbiased = m_residualPullCalculator->residualPull(measurement, extrap.get(), Trk::ResidualPull::Unbiased);
+              biased.reset(m_residualPullCalculator->residualPull(measurement, extrap.get(), Trk::ResidualPull::Biased));
+              unbiased.reset(m_residualPullCalculator->residualPull(measurement, extrap.get(), Trk::ResidualPull::Unbiased));
             }
           }
 
@@ -734,7 +740,6 @@ namespace DerivationFramework {
               msos->setBiasedResidual( biased->residual()[Trk::locX], 0 );
               msos->setBiasedPull( biased->pull()[Trk::locX], 0 );            
             }
-            delete biased;
           } 
 
           if (unbiased) {
@@ -745,7 +750,6 @@ namespace DerivationFramework {
               msos->setUnbiasedResidual( unbiased->residual()[Trk::locX], 0 );
               msos->setUnbiasedPull( unbiased->pull()[Trk::locX], 0 );            
             }
-            delete unbiased;
           }
 
         }
-- 
GitLab


From 4ce115f0a3dacac0f4a8247a7aa625753fb2df08 Mon Sep 17 00:00:00 2001
From: Goetz Gaycken <goetz.gaycken@cern.ch>
Date: Wed, 8 Apr 2020 14:46:44 +0200
Subject: [PATCH 21/26] Replace deprecated PRD association tool by
 PRDtoTrackMap.

The map is needed for to create decorations for the combined track.
This maps is already created during reconstruction but also has to be
recorded to StoreGate to be available by the decorator. In case the
decorations are applied starting from an ESD the PRD association map
has to be recreated. The latter is needed for IDTRKVALID with
dumpTrtInfo enabled.

Also configure the TRT_ToT_dEdx tool which is needed by the TSOS decorator
rather then relying on this tool being configured elsewhere in the
job.
---
 .../share/InDetDxAOD.py                       | 31 ++++++++-----------
 .../InDetPrepRawDataToxAOD/share/PixelxAOD.py |  3 +-
 .../InDetPrepRawDataToxAOD/share/SCTxAOD.py   |  2 +-
 .../share/InDetRec_jobOptions.py              |  2 +-
 .../TrackStateOnSurfaceDecorator.h            |  7 ++++-
 .../src/TrackStateOnSurfaceDecorator.cxx      | 30 ++++++++++++------
 6 files changed, 42 insertions(+), 33 deletions(-)

diff --git a/InnerDetector/InDetEventCnv/InDetPrepRawDataToxAOD/share/InDetDxAOD.py b/InnerDetector/InDetEventCnv/InDetPrepRawDataToxAOD/share/InDetDxAOD.py
index f24cb1cf383f..23081f58832e 100644
--- a/InnerDetector/InDetEventCnv/InDetPrepRawDataToxAOD/share/InDetDxAOD.py
+++ b/InnerDetector/InDetEventCnv/InDetPrepRawDataToxAOD/share/InDetDxAOD.py
@@ -379,29 +379,23 @@ if dumpTrtInfo:
     TRT_dEdx_Tool.TRT_LocalOccupancyTool    = getInDetTRT_LocalOccupancy()
     ToolSvc += TRT_dEdx_Tool
 
-    # to get shared hit info
-    from InDetAssociationTools.InDetAssociationToolsConf import InDet__InDetPRD_AssociationToolGangedPixels
-    InDetPrdAssociationTool = InDet__InDetPRD_AssociationToolGangedPixels(name                           = "InDetPrdAssociationTool",
-                                                                          PixelClusterAmbiguitiesMapName = InDetKeys.GangedPixelMap(),
-                                                                          addTRToutliers                 = True,
-                                                                          OutputLevel=INFO
-                                                                          )
-    print InDetPrdAssociationTool
-    ToolSvc += InDetPrdAssociationTool
     TrackCollectionKeys = []
 
     from InDetRecExample.ConfiguredNewTrackingCuts import ConfiguredNewTrackingCuts
     InDetNewTrackingCutsPixel = ConfiguredNewTrackingCuts("Pixel")
     print InDetNewTrackingCutsPixel
 
-    from InDetTrackPRD_Association.InDetTrackPRD_AssociationConf import InDet__InDetTrackPRD_Association
-    InDetPRD_Association = InDet__InDetTrackPRD_Association(name            = 'InDetPRD_Association'+InDetNewTrackingCutsPixel.extension(),
-                                                            AssociationTool = InDetPrdAssociationTool,
-                                                            TracksName = ['Tracks'],
-                                                            OutputLevel=INFO
-                                                            )
-    topSequence += InDetPRD_Association
-    print InDetPRD_Association
+    if not hasattr(topSequence,'InDetTrackCollectionMerger') :
+        from InDetRecExample import TrackingCommon
+        from InDetTrackPRD_Association.InDetTrackPRD_AssociationConf import InDet__InDetTrackPRD_Association
+        InDetPRD_Association = InDet__InDetTrackPRD_Association(name            = 'InDetPRD_Association'+InDetNewTrackingCutsPixel.extension(),
+                                                                AssociationTool = TrackingCommon.getInDetPRDtoTrackMapToolGangedPixels(),
+                                                                TracksName = ['Tracks'],
+                                                                AssociationMapName = "PRDtoTrackMap" + InDetKeys.UnslimmedTracks(),
+                                                                OutputLevel=INFO
+        )
+        topSequence += InDetPRD_Association
+        print InDetPRD_Association
 
 if dumpSctInfo:
     from InDetPrepRawDataToxAOD.InDetPrepRawDataToxAODConf import SCT_PrepDataToxAOD
@@ -495,7 +489,7 @@ DFTSOS = DerivationFramework__TrackStateOnSurfaceDecorator(name = "DFTrackStateO
                                                           StoreSCT   = dumpSctInfo,
                                                           StorePixel = dumpPixInfo,
                                                           IsSimulation = isIdTrkDxAODSimulation,
-                                                          AssociationTool = InDetPrdAssociationTool,
+                                                          PRDtoTrackMap= "PRDtoTrackMap" + InDetKeys.UnslimmedTracks(),
                                                           TRT_ToT_dEdx = TrackingCommon.getInDetTRT_dEdxTool() if dumpTrtInfo else "",
                                                           OutputLevel = INFO)
 
@@ -521,6 +515,7 @@ if makeSplitTracks:
                                                           StorePixel = dumpPixInfo,
                                                           PixelMsosName = 'Pixel_SplitTracks_MSOSs',
                                                           IsSimulation = isIdTrkDxAODSimulation,
+                                                          PRDtoTrackMap= "PRDtoTrackMap" + InDetKeys.UnslimmedTracks(),
                                                           TRT_ToT_dEdx = TrackingCommon.getInDetTRT_dEdxTool() if dumpTrtInfo else "",
                                                           OutputLevel = INFO)
     ToolSvc += DFTSOS_SplitTracks
diff --git a/InnerDetector/InDetEventCnv/InDetPrepRawDataToxAOD/share/PixelxAOD.py b/InnerDetector/InDetEventCnv/InDetPrepRawDataToxAOD/share/PixelxAOD.py
index 36456ead68aa..6fbbbde4f223 100644
--- a/InnerDetector/InDetEventCnv/InDetPrepRawDataToxAOD/share/PixelxAOD.py
+++ b/InnerDetector/InDetEventCnv/InDetPrepRawDataToxAOD/share/PixelxAOD.py
@@ -130,8 +130,7 @@ DFTSOS = DerivationFramework__TrackStateOnSurfaceDecorator(name = "DFTrackStateO
                                                           StoreSCT   = False,
                                                           StorePixel = True,
                                                           IsSimulation = isIdTrkDxAODSimulation,
-                                                          AssociationTool = InDetPrdAssociationTool,
-                                                          TRT_ToT_dEdx = TrackingCommon.getInDetTRT_dEdxTool(),
+                                                          PRDtoTrackMap= "",
                                                           OutputLevel = INFO)
 
 ToolSvc += DFTSOS
diff --git a/InnerDetector/InDetEventCnv/InDetPrepRawDataToxAOD/share/SCTxAOD.py b/InnerDetector/InDetEventCnv/InDetPrepRawDataToxAOD/share/SCTxAOD.py
index 63202c22f355..6c190802c5c7 100644
--- a/InnerDetector/InDetEventCnv/InDetPrepRawDataToxAOD/share/SCTxAOD.py
+++ b/InnerDetector/InDetEventCnv/InDetPrepRawDataToxAOD/share/SCTxAOD.py
@@ -116,7 +116,7 @@ if not InDetFlags.disableTracking():
                                                                StoreSCT   = True,
                                                                StorePixel = False,
                                                                IsSimulation = isSctDxAODSimulation,
-                                                               TRT_ToT_dEdx = TrackingCommon.getInDetTRT_dEdxTool(),
+                                                               PRDtoTrackMap= "",
                                                                OutputLevel = INFO)
     ToolSvc += DFTSOS
     augmentationTools+=[DFTSOS]
diff --git a/InnerDetector/InDetExample/InDetRecExample/share/InDetRec_jobOptions.py b/InnerDetector/InDetExample/InDetRecExample/share/InDetRec_jobOptions.py
index 5caca66e1224..40b0a02531d7 100755
--- a/InnerDetector/InDetExample/InDetRecExample/share/InDetRec_jobOptions.py
+++ b/InnerDetector/InDetExample/InDetRecExample/share/InDetRec_jobOptions.py
@@ -994,7 +994,7 @@ else:
                                                               TracksLocation          = InputCombinedInDetTracks,
                                                               OutputTracksLocation    = InDetKeys.UnslimmedTracks(),
                                                               AssociationTool         = getInDetPRDtoTrackMapToolGangedPixels(),
-                                                              AssociationMapName      = "" if not InDetFlags.doCosmics() else ("PRDtoTrackMap" + InDetKeys.UnslimmedTracks()),
+                                                              AssociationMapName      = "PRDtoTrackMap" + InDetKeys.UnslimmedTracks(),
                                                               UpdateSharedHitsOnly    = False,
                                                               UpdateAdditionalInfo    = True,
                                                               SummaryTool             = TrackingCommon.getInDetTrackSummaryToolSharedHits())
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/TrackStateOnSurfaceDecorator.h b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/TrackStateOnSurfaceDecorator.h
index f5cb72085312..1257ec2e83a2 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/TrackStateOnSurfaceDecorator.h
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/TrackStateOnSurfaceDecorator.h
@@ -34,6 +34,8 @@
 #include "xAODTracking/TrackStateValidationContainer.h"
 #include "CommissionEvent/ComTime.h"
 
+#include "TrkEventUtils/PRDtoTrackMap.h"
+
 class AtlasDetectorID;
 class PixelID;
 class SCT_ID;
@@ -98,6 +100,9 @@ namespace DerivationFramework {
       SG::ReadHandleKey<xAOD::TrackMeasurementValidationContainer> m_trtDCName
          {this, "TrtDriftCirclesName", "TRT_DriftCircles" ,"" };
 
+      SG::ReadHandleKey<Trk::PRDtoTrackMap> m_prdToTrackMap
+         { this,"PRDtoTrackMap","","option PRD-to-track association"};
+
       SG::WriteHandleKey<xAOD::TrackStateValidationContainer> m_pixelMsosName
          { this, "PixelMsosName", "PixelMSOSs", "" };
       SG::WriteHandleKey<xAOD::TrackStateValidationContainer> m_sctMsosName
@@ -109,6 +114,7 @@ namespace DerivationFramework {
       // For P->T converter of SCT_Clusters
       SG::ReadCondHandleKey<InDetDD::SiDetectorElementCollection> m_SCTDetEleCollKey{this, "SCTDetEleCollKey", "SCT_DetectorElementCollection", "Key of SiDetectorElementCollection for SCT"};
 
+     
       // --- Services and tools
       const AtlasDetectorID* m_idHelper;
       const PixelID*         m_pixId; 
@@ -122,7 +128,6 @@ namespace DerivationFramework {
       ToolHandle<ITRT_CalDbTool>                m_trtcaldbTool;
 	  
       ToolHandle<ITRT_ToT_dEdx>    m_TRTdEdxTool;
-      ToolHandle< Trk::IPRD_AssociationTool >  m_assoTool;
       // --- Private other members
       std::vector<SG::WriteDecorHandleKey<xAOD::EventInfo> > m_trtPhaseDecorKey;
       enum ETRTFloatDecor {kTRTdEdxDecor,
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/TrackStateOnSurfaceDecorator.cxx b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/TrackStateOnSurfaceDecorator.cxx
index d70f773b561b..cbf597d5bd95 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/TrackStateOnSurfaceDecorator.cxx
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/TrackStateOnSurfaceDecorator.cxx
@@ -72,8 +72,7 @@ namespace DerivationFramework {
     m_holeSearchTool("InDet::InDetTrackHoleSearchTool/InDetHoleSearchTool"),
     m_extrapolator("Trk::Extrapolator/AtlasExtrapolator"),
     m_trtcaldbTool("TRT_CalDbTool",this),
-    m_TRTdEdxTool("InDet::TRT_ElectronPidTools/TRT_ToT_dEdx"),
-    m_assoTool("InDet::InDetPRD_AssociationToolGangedPixels")
+    m_TRTdEdxTool("InDet::TRT_ElectronPidTools/TRT_ToT_dEdx")
   {
     declareInterface<DerivationFramework::IAugmentationTool>(this);
     // --- Steering and configuration flags
@@ -96,7 +95,6 @@ namespace DerivationFramework {
     declareProperty("TRT_CalDbTool",           m_trtcaldbTool);
     declareProperty("TRT_ToT_dEdx",           m_TRTdEdxTool);
     declareProperty("TrackExtrapolator",      m_extrapolator);
-    declareProperty("AssociationTool",        m_assoTool);
   }
 
   StatusCode TrackStateOnSurfaceDecorator::initialize()
@@ -138,7 +136,7 @@ namespace DerivationFramework {
     }
 
     ATH_CHECK( m_trtcaldbTool.retrieve(DisableTool{ !m_storeTRT }));
-    ATH_CHECK( m_assoTool.retrieve(DisableTool{ !m_storeTRT }));
+    ATH_CHECK( m_prdToTrackMap.initialize( !m_prdToTrackMap.key().empty() && m_storeTRT) );
 
     ATH_CHECK( m_updator.retrieve(DisableTool{ !m_addPulls }));
     ATH_CHECK( m_residualPullCalculator.retrieve(DisableTool{ !m_addPulls }));
@@ -307,6 +305,16 @@ namespace DerivationFramework {
       }
     }
 
+    SG::ReadHandle<Trk::PRDtoTrackMap>  prd_to_track_map;
+    const Trk::PRDtoTrackMap *prd_to_track_map_cptr = nullptr;
+    if (!m_prdToTrackMap.key().empty()) {
+       prd_to_track_map=SG::ReadHandle<Trk::PRDtoTrackMap>(m_prdToTrackMap);
+       if (!prd_to_track_map.isValid()) {
+          ATH_MSG_ERROR("Failed to read PRD to track association map: " << m_prdToTrackMap.key());
+       }
+       prd_to_track_map_cptr = prd_to_track_map.cptr();
+    }
+
     std::vector<SG::WriteDecorHandle<xAOD::TrackParticleContainer,float> > trackTRTFloatDecorators;
     if (m_storeTRT && m_TRTdEdxTool.isEnabled()) {
        trackTRTFloatDecorators = createDecorators<xAOD::TrackParticleContainer,float>(m_trackTRTFloatDecorKeys,ctx);
@@ -571,13 +579,15 @@ namespace DerivationFramework {
 	    }
 	  }
 	  msos->setLocalAngles(lTheta, lPhi);
-	  
+
 	  bool isShared=false;
-	  const Trk::RIO_OnTrack* hit_trt = measurement ? dynamic_cast<const Trk::RIO_OnTrack*>(measurement) : 0;
-	  if (hit_trt) {
-	    if ( m_assoTool->isShared(*(hit_trt->prepRawData())) ) isShared=true;
-	    msos->auxdata<bool>("isShared") = isShared;
-	  }
+          if (prd_to_track_map_cptr) {
+             const Trk::RIO_OnTrack* hit_trt = measurement ? dynamic_cast<const Trk::RIO_OnTrack*>(measurement) : 0;
+             if (hit_trt) {
+                if (prd_to_track_map_cptr->isShared(*(hit_trt->prepRawData())) ) isShared=true;
+                msos->auxdata<bool>("isShared") = isShared;
+             }
+          }
 	}
 
 
-- 
GitLab


From d949b74343b55d976a66537df9e3a9d40437a7d3 Mon Sep 17 00:00:00 2001
From: Goetz Gaycken <goetz.gaycken@cern.ch>
Date: Thu, 16 Apr 2020 13:26:14 +0200
Subject: [PATCH 22/26] Removed duplicated truth decoration.

---
 .../InDetPrepRawDataToxAOD/share/InDetDxAOD.py     | 14 --------------
 1 file changed, 14 deletions(-)

diff --git a/InnerDetector/InDetEventCnv/InDetPrepRawDataToxAOD/share/InDetDxAOD.py b/InnerDetector/InDetEventCnv/InDetPrepRawDataToxAOD/share/InDetDxAOD.py
index 23081f58832e..112c283a73c1 100644
--- a/InnerDetector/InDetEventCnv/InDetPrepRawDataToxAOD/share/InDetDxAOD.py
+++ b/InnerDetector/InDetEventCnv/InDetPrepRawDataToxAOD/share/InDetDxAOD.py
@@ -668,20 +668,6 @@ if (printIdTrkDxAODConf):
     print IDDerivationSequence 
     print IDDerivationSequence.properties()
 
-if DerivationFrameworkIsMonteCarlo:
-  # add track parameter decorations to truth particles but only if the decorations have not been applied already
-  import InDetPhysValMonitoring.InDetPhysValDecoration
-  meta_data = InDetPhysValMonitoring.InDetPhysValDecoration.getMetaData()
-  from AthenaCommon.Logging import logging
-  logger = logging.getLogger( "DerivationFramework" )
-  if len(meta_data) == 0 :
-    truth_track_param_decor_alg = InDetPhysValMonitoring.InDetPhysValDecoration.getInDetPhysValTruthDecoratorAlg()
-    if  InDetPhysValMonitoring.InDetPhysValDecoration.findAlg(truth_track_param_decor_alg.getName()) == None :
-      IDDerivationSequence.append( truth_track_param_decor_alg )
-    else :
-      logger.info('Decorator %s already present not adding again.' % (truth_track_param_decor_alg.getName() ))
-  else :
-    logger.info('IDPVM decorations to track particles already applied to input file not adding again.')
 
 #################
 ### Steer output file content
-- 
GitLab


From ed6cb37408acd24e59548b16356aeb3ed4a885db Mon Sep 17 00:00:00 2001
From: Goetz Gaycken <goetz.gaycken@cern.ch>
Date: Tue, 7 Apr 2020 18:32:26 +0200
Subject: [PATCH 23/26] Migrate TrackToVertexWrapper to data handles.

---
 .../TrackToVertexWrapper.h                    |  41 ++++-
 .../src/TrackToVertexWrapper.cxx              | 158 +++++++++---------
 2 files changed, 115 insertions(+), 84 deletions(-)

diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/TrackToVertexWrapper.h b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/TrackToVertexWrapper.h
index e22bdea82026..a1fe49f9eff5 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/TrackToVertexWrapper.h
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/TrackToVertexWrapper.h
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
+  Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 */
 
 ///////////////////////////////////////////////////////////////////
@@ -10,13 +10,17 @@
 #define DERIVATIONFRAMEWORK_TRACKTOVERTEXWRAPPER_H
 
 #include <string>
+#include <vector>
 
 #include "AthenaBaseComps/AthAlgTool.h"
 #include "DerivationFrameworkInterfaces/IAugmentationTool.h"
 #include "GaudiKernel/ToolHandle.h"
+#include "xAODTracking/TrackParticleContainer.h"
 #include "xAODTracking/VertexContainer.h"
 #include "TrkVertexFitterInterfaces/ITrackToVertexIPEstimator.h"
 
+#include "StoreGate/WriteDecorHandleKey.h"
+
 namespace DerivationFramework {
 
   class TrackToVertexWrapper : public AthAlgTool, public IAugmentationTool {
@@ -28,11 +32,36 @@ namespace DerivationFramework {
       virtual StatusCode addBranches() const;
 
     private:
-      ToolHandle< Trk::ITrackToVertexIPEstimator > m_tool;
-      std::string m_sgName;
-      std::string m_containerName;
-      SG::ReadHandleKey<xAOD::VertexContainer> m_vertexKey {this, "VertexContainer", "PrimaryVertices", "primary vertex container"};
-  }; 
+      ToolHandle< Trk::ITrackToVertexIPEstimator > m_tool
+         {this, "TrackToVertexIPEstimator", "Trk::TrackToVertexIPEstimator", ""};
+      Gaudi::Property<std::string> m_sgName
+         {this, "DecorationPrefix", "", ""};
+      SG::ReadHandleKey<xAOD::TrackParticleContainer> m_containerName
+         {this, "ContainerName", "", ""};
+      SG::ReadHandleKey<xAOD::VertexContainer> m_vertexKey
+         {this, "VertexContainer", "PrimaryVertices", "primary vertex container"};
+
+      enum ETrackFloatDecor {kdecnD0Decor,
+                             kdecnZ0Decor,
+                             kdecnZ0SinThetaDecor,
+                             kdecnD0ErrDecor,
+                             kdecnZ0ErrDecor,
+                             kdecnZ0SinThetaErrDecor,
+                             kdecnPVD0ErrDecor,
+                             kdecnPVZ0ErrDecor,
+                             kdecnPVZ0SinThetaErrDecor,
+                             kdecn_b_D0Decor,
+                             kdecn_b_Z0Decor,
+                             kdecn_b_Z0SinThetaDecor,
+                             kdecn_b_D0ErrDecor,
+                             kdecn_b_Z0ErrDecor,
+                             kdecn_b_Z0SinThetaErrDecor,
+                             kdecn_b_PVD0ErrDecor,
+                             kdecn_b_PVZ0ErrDecor,
+                             kdecn_b_PVZ0SinThetaErrDecor,
+                             kNFloatDecor};
+      std::vector<SG::WriteDecorHandleKey<xAOD::TrackParticleContainer> > m_trackFloatDecorKeys;
+  };
 }
 
 #endif // DERIVATIONFRAMEWORK_TRACKTOVERTEXWRAPPER_H
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/TrackToVertexWrapper.cxx b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/TrackToVertexWrapper.cxx
index 9864a870c09d..f3d8f93a67f7 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/TrackToVertexWrapper.cxx
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/TrackToVertexWrapper.cxx
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
+  Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 */
 
 ///////////////////////////////////////////////////////////////////
@@ -9,39 +9,58 @@
 //
 
 #include "DerivationFrameworkInDet/TrackToVertexWrapper.h"
-#include "xAODTracking/TrackParticleContainer.h"
 #include "TrkVertexFitterInterfaces/ITrackToVertexIPEstimator.h"
 #include <vector>
 #include <string>
+#include "StoreGate/WriteDecorHandle.h"
+#include "DerivationFrameworkInDet/DecoratorUtils.h"
 
 namespace DerivationFramework {
 
   TrackToVertexWrapper::TrackToVertexWrapper(const std::string& t,
       const std::string& n,
-      const IInterface* p) : 
-    AthAlgTool(t,n,p),
-    m_tool("Trk::TrackToVertexIPEstimator"),
-    m_sgName(""),
-    m_containerName("")
+      const IInterface* p) :
+    AthAlgTool(t,n,p)
   {
     declareInterface<DerivationFramework::IAugmentationTool>(this);
-    declareProperty("TrackToVertexIPEstimator", m_tool);
-    declareProperty("DecorationPrefix", m_sgName);
-    declareProperty("ContainerName", m_containerName);
   }
 
   StatusCode TrackToVertexWrapper::initialize()
   {
-    if (m_sgName=="") {
+     if (m_sgName.empty()) {
       ATH_MSG_ERROR("No decoration prefix name provided for the output of TracktoVertexWrapper!");
       return StatusCode::FAILURE;
     }
-    if (m_containerName=="") {
+    if (m_containerName.key().empty()) {
       ATH_MSG_ERROR("No TrackParticle collection provided for TracktoVertexWrapper!");
       return StatusCode::FAILURE;
     }
+    ATH_CHECK(m_containerName.initialize() );
     ATH_CHECK(m_tool.retrieve());
     ATH_CHECK(m_vertexKey.initialize());
+    {
+       std::vector<std::string> names;
+       names.resize(kNFloatDecor);
+       names[kdecnD0Decor]="unbiased_d0";
+       names[kdecnZ0Decor]="unbiased_z0";
+       names[kdecnZ0SinThetaDecor]="unbiased_z0SinTheta";
+       names[kdecnD0ErrDecor]="unbiased_d0Sigma";
+       names[kdecnZ0ErrDecor]="unbiased_z0Sigma";
+       names[kdecnZ0SinThetaErrDecor]="unbiased_z0SigmaSinTheta";
+       names[kdecnPVD0ErrDecor]="unbiased_PVd0Sigma";
+       names[kdecnPVZ0ErrDecor]="unbiased_PVz0Sigma";
+       names[kdecnPVZ0SinThetaErrDecor]="unbiased_PVz0SigmaSinTheta";
+       names[kdecn_b_D0Decor]="biased_d0";
+       names[kdecn_b_Z0Decor]="biased_z0";
+       names[kdecn_b_Z0SinThetaDecor]="biased_z0SinTheta";
+       names[kdecn_b_D0ErrDecor]="biased_d0Sigma";
+       names[kdecn_b_Z0ErrDecor]="biased_z0Sigma";
+       names[kdecn_b_Z0SinThetaErrDecor]="biased_z0SigmaSinTheta";
+       names[kdecn_b_PVD0ErrDecor]="biased_PVd0Sigma";
+       names[kdecn_b_PVZ0ErrDecor]="biased_PVz0Sigma";
+       names[kdecn_b_PVZ0SinThetaErrDecor]="biased_PVz0SigmaSinTheta";
+       createDecoratorKeys(*this,m_containerName, m_sgName+"_", names, m_trackFloatDecorKeys);
+    }
     return StatusCode::SUCCESS;
   }
 
@@ -52,24 +71,27 @@ namespace DerivationFramework {
 
   StatusCode TrackToVertexWrapper::addBranches() const
   {
+    const EventContext& ctx = Gaudi::Hive::currentContext();
 
     // retrieve track container
-    const xAOD::TrackParticleContainer* tracks = evtStore()->retrieve< const xAOD::TrackParticleContainer >( m_containerName );
-    if( ! tracks ) {
-        ATH_MSG_ERROR ("Couldn't retrieve TrackParticles with key: " << m_containerName );
+    SG::ReadHandle<xAOD::TrackParticleContainer> tracks(m_containerName, ctx );
+    if( ! tracks.isValid() ) {
+        ATH_MSG_ERROR ("Couldn't retrieve TrackParticles with key: " << m_containerName.key() );
         return StatusCode::FAILURE;
     }
-    SG::ReadHandle<xAOD::VertexContainer> vertices { m_vertexKey };
+    SG::ReadHandle<xAOD::VertexContainer> vertices { m_vertexKey, ctx };
     if ( !vertices.isValid() )
     {
       ATH_MSG_ERROR ("Couldn't retrieve Vertices with key: " << m_vertexKey.key());
       return StatusCode::FAILURE;
     }
 
+    std::vector<SG::WriteDecorHandle<xAOD::TrackParticleContainer,float> >
+       track_decorators = createDecorators<xAOD::TrackParticleContainer,float>(m_trackFloatDecorKeys,ctx);
     // Run tool for each element and calculate the impact parameters/errors 
     for (xAOD::TrackParticleContainer::const_iterator trItr = tracks->begin(); trItr!=tracks->end(); ++trItr) {
-      const Trk::ImpactParametersAndSigma* iPandSigma(NULL);
-      const Trk::ImpactParametersAndSigma* iPandSigmaBiased(NULL);
+      std::unique_ptr<const Trk::ImpactParametersAndSigma> iPandSigma;
+      std::unique_ptr<const Trk::ImpactParametersAndSigma> iPandSigmaBiased;
       const xAOD::Vertex* foundVertex { nullptr };
       for (const auto& vx : *vertices)
       {
@@ -84,76 +106,56 @@ namespace DerivationFramework {
 	if (foundVertex) break;
       }
       if ( foundVertex ) {
-	iPandSigma = m_tool->estimate(*trItr,foundVertex,true);
-	iPandSigmaBiased = m_tool->estimate(*trItr,foundVertex,false);
-	if( iPandSigma==0 ) ATH_MSG_WARNING ("trackToVertexIPEstimator failed !");
-	if( iPandSigmaBiased==0 ) ATH_MSG_WARNING ("trackToVertexIPEstimator biased IP failed !");
+        iPandSigma.reset(m_tool->estimate(*trItr,foundVertex,true));
+	iPandSigmaBiased.reset(m_tool->estimate(*trItr,foundVertex,false));
+	if( !iPandSigma ) ATH_MSG_WARNING ("trackToVertexIPEstimator failed !");
+	if( !iPandSigmaBiased ) ATH_MSG_WARNING ("trackToVertexIPEstimator biased IP failed !");
       } else {
 	ATH_MSG_DEBUG("No vertex associated to the track. Skipping it.");
       }
       // Do the decoration for each track
-      SG::AuxElement::Decorator< float > decnD0(m_sgName+"_unbiased_d0");
-      SG::AuxElement::Decorator< float > decnZ0(m_sgName+"_unbiased_z0");
-      SG::AuxElement::Decorator< float > decnZ0SinTheta(m_sgName+"_unbiased_z0SinTheta");
-      SG::AuxElement::Decorator< float > decnD0Err(m_sgName+"_unbiased_d0Sigma");
-      SG::AuxElement::Decorator< float > decnZ0Err(m_sgName+"_unbiased_z0Sigma");
-      SG::AuxElement::Decorator< float > decnZ0SinThetaErr(m_sgName+"_unbiased_z0SigmaSinTheta");
-      SG::AuxElement::Decorator< float > decnPVD0Err(m_sgName+"_unbiased_PVd0Sigma");
-      SG::AuxElement::Decorator< float > decnPVZ0Err(m_sgName+"_unbiased_PVz0Sigma");
-      SG::AuxElement::Decorator< float > decnPVZ0SinThetaErr(m_sgName+"_unbiased_PVz0SigmaSinTheta");
       if (iPandSigma) {
-	decnD0( **trItr ) = iPandSigma->IPd0;
-	decnZ0( **trItr ) = iPandSigma->IPz0;
-	decnZ0SinTheta( **trItr ) = iPandSigma->IPz0SinTheta;
-	decnD0Err( **trItr ) = iPandSigma->sigmad0;
-	decnZ0Err( **trItr ) = iPandSigma->sigmaz0;
-	decnZ0SinThetaErr( **trItr ) = iPandSigma->sigmaz0SinTheta;
-	decnPVD0Err (**trItr ) = iPandSigma->PVsigmad0;
-	decnPVZ0Err (**trItr ) = iPandSigma->PVsigmaz0;
-	decnPVZ0SinThetaErr (**trItr ) = iPandSigma->PVsigmaz0SinTheta;
-	delete iPandSigma;
+	track_decorators[kdecnD0Decor]( **trItr ) = iPandSigma->IPd0;
+	track_decorators[kdecnZ0Decor]( **trItr ) = iPandSigma->IPz0;
+	track_decorators[kdecnZ0SinThetaDecor]( **trItr ) = iPandSigma->IPz0SinTheta;
+	track_decorators[kdecnD0ErrDecor]( **trItr ) = iPandSigma->sigmad0;
+	track_decorators[kdecnZ0ErrDecor]( **trItr ) = iPandSigma->sigmaz0;
+	track_decorators[kdecnZ0SinThetaErrDecor]( **trItr ) = iPandSigma->sigmaz0SinTheta;
+	track_decorators[kdecnPVD0ErrDecor] (**trItr ) = iPandSigma->PVsigmad0;
+	track_decorators[kdecnPVZ0ErrDecor] (**trItr ) = iPandSigma->PVsigmaz0;
+	track_decorators[kdecnPVZ0SinThetaErrDecor] (**trItr ) = iPandSigma->PVsigmaz0SinTheta;
       } else {
-	decnD0( **trItr ) = 999.;
-	decnZ0( **trItr ) = 999.;
-	decnZ0SinTheta( **trItr ) = 999.;
-	decnD0Err( **trItr ) = 999.;
-	decnZ0Err( **trItr ) = 999.;
-	decnZ0SinThetaErr( **trItr ) = 999.;
-	decnPVD0Err (**trItr ) = 999.;
-	decnPVZ0Err (**trItr ) = 999.;
-	decnPVZ0SinThetaErr (**trItr ) = 999.;
+	track_decorators[kdecnD0Decor]( **trItr ) = 999.;
+	track_decorators[kdecnZ0Decor]( **trItr ) = 999.;
+	track_decorators[kdecnZ0SinThetaDecor]( **trItr ) = 999.;
+	track_decorators[kdecnD0ErrDecor]( **trItr ) = 999.;
+	track_decorators[kdecnZ0ErrDecor]( **trItr ) = 999.;
+	track_decorators[kdecnZ0SinThetaErrDecor]( **trItr ) = 999.;
+	track_decorators[kdecnPVD0ErrDecor] (**trItr ) = 999.;
+	track_decorators[kdecnPVZ0ErrDecor] (**trItr ) = 999.;
+	track_decorators[kdecnPVZ0SinThetaErrDecor] (**trItr ) = 999.;
       }
 
-      SG::AuxElement::Decorator< float > decn_b_D0(m_sgName+"_biased_d0");
-      SG::AuxElement::Decorator< float > decn_b_Z0(m_sgName+"_biased_z0");
-      SG::AuxElement::Decorator< float > decn_b_Z0SinTheta(m_sgName+"_biased_z0SinTheta");
-      SG::AuxElement::Decorator< float > decn_b_D0Err(m_sgName+"_biased_d0Sigma");
-      SG::AuxElement::Decorator< float > decn_b_Z0Err(m_sgName+"_biased_z0Sigma");
-      SG::AuxElement::Decorator< float > decn_b_Z0SinThetaErr(m_sgName+"_biased_z0SigmaSinTheta");
-      SG::AuxElement::Decorator< float > decn_b_PVD0Err(m_sgName+"_biased_PVd0Sigma");
-      SG::AuxElement::Decorator< float > decn_b_PVZ0Err(m_sgName+"_biased_PVz0Sigma");
-      SG::AuxElement::Decorator< float > decn_b_PVZ0SinThetaErr(m_sgName+"_biased_PVz0SigmaSinTheta");
       if (iPandSigmaBiased) {
-	decn_b_D0( **trItr ) = iPandSigmaBiased->IPd0;
-	decn_b_Z0( **trItr ) = iPandSigmaBiased->IPz0;
-	decn_b_Z0SinTheta( **trItr ) = iPandSigmaBiased->IPz0SinTheta;
-	decn_b_D0Err( **trItr ) = iPandSigmaBiased->sigmad0;
-	decn_b_Z0Err( **trItr ) = iPandSigmaBiased->sigmaz0;
-	decn_b_Z0SinThetaErr( **trItr ) = iPandSigmaBiased->sigmaz0SinTheta;
-	decn_b_PVD0Err (**trItr ) = iPandSigmaBiased->PVsigmad0;
-	decn_b_PVZ0Err (**trItr ) = iPandSigmaBiased->PVsigmaz0;
-	decn_b_PVZ0SinThetaErr (**trItr ) = iPandSigmaBiased->PVsigmaz0SinTheta;
-	delete iPandSigmaBiased;
+	track_decorators[kdecn_b_D0Decor]( **trItr ) = iPandSigmaBiased->IPd0;
+	track_decorators[kdecn_b_Z0Decor]( **trItr ) = iPandSigmaBiased->IPz0;
+	track_decorators[kdecn_b_Z0SinThetaDecor]( **trItr ) = iPandSigmaBiased->IPz0SinTheta;
+	track_decorators[kdecn_b_D0ErrDecor]( **trItr ) = iPandSigmaBiased->sigmad0;
+	track_decorators[kdecn_b_Z0ErrDecor]( **trItr ) = iPandSigmaBiased->sigmaz0;
+	track_decorators[kdecn_b_Z0SinThetaErrDecor]( **trItr ) = iPandSigmaBiased->sigmaz0SinTheta;
+	track_decorators[kdecn_b_PVD0ErrDecor] (**trItr ) = iPandSigmaBiased->PVsigmad0;
+	track_decorators[kdecn_b_PVZ0ErrDecor] (**trItr ) = iPandSigmaBiased->PVsigmaz0;
+	track_decorators[kdecn_b_PVZ0SinThetaErrDecor] (**trItr ) = iPandSigmaBiased->PVsigmaz0SinTheta;
       } else {
-	decn_b_D0( **trItr ) = 999.;
-	decn_b_Z0( **trItr ) = 999.;
-	decn_b_Z0SinTheta( **trItr ) = 999.;
-	decn_b_D0Err( **trItr ) = 999.;
-	decn_b_Z0Err( **trItr ) = 999.;
-	decn_b_Z0SinThetaErr( **trItr ) = 999.;
-	decn_b_PVD0Err (**trItr ) = 999.;
-	decn_b_PVZ0Err (**trItr ) = 999.;
-	decn_b_PVZ0SinThetaErr (**trItr ) = 999.;
+	track_decorators[kdecn_b_D0Decor]( **trItr ) = 999.;
+	track_decorators[kdecn_b_Z0Decor]( **trItr ) = 999.;
+	track_decorators[kdecn_b_Z0SinThetaDecor]( **trItr ) = 999.;
+	track_decorators[kdecn_b_D0ErrDecor]( **trItr ) = 999.;
+	track_decorators[kdecn_b_Z0ErrDecor]( **trItr ) = 999.;
+	track_decorators[kdecn_b_Z0SinThetaErrDecor]( **trItr ) = 999.;
+	track_decorators[kdecn_b_PVD0ErrDecor] (**trItr ) = 999.;
+	track_decorators[kdecn_b_PVZ0ErrDecor] (**trItr ) = 999.;
+	track_decorators[kdecn_b_PVZ0SinThetaErrDecor] (**trItr ) = 999.;
       }
     } // end of loop over tracks		 	 	  
     
-- 
GitLab


From afce1969b72e2944ce2d3244ec7ef55fc9a8e053 Mon Sep 17 00:00:00 2001
From: Goetz Gaycken <goetz.gaycken@cern.ch>
Date: Tue, 7 Apr 2020 18:38:35 +0200
Subject: [PATCH 24/26] Converted end-of-line from Dos to unix in
 UnassociatedHitsDecorator

---
 .../src/UnassociatedHitsDecorator.cxx         | 174 +++++++++---------
 1 file changed, 87 insertions(+), 87 deletions(-)

diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/UnassociatedHitsDecorator.cxx b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/UnassociatedHitsDecorator.cxx
index 0a22c1b0de10..415ec19bfecf 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/UnassociatedHitsDecorator.cxx
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/UnassociatedHitsDecorator.cxx
@@ -1,90 +1,90 @@
 /*
-  Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
+  Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 */
 
-///////////////////////////////////////////////////////////////////
-// UnassociatedHitsDecorator.cxx, (c) ATLAS Detector software
-///////////////////////////////////////////////////////////////////
-// Author: Olivier Arnaez ( olivier.arnaez@cern.ch )
-
-#include "DerivationFrameworkInDet/UnassociatedHitsDecorator.h"
-#include "AthenaBaseComps/AthMsgStreamMacros.h"
-
-#include <vector>
-#include <utility>
-#include <string>
-
-namespace DerivationFramework {
-
-  UnassociatedHitsDecorator::UnassociatedHitsDecorator(const std::string& type,
-      const std::string& name,
-      const IInterface* parent) : 
-    AthAlgTool(type,name,parent),  
-    m_sgName(""),
-    m_containerName(""),
-    m_UnassociatedHitsGetterTool(this)
-  {
-    declareInterface<DerivationFramework::IAugmentationTool>(this);
-    declareProperty("DecorationPrefix",       m_sgName);
-    declareProperty("ContainerName",          m_containerName="EventInfo");
-    declareProperty("UnassociatedHitsGetter", m_UnassociatedHitsGetterTool, "The UnassociatedHitsGetterTool instance");
-  }
-
-  StatusCode UnassociatedHitsDecorator::initialize()
-  {
-
-    if (m_sgName=="") {
-      ATH_MSG_WARNING("No decoration prefix name provided for the output of UnassociatedHitsDecorator!");
-    }
-    
-    if (m_containerName=="") {
-      ATH_MSG_ERROR("No EventInfo collection provided for UnassociatedHitsDecorator!");
-      return StatusCode::FAILURE;
-    }
-
-    // retrieve PRD association tool
-    CHECK( m_UnassociatedHitsGetterTool.retrieve() );
-
-    return StatusCode::SUCCESS;
-  }
-
-  StatusCode UnassociatedHitsDecorator::finalize()
-  {
-    return StatusCode::SUCCESS;
-  }
-
-  StatusCode UnassociatedHitsDecorator::addBranches() const
-  {
-    ATH_MSG_DEBUG("Adding unassociated hits info to EventInfo");
-
-    const xAOD::EventInfo* eventInfo;
-    CHECK( evtStore()->retrieve( eventInfo, m_containerName ) );
-
-    const MinBiasPRDAssociation* prdAssoc = m_UnassociatedHitsGetterTool->get();
-    if (prdAssoc) {
-      eventInfo->auxdecor< int >(m_sgName+"nPixelUA")        = prdAssoc->nPixelUA;
-      eventInfo->auxdecor< int >(m_sgName+"nBlayerUA")       = prdAssoc->nBlayerUA;
-      eventInfo->auxdecor< int >(m_sgName+"nPixelBarrelUA")  = prdAssoc->nPixelBarrelUA;
-      eventInfo->auxdecor< int >(m_sgName+"nPixelEndCapAUA") = prdAssoc->nPixelEndCapAUA;
-      eventInfo->auxdecor< int >(m_sgName+"nPixelEndCapCUA") = prdAssoc->nPixelEndCapCUA;
-      eventInfo->auxdecor< int >(m_sgName+"nSCTUA")          = prdAssoc->nSCTUA;
-      eventInfo->auxdecor< int >(m_sgName+"nSCTBarrelUA")    = prdAssoc->nSCTBarrelUA;
-      eventInfo->auxdecor< int >(m_sgName+"nSCTEndCapAUA")   = prdAssoc->nSCTEndCapAUA;
-      eventInfo->auxdecor< int >(m_sgName+"nSCTEndCapCUA")   = prdAssoc->nSCTEndCapCUA;
-      eventInfo->auxdecor< int >(m_sgName+"nTRTUA")          = prdAssoc->nTRTUA;
-      eventInfo->auxdecor< int >(m_sgName+"nTRTBarrelUA")    = prdAssoc->nTRTBarrelUA;
-      eventInfo->auxdecor< int >(m_sgName+"nTRTEndCapAUA")   = prdAssoc->nTRTEndCapAUA;
-      eventInfo->auxdecor< int >(m_sgName+"nTRTEndCapCUA")   = prdAssoc->nTRTEndCapCUA;
-
-      ATH_MSG_DEBUG("Decorating unassociated hits with nPixelBarrelUA = ");
-      ATH_MSG_DEBUG(prdAssoc->nPixelBarrelUA);
-
-      m_UnassociatedHitsGetterTool->releaseObject(prdAssoc);
-    }
-    else
-      ATH_MSG_WARNING("Could not retrieve Unassociated hits information");
-    
-    return StatusCode::SUCCESS;
-  }  
-  
-}
+///////////////////////////////////////////////////////////////////
+// UnassociatedHitsDecorator.cxx, (c) ATLAS Detector software
+///////////////////////////////////////////////////////////////////
+// Author: Olivier Arnaez ( olivier.arnaez@cern.ch )
+
+#include "DerivationFrameworkInDet/UnassociatedHitsDecorator.h"
+#include "AthenaBaseComps/AthMsgStreamMacros.h"
+
+#include <vector>
+#include <utility>
+#include <string>
+
+namespace DerivationFramework {
+
+  UnassociatedHitsDecorator::UnassociatedHitsDecorator(const std::string& type,
+      const std::string& name,
+      const IInterface* parent) : 
+    AthAlgTool(type,name,parent),  
+    m_sgName(""),
+    m_containerName(""),
+    m_UnassociatedHitsGetterTool(this)
+  {
+    declareInterface<DerivationFramework::IAugmentationTool>(this);
+    declareProperty("DecorationPrefix",       m_sgName);
+    declareProperty("ContainerName",          m_containerName="EventInfo");
+    declareProperty("UnassociatedHitsGetter", m_UnassociatedHitsGetterTool, "The UnassociatedHitsGetterTool instance");
+  }
+
+  StatusCode UnassociatedHitsDecorator::initialize()
+  {
+
+    if (m_sgName=="") {
+      ATH_MSG_WARNING("No decoration prefix name provided for the output of UnassociatedHitsDecorator!");
+    }
+    
+    if (m_containerName=="") {
+      ATH_MSG_ERROR("No EventInfo collection provided for UnassociatedHitsDecorator!");
+      return StatusCode::FAILURE;
+    }
+
+    // retrieve PRD association tool
+    CHECK( m_UnassociatedHitsGetterTool.retrieve() );
+
+    return StatusCode::SUCCESS;
+  }
+
+  StatusCode UnassociatedHitsDecorator::finalize()
+  {
+    return StatusCode::SUCCESS;
+  }
+
+  StatusCode UnassociatedHitsDecorator::addBranches() const
+  {
+    ATH_MSG_DEBUG("Adding unassociated hits info to EventInfo");
+
+    const xAOD::EventInfo* eventInfo;
+    CHECK( evtStore()->retrieve( eventInfo, m_containerName ) );
+
+    const MinBiasPRDAssociation* prdAssoc = m_UnassociatedHitsGetterTool->get();
+    if (prdAssoc) {
+      eventInfo->auxdecor< int >(m_sgName+"nPixelUA")        = prdAssoc->nPixelUA;
+      eventInfo->auxdecor< int >(m_sgName+"nBlayerUA")       = prdAssoc->nBlayerUA;
+      eventInfo->auxdecor< int >(m_sgName+"nPixelBarrelUA")  = prdAssoc->nPixelBarrelUA;
+      eventInfo->auxdecor< int >(m_sgName+"nPixelEndCapAUA") = prdAssoc->nPixelEndCapAUA;
+      eventInfo->auxdecor< int >(m_sgName+"nPixelEndCapCUA") = prdAssoc->nPixelEndCapCUA;
+      eventInfo->auxdecor< int >(m_sgName+"nSCTUA")          = prdAssoc->nSCTUA;
+      eventInfo->auxdecor< int >(m_sgName+"nSCTBarrelUA")    = prdAssoc->nSCTBarrelUA;
+      eventInfo->auxdecor< int >(m_sgName+"nSCTEndCapAUA")   = prdAssoc->nSCTEndCapAUA;
+      eventInfo->auxdecor< int >(m_sgName+"nSCTEndCapCUA")   = prdAssoc->nSCTEndCapCUA;
+      eventInfo->auxdecor< int >(m_sgName+"nTRTUA")          = prdAssoc->nTRTUA;
+      eventInfo->auxdecor< int >(m_sgName+"nTRTBarrelUA")    = prdAssoc->nTRTBarrelUA;
+      eventInfo->auxdecor< int >(m_sgName+"nTRTEndCapAUA")   = prdAssoc->nTRTEndCapAUA;
+      eventInfo->auxdecor< int >(m_sgName+"nTRTEndCapCUA")   = prdAssoc->nTRTEndCapCUA;
+
+      ATH_MSG_DEBUG("Decorating unassociated hits with nPixelBarrelUA = ");
+      ATH_MSG_DEBUG(prdAssoc->nPixelBarrelUA);
+
+      m_UnassociatedHitsGetterTool->releaseObject(prdAssoc);
+    }
+    else
+      ATH_MSG_WARNING("Could not retrieve Unassociated hits information");
+    
+    return StatusCode::SUCCESS;
+  }  
+  
+}
-- 
GitLab


From 6c2f653f90b22c6d90437dd1a0db6a91c3976998 Mon Sep 17 00:00:00 2001
From: Goetz Gaycken <goetz.gaycken@cern.ch>
Date: Tue, 7 Apr 2020 19:56:43 +0200
Subject: [PATCH 25/26] Migrate UnassociatedHitsDecorator to data handles.

---
 .../UnassociatedHitsDecorator.h               | 34 +++++++--
 .../src/UnassociatedHitsDecorator.cxx         | 72 +++++++++++--------
 2 files changed, 72 insertions(+), 34 deletions(-)

diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/UnassociatedHitsDecorator.h b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/UnassociatedHitsDecorator.h
index 850f47fe9404..dde32b39dc43 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/UnassociatedHitsDecorator.h
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/UnassociatedHitsDecorator.h
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
+  Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 */
 
 ///////////////////////////////////////////////////////////////////
@@ -24,6 +24,8 @@
 #include "DerivationFrameworkInDet/MinBiasPRDAssociation.h"
 #include "DerivationFrameworkInDet/IUnassociatedHitsGetterTool.h"
 
+#include "StoreGate/WriteDecorHandleKey.h"
+#include "StoreGate/ReadHandleKey.h"
 
 namespace DerivationFramework {
 
@@ -36,12 +38,32 @@ namespace DerivationFramework {
       virtual StatusCode addBranches() const;
 
     private:
-    
-      std::string m_sgName;
-      std::string m_containerName;
 
-      ToolHandle<IUnassociatedHitsGetterTool> m_UnassociatedHitsGetterTool;
-    
+      Gaudi::Property<std::string>  m_sgName
+         { this, "DecorationPrefix", "", ""};
+
+      SG::ReadHandleKey<xAOD::EventInfo> m_eventInfoKey
+         { this, "ContainerName", "EventInfo", ""};
+
+      ToolHandle<IUnassociatedHitsGetterTool> m_UnassociatedHitsGetterTool
+         { this, "UnassociatedHitsGetter", "" , ""};
+
+      enum EIntDecor {knPixelUADecor,
+                      knBlayerUADecor,
+                      knPixelBarrelUADecor,
+                      knPixelEndCapAUADecor,
+                      knPixelEndCapCUADecor,
+                      knSCTUADecor,
+                      knSCTBarrelUADecor,
+                      knSCTEndCapAUADecor,
+                      knSCTEndCapCUADecor,
+                      knTRTUADecor,
+                      knTRTBarrelUADecor,
+                      knTRTEndCapAUADecor,
+                      knTRTEndCapCUADecor,
+                      kNIntDecor};
+      std::vector<SG::WriteDecorHandleKey<xAOD::EventInfo> > m_intDecorKeys;
+
   }; 
 }
 
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/UnassociatedHitsDecorator.cxx b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/UnassociatedHitsDecorator.cxx
index 415ec19bfecf..a750b5d883ec 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/UnassociatedHitsDecorator.cxx
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/UnassociatedHitsDecorator.cxx
@@ -8,6 +8,7 @@
 // Author: Olivier Arnaez ( olivier.arnaez@cern.ch )
 
 #include "DerivationFrameworkInDet/UnassociatedHitsDecorator.h"
+#include "DerivationFrameworkInDet/DecoratorUtils.h"
 #include "AthenaBaseComps/AthMsgStreamMacros.h"
 
 #include <vector>
@@ -18,33 +19,45 @@ namespace DerivationFramework {
 
   UnassociatedHitsDecorator::UnassociatedHitsDecorator(const std::string& type,
       const std::string& name,
-      const IInterface* parent) : 
-    AthAlgTool(type,name,parent),  
-    m_sgName(""),
-    m_containerName(""),
-    m_UnassociatedHitsGetterTool(this)
+      const IInterface* parent) :
+    AthAlgTool(type,name,parent)
   {
     declareInterface<DerivationFramework::IAugmentationTool>(this);
-    declareProperty("DecorationPrefix",       m_sgName);
-    declareProperty("ContainerName",          m_containerName="EventInfo");
-    declareProperty("UnassociatedHitsGetter", m_UnassociatedHitsGetterTool, "The UnassociatedHitsGetterTool instance");
   }
 
   StatusCode UnassociatedHitsDecorator::initialize()
   {
 
-    if (m_sgName=="") {
+    if (m_sgName.empty()) {
       ATH_MSG_WARNING("No decoration prefix name provided for the output of UnassociatedHitsDecorator!");
     }
-    
-    if (m_containerName=="") {
+
+    if (m_eventInfoKey.empty()) {
       ATH_MSG_ERROR("No EventInfo collection provided for UnassociatedHitsDecorator!");
       return StatusCode::FAILURE;
     }
-
+    ATH_CHECK(m_eventInfoKey.initialize() );
     // retrieve PRD association tool
-    CHECK( m_UnassociatedHitsGetterTool.retrieve() );
+    ATH_CHECK( m_UnassociatedHitsGetterTool.retrieve() );
 
+    {
+       std::vector<std::string> names;
+       names.resize(kNIntDecor);
+       names[knPixelUADecor]        ="nPixelUA";
+       names[knBlayerUADecor]       ="nBlayerUA";
+       names[knPixelBarrelUADecor]  ="nPixelBarrelUA";
+       names[knPixelEndCapAUADecor] ="nPixelEndCapAUA";
+       names[knPixelEndCapCUADecor] ="nPixelEndCapCUA";
+       names[knSCTUADecor]          ="nSCTUA";
+       names[knSCTBarrelUADecor]    ="nSCTBarrelUA";
+       names[knSCTEndCapAUADecor]   ="nSCTEndCapAUA";
+       names[knSCTEndCapCUADecor]   ="nSCTEndCapCUA";
+       names[knTRTUADecor]          ="nTRTUA";
+       names[knTRTBarrelUADecor]    ="nTRTBarrelUA";
+       names[knTRTEndCapAUADecor]   ="nTRTEndCapAUA";
+       names[knTRTEndCapCUADecor]   ="nTRTEndCapCUA";
+       createDecoratorKeys(*this,m_eventInfoKey, m_sgName, names, m_intDecorKeys);
+    }
     return StatusCode::SUCCESS;
   }
 
@@ -56,25 +69,28 @@ namespace DerivationFramework {
   StatusCode UnassociatedHitsDecorator::addBranches() const
   {
     ATH_MSG_DEBUG("Adding unassociated hits info to EventInfo");
+    const EventContext& ctx = Gaudi::Hive::currentContext();
 
-    const xAOD::EventInfo* eventInfo;
-    CHECK( evtStore()->retrieve( eventInfo, m_containerName ) );
+    SG::ReadHandle<xAOD::EventInfo> eventInfo(m_eventInfoKey,ctx);
+    CHECK( eventInfo.isValid() ? StatusCode::SUCCESS : StatusCode::FAILURE );
 
     const MinBiasPRDAssociation* prdAssoc = m_UnassociatedHitsGetterTool->get();
+    std::vector<SG::WriteDecorHandle<xAOD::EventInfo,int> >
+    intDecorators = createDecorators<xAOD::EventInfo,int>(m_intDecorKeys,ctx);
     if (prdAssoc) {
-      eventInfo->auxdecor< int >(m_sgName+"nPixelUA")        = prdAssoc->nPixelUA;
-      eventInfo->auxdecor< int >(m_sgName+"nBlayerUA")       = prdAssoc->nBlayerUA;
-      eventInfo->auxdecor< int >(m_sgName+"nPixelBarrelUA")  = prdAssoc->nPixelBarrelUA;
-      eventInfo->auxdecor< int >(m_sgName+"nPixelEndCapAUA") = prdAssoc->nPixelEndCapAUA;
-      eventInfo->auxdecor< int >(m_sgName+"nPixelEndCapCUA") = prdAssoc->nPixelEndCapCUA;
-      eventInfo->auxdecor< int >(m_sgName+"nSCTUA")          = prdAssoc->nSCTUA;
-      eventInfo->auxdecor< int >(m_sgName+"nSCTBarrelUA")    = prdAssoc->nSCTBarrelUA;
-      eventInfo->auxdecor< int >(m_sgName+"nSCTEndCapAUA")   = prdAssoc->nSCTEndCapAUA;
-      eventInfo->auxdecor< int >(m_sgName+"nSCTEndCapCUA")   = prdAssoc->nSCTEndCapCUA;
-      eventInfo->auxdecor< int >(m_sgName+"nTRTUA")          = prdAssoc->nTRTUA;
-      eventInfo->auxdecor< int >(m_sgName+"nTRTBarrelUA")    = prdAssoc->nTRTBarrelUA;
-      eventInfo->auxdecor< int >(m_sgName+"nTRTEndCapAUA")   = prdAssoc->nTRTEndCapAUA;
-      eventInfo->auxdecor< int >(m_sgName+"nTRTEndCapCUA")   = prdAssoc->nTRTEndCapCUA;
+      intDecorators[knPixelUADecor](*eventInfo)        = prdAssoc->nPixelUA;
+      intDecorators[knBlayerUADecor](*eventInfo)       = prdAssoc->nBlayerUA;
+      intDecorators[knPixelBarrelUADecor](*eventInfo)  = prdAssoc->nPixelBarrelUA;
+      intDecorators[knPixelEndCapAUADecor](*eventInfo) = prdAssoc->nPixelEndCapAUA;
+      intDecorators[knPixelEndCapCUADecor](*eventInfo) = prdAssoc->nPixelEndCapCUA;
+      intDecorators[knSCTUADecor](*eventInfo)          = prdAssoc->nSCTUA;
+      intDecorators[knSCTBarrelUADecor](*eventInfo)    = prdAssoc->nSCTBarrelUA;
+      intDecorators[knSCTEndCapAUADecor](*eventInfo)   = prdAssoc->nSCTEndCapAUA;
+      intDecorators[knSCTEndCapCUADecor](*eventInfo)   = prdAssoc->nSCTEndCapCUA;
+      intDecorators[knTRTUADecor](*eventInfo)          = prdAssoc->nTRTUA;
+      intDecorators[knTRTBarrelUADecor](*eventInfo)    = prdAssoc->nTRTBarrelUA;
+      intDecorators[knTRTEndCapAUADecor](*eventInfo)   = prdAssoc->nTRTEndCapAUA;
+      intDecorators[knTRTEndCapCUADecor](*eventInfo)   = prdAssoc->nTRTEndCapCUA;
 
       ATH_MSG_DEBUG("Decorating unassociated hits with nPixelBarrelUA = ");
       ATH_MSG_DEBUG(prdAssoc->nPixelBarrelUA);
-- 
GitLab


From 721614a7423815f386fac28fa3bef090a2414cd9 Mon Sep 17 00:00:00 2001
From: Goetz Gaycken <goetz.gaycken@cern.ch>
Date: Tue, 7 Apr 2020 20:30:30 +0200
Subject: [PATCH 26/26] Migrate UnassociatedHitsGetterTool to data handles.

Also added the possibility to use a PRDtoTrackMap from StoreGate.
---
 .../share/InDetDxAOD.py                       |   7 +-
 .../InDetPrepRawDataToxAOD/share/SCTxAOD.py   |   5 +
 .../UnassociatedHitsGetterTool.h              |  36 +++--
 .../src/UnassociatedHitsGetterTool.cxx        | 148 ++++++++----------
 4 files changed, 100 insertions(+), 96 deletions(-)

diff --git a/InnerDetector/InDetEventCnv/InDetPrepRawDataToxAOD/share/InDetDxAOD.py b/InnerDetector/InDetEventCnv/InDetPrepRawDataToxAOD/share/InDetDxAOD.py
index 112c283a73c1..22d39a9c73fd 100644
--- a/InnerDetector/InDetEventCnv/InDetPrepRawDataToxAOD/share/InDetDxAOD.py
+++ b/InnerDetector/InDetEventCnv/InDetPrepRawDataToxAOD/share/InDetDxAOD.py
@@ -536,9 +536,14 @@ if dumpBytestreamErrors:
 
 # Add Unassociated hits augmentation tool
 if dumpUnassociatedHits:
-    from DerivationFrameworkInDet.DerivationFrameworkInDetConf import DerivationFramework__UnassociatedHitsGetterTool 
+    from InDetRecExample import TrackingCommon
+    from DerivationFrameworkInDet.DerivationFrameworkInDetConf import DerivationFramework__UnassociatedHitsGetterTool
     unassociatedHitsGetterTool = DerivationFramework__UnassociatedHitsGetterTool (name = 'unassociatedHitsGetter',
                                                                                   TrackCollection = "Tracks",
+                                                                                  AssociationTool = TrackingCommon.getPRDtoTrackMapTool(),
+                                                                                  # @TODO consider ganged pixel and TRT outliers when searching for unassociated PRDs (enabled by props below)?
+                                                                                  # AssociationTool = "",
+                                                                                  # PRDtoTrackMap = "PRDtoTrackMap" + InDetKeys.UnslimmedTracks(),
                                                                                   PixelClusters = "PixelClusters",
                                                                                   SCTClusterContainer = "SCT_Clusters",
                                                                                   TRTDriftCircleContainer = "TRT_DriftCircles")
diff --git a/InnerDetector/InDetEventCnv/InDetPrepRawDataToxAOD/share/SCTxAOD.py b/InnerDetector/InDetEventCnv/InDetPrepRawDataToxAOD/share/SCTxAOD.py
index 6c190802c5c7..c7c1a1bbfd8f 100644
--- a/InnerDetector/InDetEventCnv/InDetPrepRawDataToxAOD/share/SCTxAOD.py
+++ b/InnerDetector/InDetEventCnv/InDetPrepRawDataToxAOD/share/SCTxAOD.py
@@ -137,9 +137,14 @@ if dumpBytestreamErrors:
 
 # Add Unassociated hits augmentation tool
 if dumpUnassociatedHits:
+    from InDetRecExample import TrackingCommon
     from DerivationFrameworkInDet.DerivationFrameworkInDetConf import DerivationFramework__UnassociatedHitsGetterTool 
     unassociatedHitsGetterTool = DerivationFramework__UnassociatedHitsGetterTool (name = 'SCTxAOD_unassociatedHitsGetter',
                                                                                   TrackCollection = "Tracks",
+                                                                                  AssociationTool = TrackingCommon.getPRDtoTrackMapTool(),
+                                                                                  # @TODO consider ganged pixel and TRT outliers when searching for unassociated PRDs (enabled by props below) ?
+                                                                                  # AssociationTool = "",
+                                                                                  # PRDtoTrackMap = "PRDtoTrackMap" + InDetKeys.UnslimmedTracks(),
                                                                                   PixelClusters = "PixelClusters",
                                                                                   SCTClusterContainer = "SCT_Clusters",
                                                                                   TRTDriftCircleContainer = "TRT_DriftCircles")
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/UnassociatedHitsGetterTool.h b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/UnassociatedHitsGetterTool.h
index 787c21765e19..5ae69db7b2ba 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/UnassociatedHitsGetterTool.h
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/DerivationFrameworkInDet/UnassociatedHitsGetterTool.h
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration
+  Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 */
 
 #ifndef DERIVATIONFRAMEWORK_UNASSOCIATEDHITSGETTERTOOL_H
@@ -10,17 +10,21 @@
 
 #include "InDetReadoutGeometry/SiDetectorElementCollection.h"
 #include "StoreGate/ReadCondHandleKey.h"
-#include "StoreGate/StoreGateSvc.h"
+#include "StoreGate/ReadHandleKey.h"
 
 #include "GaudiKernel/ToolHandle.h"
 
+#include "TrkTrack/TrackCollection.h"
+#include "InDetPrepRawData/PixelClusterContainer.h"
+#include "InDetPrepRawData/SCT_ClusterContainer.h"
+#include "InDetPrepRawData/TRT_DriftCircleContainer.h"
+
+#include "TrkToolInterfaces/IPRDtoTrackMapTool.h"
+#include "TrkToolInterfaces/IPRD_AssociationTool.h"
 #include <atomic>
 #include <string>
 
 class MinBiasPRDAssociation;
-namespace Trk {
-  class IPRD_AssociationTool;
-}
 
 namespace DerivationFramework {
 
@@ -48,21 +52,23 @@ public:
 
 private:
 
-
-  /* Pointer to storegate **/
-  StoreGateSvc* m_storeGate;
-
   /* StoreGate keys **/
-  std::string m_trackCollection;
-  std::string m_pixelClusterContainer;
-  std::string m_SCTClusterContainer;
-  std::string m_TRTDriftCircleContainer;
+  SG::ReadHandleKey<TrackCollection> m_trackCollection
+     { this, "TrackCollection", "Tracks", "" };
+  SG::ReadHandleKey<InDet::PixelClusterContainer>    m_pixelClusterContainer
+     { this, "PixelClusters", "PixelClusters", ""};
+  SG::ReadHandleKey<InDet::SCT_ClusterContainer>     m_SCTClusterContainer
+     { this, "SCTClusterContainer", "SCT_Clusters", ""};
+  SG::ReadHandleKey<InDet::TRT_DriftCircleContainer> m_TRTDriftCircleContainer
+     { this, "TRTDriftCircleContainer", "TRT_DriftCircles", ""};
 
   // For P->T converter of SCT_Clusters
   SG::ReadCondHandleKey<InDetDD::SiDetectorElementCollection> m_SCTDetEleCollKey{this, "SCTDetEleCollKey", "SCT_DetectorElementCollection", "Key of SiDetectorElementCollection for SCT"};
 
-  /* PRD association tool **/
-  ToolHandle<Trk::IPRD_AssociationTool> m_assoTool;
+  ToolHandle<Trk::IPRDtoTrackMapTool>         m_assoTool
+     {this, "AssociationTool", "InDet::InDetPRDtoTrackMapToolGangedPixels" };
+  SG::ReadHandleKey<Trk::PRDtoTrackMap>       m_prdToTrackMapKey
+     {this, "PRDtoTrackMap", "",""};
 
   mutable std::atomic_bool m_firstTime;
   mutable std::atomic_bool m_disabled;
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/UnassociatedHitsGetterTool.cxx b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/UnassociatedHitsGetterTool.cxx
index 9169b997a979..c2264277ccf2 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/UnassociatedHitsGetterTool.cxx
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/src/UnassociatedHitsGetterTool.cxx
@@ -1,39 +1,28 @@
 /*
-  Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration
+  Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 */
 
 #include "DerivationFrameworkInDet/UnassociatedHitsGetterTool.h"
 
 #include "AthenaKernel/errorcheck.h"
-#include "TrkToolInterfaces/IPRD_AssociationTool.h"
 #include "InDetPrepRawData/PixelCluster.h"
 #include "InDetPrepRawData/SCT_Cluster.h"
 #include "InDetPrepRawData/TRT_DriftCircle.h"
-#include "InDetPrepRawData/PixelClusterContainer.h"
-#include "InDetPrepRawData/SCT_ClusterContainer.h"
-#include "InDetPrepRawData/TRT_DriftCircleContainer.h"
 #include "TrkTrack/Track.h"
-#include "TrkTrack/TrackCollection.h"
 #include "InDetReadoutGeometry/SiDetectorElement.h"
 #include "TRT_ReadoutGeometry/TRT_BaseElement.h"
+#include "TrkEventUtils/PRDtoTrackMap.h"
+
+#include "AthenaBaseComps/AthMsgStreamMacros.h"
 
 namespace DerivationFramework {
 
 UnassociatedHitsGetterTool::UnassociatedHitsGetterTool(const std::string& type,
 						       const std::string& name,
 						       const IInterface* parent) : 
-  AthAlgTool(type, name, parent),
-  m_storeGate(0),
-  m_assoTool("Trk::PRD_AssociationTool"),
-  m_firstTime (true),
-  m_disabled (false)
+  AthAlgTool(type, name, parent)
 {
   declareInterface<IUnassociatedHitsGetterTool>(this);
-  declareProperty("PRDAssociationTool", m_assoTool);
-  declareProperty("TrackCollection", m_trackCollection = "Tracks");
-  declareProperty("PixelClusters", m_pixelClusterContainer = "PixelClusters");
-  declareProperty("SCTClusterContainer", m_SCTClusterContainer = "SCT_Clusters");
-  declareProperty("TRTDriftCircleContainer", m_TRTDriftCircleContainer = "TRT_DriftCircles");
 }
 
 UnassociatedHitsGetterTool::~UnassociatedHitsGetterTool(){
@@ -44,85 +33,67 @@ StatusCode UnassociatedHitsGetterTool::initialize(){
 
   CHECK(AthAlgTool::initialize());
   
-  // Retrieve a pointer to StoreGate
-  CHECK( service("StoreGateSvc", m_storeGate) );
-  
   // retrieve PRD association tool
-  CHECK( m_assoTool.retrieve() );
-
+  ATH_CHECK( m_prdToTrackMapKey.initialize(!m_prdToTrackMapKey.key().empty()));
+  ATH_CHECK( m_assoTool.retrieve(DisableTool{!m_prdToTrackMapKey.key().empty()} ) );
+  ATH_CHECK( m_trackCollection.initialize());
+  ATH_CHECK( m_pixelClusterContainer.initialize( !m_pixelClusterContainer.key().empty()) );
+  ATH_CHECK( m_SCTClusterContainer.initialize( !m_SCTClusterContainer.key().empty()) );
   // Read Cond Handle Key
-  CHECK( m_SCTDetEleCollKey.initialize() );
+  ATH_CHECK( m_SCTDetEleCollKey.initialize(!m_SCTClusterContainer.key().empty()) );
+
+  ATH_CHECK( m_TRTDriftCircleContainer.initialize( !m_TRTDriftCircleContainer.key().empty()) );
 
   return StatusCode::SUCCESS;
 }
   
 const MinBiasPRDAssociation* UnassociatedHitsGetterTool::get (bool /*allowMissing*/) const {
-    
+  const EventContext& ctx = Gaudi::Hive::currentContext();
+
   // If we fail to find something we need in SG on the first call,
   // issue a warning and don't try again (this can happen if we're
   // reading an AOD).  But consider it an ERROR if it happens
   // after the first call.
-  
-  if (m_disabled){
-    return 0;
-  }
-  
-  MSG::Level level = MSG::ERROR;
-  if (m_firstTime) {
-    level = MSG::WARNING;
-    m_firstTime = false;
-  }
-  
-  // retrieve track collection
-  const TrackCollection* trackCollection;
-  StatusCode sc = m_storeGate->retrieve(trackCollection, m_trackCollection);  
-  if(sc.isFailure() || !trackCollection) {
-    m_disabled = true;
-    REPORT_MESSAGE (level) << "Track collection " << m_trackCollection << " not found in StoreGate";
-    return 0;
-  }
-  
-  // retrieve pixel clusters
-  const InDet::PixelClusterContainer *pixelClusters;
-  sc = m_storeGate->retrieve(pixelClusters, m_pixelClusterContainer);
-  if(sc.isFailure() || !pixelClusters) {
-    m_disabled = true;
-    REPORT_MESSAGE (level) << "Pixel cluster container '" << m_pixelClusterContainer << "' not found in StoreGate";
-    return 0;
-  }
-  
-  // retrieve SCT clusters
-  const InDet::SCT_ClusterContainer *SCTClusters;
-  sc = m_storeGate->retrieve(SCTClusters, m_SCTClusterContainer);
-  if(sc.isFailure() || !SCTClusters) {
-    m_disabled = true;
-    REPORT_MESSAGE (level) << "SCT cluster container '" << m_SCTClusterContainer << "' not found in StoreGate";
-    return 0;
-  }
 
-  // retrieve TRT drift circles
-  const InDet::TRT_DriftCircleContainer *TRTDriftCircles;
-  sc = m_storeGate->retrieve(TRTDriftCircles, m_TRTDriftCircleContainer);
-  if(sc.isFailure() || !TRTDriftCircles) {
-    m_disabled = true;
-    REPORT_MESSAGE (level) << "TRT drift circle container '" << m_TRTDriftCircleContainer << "' not found in StoreGate";
+  // retrieve track collection
+  SG::ReadHandle<TrackCollection> trackCollection(m_trackCollection,ctx);
+  if(!trackCollection.isValid()) {
+    ATH_MSG_FATAL("Track collection " << m_trackCollection.key() << " not found in StoreGate");
     return 0;
   }
 
   // Get empty state for PRD association tool.
-  Trk::IPRD_AssociationTool::Maps prdmaps;
-
+  const Trk::PRDtoTrackMap *prd_to_track_map;
+  std::unique_ptr<Trk::PRDtoTrackMap> prd_to_track_map_cleanup;
+  if (!m_prdToTrackMapKey.key().empty()) {
+     SG::ReadHandle<Trk::PRDtoTrackMap> prd_to_track_map_handle(m_prdToTrackMapKey,ctx);
+     if (!prd_to_track_map_handle.isValid()) {
+        ATH_MSG_ERROR(  "Failed to get PRDs to track map " << m_prdToTrackMapKey.key());
+        return 0;
+     }
+     prd_to_track_map=prd_to_track_map_handle.cptr();
+  }
+  else {
+     prd_to_track_map_cleanup = m_assoTool->createPRDtoTrackMap();
   // Loop over tracks and add PRDs to the PRD association tool
-  for (const Trk::Track* track : *trackCollection) {
-    StatusCode sc = m_assoTool->addPRDs(prdmaps, *track);
-    if(sc.isFailure()){
-      REPORT_MESSAGE (MSG::ERROR) << "Could not add PRDs to track";
-      return 0;
-    }
+     for (const Trk::Track* track : *trackCollection) {
+        StatusCode sc = m_assoTool->addPRDs(*prd_to_track_map_cleanup, *track);
+        if(sc.isFailure()){
+           ATH_MSG_FATAL(  "Could not add PRDs to track");
+           return 0;
+        }
+     }
+     prd_to_track_map = prd_to_track_map_cleanup.get();
   }
 
-  MinBiasPRDAssociation *PRDAssociation = new MinBiasPRDAssociation();
-
+  std::unique_ptr<MinBiasPRDAssociation> PRDAssociation(std::make_unique<MinBiasPRDAssociation>());
+  if (!m_pixelClusterContainer.key().empty()) {
+  // retrieve pixel clusters
+  SG::ReadHandle<InDet::PixelClusterContainer> pixelClusters(m_pixelClusterContainer,ctx);
+  if(!pixelClusters.isValid()) {
+    ATH_MSG_FATAL("Pixel cluster container '" << m_pixelClusterContainer.key() << "' not found in StoreGate");
+    return 0;
+  }
   // Loop on pixel clusters
   InDet::PixelClusterContainer::const_iterator pixCollItr = pixelClusters->begin();
   InDet::PixelClusterContainer::const_iterator pixCollEnd = pixelClusters->end();
@@ -133,7 +104,7 @@ const MinBiasPRDAssociation* UnassociatedHitsGetterTool::get (bool /*allowMissin
     for(; pixItr!=pixEnd; pixItr++){
 
       // ask the association tool if the hit was associated
-      if(m_assoTool->isUsed(prdmaps, *(*pixItr))) continue;
+      if(prd_to_track_map->isUsed(*(*pixItr))) continue;
 
       // count number of unassociated pixel hits
       PRDAssociation->nPixelUA++;
@@ -157,7 +128,15 @@ const MinBiasPRDAssociation* UnassociatedHitsGetterTool::get (bool /*allowMissin
       if(det->isBlayer()) PRDAssociation->nBlayerUA++;
     }
   }
+  }
 
+  // retrieve SCT clusters
+  if (!m_SCTClusterContainer.key().empty()) {
+  SG::ReadHandle<InDet::SCT_ClusterContainer> SCTClusters(m_SCTClusterContainer,ctx);
+  if(!SCTClusters.isValid()) {
+    ATH_MSG_FATAL("SCT cluster container '" << m_SCTClusterContainer.key() << "' not found in StoreGate");
+    return 0;
+  }
   // Loop on SCT clusters
   InDet::SCT_ClusterContainer::const_iterator sctCollItr = SCTClusters->begin();
   InDet::SCT_ClusterContainer::const_iterator sctCollEnd = SCTClusters->end();
@@ -168,7 +147,7 @@ const MinBiasPRDAssociation* UnassociatedHitsGetterTool::get (bool /*allowMissin
     for(; sctItr!=sctEnd; sctItr++){
 
       // ask the association tool if the hit was associated
-      if(m_assoTool->isUsed(prdmaps, *(*sctItr))) continue;
+      if(prd_to_track_map->isUsed(*(*sctItr))) continue;
 
       // count number of unassociated SCT hits
       PRDAssociation->nSCTUA++;
@@ -189,7 +168,15 @@ const MinBiasPRDAssociation* UnassociatedHitsGetterTool::get (bool /*allowMissin
       }
     }
   }
+  }
 
+  // retrieve TRT drift circles
+  if (!m_TRTDriftCircleContainer.key().empty()) {
+  SG::ReadHandle<InDet::TRT_DriftCircleContainer> TRTDriftCircles(m_TRTDriftCircleContainer,ctx);
+  if(!TRTDriftCircles.isValid()) {
+    ATH_MSG_FATAL("TRT drift circle container '" << m_TRTDriftCircleContainer << "' not found in StoreGate");
+    return 0;
+  }
   // Loop on TRT clusters
   InDet::TRT_DriftCircleContainer::const_iterator trtCollItr = TRTDriftCircles->begin();
   InDet::TRT_DriftCircleContainer::const_iterator trtCollEnd = TRTDriftCircles->end();
@@ -200,7 +187,7 @@ const MinBiasPRDAssociation* UnassociatedHitsGetterTool::get (bool /*allowMissin
     for(; trtItr!=trtEnd; trtItr++){
 
       // ask the association tool if the hit was associated
-      if(m_assoTool->isUsed(prdmaps, *(*trtItr))) continue;
+      if(prd_to_track_map->isUsed(*(*trtItr))) continue;
 
       // count number of unassociated TRT hits
       PRDAssociation->nTRTUA++;
@@ -223,8 +210,9 @@ const MinBiasPRDAssociation* UnassociatedHitsGetterTool::get (bool /*allowMissin
       }
     }
   }
+  }
 
-  return PRDAssociation;
+  return PRDAssociation.release();
 }
 
 void UnassociatedHitsGetterTool::releaseObject (const MinBiasPRDAssociation* p) const {
-- 
GitLab