From b356b385d4e5ec782a7f05a1c6ca83a6eb8df2a1 Mon Sep 17 00:00:00 2001
From: Johannes Junggeburth <johannes.josef.junggeburth@cern.ch>
Date: Sun, 4 Feb 2018 21:03:57 +0100
Subject: [PATCH] Okay now the latest changes are in

Former-commit-id: 876361953fff225f824bee7ee1e7491e5cd59f08
---
 .../DerivationFrameworkMuons/CMakeLists.txt   |   8 +-
 .../IDTrackCaloDepositsDecoratorTool.h        |  71 +++
 .../IIDTrackCaloDepositsDecoratorTool.h       |  23 +
 .../IMuonTPExtrapolationTool.h                |  29 +
 .../MuonIDCovMatrixDecorator.h                |  39 ++
 .../MuonTPExtrapolationTool.h                 |  71 +++
 .../python/JPsiVertexFitSetup.py              | 105 ++++
 .../python/MuonsCPContent.py                  |   8 +-
 .../python/MuonsCommon.py                     |   7 +
 .../python/StreamConfig.py                    |   3 +-
 .../scripts/trival_test.sh                    |   4 +-
 .../DerivationFrameworkMuons/share/MUON0.py   |  10 +-
 .../DerivationFrameworkMuons/share/MUON1.py   | 105 +++-
 .../DerivationFrameworkMuons/share/MUON2.py   | 530 ++++++++++++++----
 .../DerivationFrameworkMuons/share/MUON3.py   |  15 +-
 .../DerivationFrameworkMuons/share/MUON5.py   | 297 ++++++++++
 .../src/IDTrackCaloDepositsDecoratorTool.cxx  | 191 +++++++
 .../src/MuonIDCovMatrixDecorator.cxx          |  73 +++
 .../src/MuonTPExtrapolationTool.cxx           | 329 +++++++++++
 .../src/MuonTPJpsiVertexFittingAlg.cxx        |  61 ++
 .../src/MuonTPJpsiVertexFittingAlg.h          |  47 ++
 .../DerivationFrameworkMuons_entries.cxx      |  22 +-
 .../DerivationFrameworkMuons_load.cxx         |   3 +
 .../src/dimuonTaggingTool.cxx                 |   4 +-
 .../src/isolationDecorator.cxx                |   6 +-
 .../src/mcpDecorator.cxx                      | 131 -----
 26 files changed, 1920 insertions(+), 272 deletions(-)
 create mode 100644 PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/DerivationFrameworkMuons/IDTrackCaloDepositsDecoratorTool.h
 create mode 100644 PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/DerivationFrameworkMuons/IIDTrackCaloDepositsDecoratorTool.h
 create mode 100644 PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/DerivationFrameworkMuons/IMuonTPExtrapolationTool.h
 create mode 100644 PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/DerivationFrameworkMuons/MuonIDCovMatrixDecorator.h
 create mode 100644 PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/DerivationFrameworkMuons/MuonTPExtrapolationTool.h
 create mode 100644 PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/python/JPsiVertexFitSetup.py
 create mode 100644 PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/share/MUON5.py
 create mode 100644 PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/src/IDTrackCaloDepositsDecoratorTool.cxx
 create mode 100644 PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/src/MuonIDCovMatrixDecorator.cxx
 create mode 100644 PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/src/MuonTPExtrapolationTool.cxx
 create mode 100644 PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/src/MuonTPJpsiVertexFittingAlg.cxx
 create mode 100644 PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/src/MuonTPJpsiVertexFittingAlg.h
 create mode 100644 PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/src/components/DerivationFrameworkMuons_load.cxx

diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/CMakeLists.txt b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/CMakeLists.txt
index a775a37543d..7aa12af3d71 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/CMakeLists.txt
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/CMakeLists.txt
@@ -18,8 +18,10 @@ atlas_depends_on_subdirs( PUBLIC
                           Reconstruction/RecoTools/RecoToolInterfaces
                           Trigger/TrigAnalysis/TrigDecisionTool
                           Trigger/TrigAnalysis/TrigMuonMatching
+                          Reconstruction/MuonIdentification/ICaloTrkMuIdTools
+                          Reconstruction/MuonIdentification/CaloTrkMuIdTools
+                          Tracking/TrkExtrapolation/TrkExInterfaces
                           PRIVATE
-			  PhysicsAnalysis/MuonID/MuonPerformanceAnalysis/MuonTPTools
                           Control/AthenaKernel
 			  Control/AthenaBaseComps
                           Event/xAOD/xAODEventInfo
@@ -35,13 +37,13 @@ atlas_add_library( DerivationFrameworkMuonsLib
                    PUBLIC_HEADERS DerivationFrameworkMuons
                    PRIVATE_INCLUDE_DIRS ${CLHEP_INCLUDE_DIRS}
                    PRIVATE_DEFINITIONS ${CLHEP_DEFINITIONS}
-                   LINK_LIBRARIES CaloEvent CaloGeoHelpers AthenaBaseComps xAODCaloEvent xAODMuon GaudiKernel RecoToolInterfaces ExpressionEvaluationLib TrigDecisionToolLib TrigMuonMatchingLib
+                   LINK_LIBRARIES CaloEvent CaloGeoHelpers AthenaBaseComps xAODCaloEvent xAODMuon GaudiKernel RecoToolInterfaces ExpressionEvaluationLib TrigDecisionToolLib TrigMuonMatchingLib ICaloTrkMuIdTools CaloTrkMuIdTools TrkExInterfaces
                    PRIVATE_LINK_LIBRARIES ${CLHEP_LIBRARIES} AthenaKernel xAODEventInfo xAODTracking xAODTruth )
 
 atlas_add_component( DerivationFrameworkMuons
                      src/components/*.cxx
                      INCLUDE_DIRS ${CLHEP_INCLUDE_DIRS}
-                     LINK_LIBRARIES ${CLHEP_LIBRARIES} CaloEvent CaloGeoHelpers AthenaBaseComps xAODCaloEvent xAODMuon GaudiKernel ExpressionEvaluationLib RecoToolInterfaces TrigDecisionToolLib TrigMuonMatchingLib AthenaKernel xAODEventInfo xAODTracking xAODTruth DerivationFrameworkMuonsLib )
+                     LINK_LIBRARIES ${CLHEP_LIBRARIES} CaloEvent CaloGeoHelpers AthenaBaseComps xAODCaloEvent xAODMuon GaudiKernel ExpressionEvaluationLib RecoToolInterfaces TrigDecisionToolLib TrigMuonMatchingLib AthenaKernel xAODEventInfo xAODTracking xAODTruth DerivationFrameworkMuonsLib ICaloTrkMuIdTools CaloTrkMuIdTools TrkExInterfaces)
 
 # Install files from the package:
 atlas_install_python_modules( python/*.py )
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/DerivationFrameworkMuons/IDTrackCaloDepositsDecoratorTool.h b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/DerivationFrameworkMuons/IDTrackCaloDepositsDecoratorTool.h
new file mode 100644
index 00000000000..0e19207edef
--- /dev/null
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/DerivationFrameworkMuons/IDTrackCaloDepositsDecoratorTool.h
@@ -0,0 +1,71 @@
+/*
+ * IDTrackCaloDepositsDecoratorTool.h
+ *
+ *  Created on: Oct 29, 2015
+ *      Author: mbellomo
+ */
+
+#ifndef IDTRACKCALODEPOSITSDECORATORTOOL_H_
+#define IDTRACKCALODEPOSITSDECORATORTOOL_H_
+
+
+#include "AsgTools/AsgTool.h"
+#include "AsgTools/ToolHandle.h"
+
+#include "DerivationFrameworkMuons/IIDTrackCaloDepositsDecoratorTool.h"
+
+
+#ifndef XAOD_ANALYSIS
+#include "ICaloTrkMuIdTools/ITrackDepositInCaloTool.h"
+#endif
+class IDTrackCaloDepositsDecoratorTool :
+          public asg::AsgTool,
+          virtual public IIDTrackCaloDepositsDecoratorTool {
+    ASG_TOOL_CLASS(IDTrackCaloDepositsDecoratorTool, IIDTrackCaloDepositsDecoratorTool)
+public:
+    IDTrackCaloDepositsDecoratorTool(std::string myname);
+    virtual StatusCode      initialize  ();
+    StatusCode              decorate (const xAOD::IParticle* part) const;
+protected:
+
+#ifndef XAOD_ANALYSIS
+    ToolHandle<ITrackDepositInCaloTool>  m_trkDepositInCalo;
+#endif
+    StatusCode    recompute_and_decorate (const xAOD::IParticle* part) const;
+
+    SG::AuxElement::Decorator< float > m_dec_EMB1_dep;
+    SG::AuxElement::Decorator< float > m_dec_EMB1_eloss;
+    SG::AuxElement::Decorator< float > m_dec_EMB2_dep;
+    SG::AuxElement::Decorator< float > m_dec_EMB2_eloss;
+    SG::AuxElement::Decorator< float > m_dec_EMB3_dep;
+    SG::AuxElement::Decorator< float > m_dec_EMB3_eloss;
+    SG::AuxElement::Decorator< float > m_dec_EME1_dep;
+    SG::AuxElement::Decorator< float > m_dec_EME1_eloss;
+    SG::AuxElement::Decorator< float > m_dec_EME2_dep;
+    SG::AuxElement::Decorator< float > m_dec_EME2_eloss;
+    SG::AuxElement::Decorator< float > m_dec_EME3_dep;
+    SG::AuxElement::Decorator< float > m_dec_EME3_eloss;
+    SG::AuxElement::Decorator< float > m_dec_TileBar0_dep;
+    SG::AuxElement::Decorator< float > m_dec_TileBar0_eloss;
+    SG::AuxElement::Decorator< float > m_dec_TileBar1_dep;
+    SG::AuxElement::Decorator< float > m_dec_TileBar1_eloss;
+    SG::AuxElement::Decorator< float > m_dec_TileBar2_dep;
+    SG::AuxElement::Decorator< float > m_dec_TileBar2_eloss;
+    SG::AuxElement::Decorator< float > m_dec_TileExt0_dep;
+    SG::AuxElement::Decorator< float > m_dec_TileExt0_eloss;
+    SG::AuxElement::Decorator< float > m_dec_TileExt1_dep;
+    SG::AuxElement::Decorator< float > m_dec_TileExt1_eloss;
+    SG::AuxElement::Decorator< float > m_dec_TileExt2_dep;
+    SG::AuxElement::Decorator< float > m_dec_TileExt2_eloss;
+    SG::AuxElement::Decorator< float > m_dec_HEC0_dep;
+    SG::AuxElement::Decorator< float > m_dec_HEC0_eloss;
+    SG::AuxElement::Decorator< float > m_dec_HEC1_dep;
+    SG::AuxElement::Decorator< float > m_dec_HEC1_eloss;
+    SG::AuxElement::Decorator< float > m_dec_HEC2_dep;
+    SG::AuxElement::Decorator< float > m_dec_HEC2_eloss;
+    SG::AuxElement::Decorator< float > m_dec_HEC3_dep;
+    SG::AuxElement::Decorator< float > m_dec_HEC3_eloss;
+
+};
+
+#endif 
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/DerivationFrameworkMuons/IIDTrackCaloDepositsDecoratorTool.h b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/DerivationFrameworkMuons/IIDTrackCaloDepositsDecoratorTool.h
new file mode 100644
index 00000000000..d1979a0c1ed
--- /dev/null
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/DerivationFrameworkMuons/IIDTrackCaloDepositsDecoratorTool.h
@@ -0,0 +1,23 @@
+/*
+ * IIDTrackCaloDepositsDecoratorTool.h
+ *
+ *  Created on: Oct 29, 2015
+ *      Author: mbellomo
+ */
+
+#ifndef IIDTRACKCALODEPOSITSDECORATORTOOL_H_
+#define IIDTRACKCALODEPOSITSDECORATORTOOL_H_
+
+
+#include "AsgTools/IAsgTool.h"
+#include "xAODBase/IParticle.h"
+
+
+class IIDTrackCaloDepositsDecoratorTool : virtual public asg::IAsgTool {
+  ASG_TOOL_INTERFACE(IIDTrackCaloDepositsDecoratorTool)
+public:
+    virtual StatusCode decorate (const xAOD::IParticle* part) const = 0;
+};
+
+
+#endif /* IIDTRACKISOLATIONDECORATORTOOL_H_ */
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/DerivationFrameworkMuons/IMuonTPExtrapolationTool.h b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/DerivationFrameworkMuons/IMuonTPExtrapolationTool.h
new file mode 100644
index 00000000000..d41694358e5
--- /dev/null
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/DerivationFrameworkMuons/IMuonTPExtrapolationTool.h
@@ -0,0 +1,29 @@
+// IMuonTPExtrapolationTool.h
+#ifndef IMuonTPExtrapolationTool_H
+#define IMuonTPExtrapolationTool_H
+
+#include "AsgTools/IAsgTool.h"
+#include "xAODTracking/TrackParticle.h"
+#include "xAODMuon/Muon.h"
+
+#ifndef XAOD_ANALYSIS
+#include "TrkParameters/TrackParameters.h"
+#endif
+
+
+class IMuonTPExtrapolationTool : virtual public asg::IAsgTool {
+  ASG_TOOL_INTERFACE(IMuonTPExtrapolationTool)
+
+    public:
+  
+  /// compute dR on trigger pivot plane
+  /// This also applies decorations for the eta and phi coordinates in said plane to the tag and the probe track particles 
+  /// If we are processing a DAOD in AthAnalysis, it attempts to read the decorations that should be provided by the derivation
+  /// In full athena, it will check for the decoration, and run extrapolation if it is not (yet) in place
+  virtual double dROnTriggerPivotPlane(const xAOD::Muon& tag, const xAOD::IParticle* probe)=0;
+
+  // this method is intended for use in the DAOD production. It takes only one particle as argument, and handles the decoration. 
+  virtual StatusCode decoratePivotPlaneCoords(const xAOD::IParticle* particle)=0;
+  };
+
+#endif
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/DerivationFrameworkMuons/MuonIDCovMatrixDecorator.h b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/DerivationFrameworkMuons/MuonIDCovMatrixDecorator.h
new file mode 100644
index 00000000000..3c0abd3c682
--- /dev/null
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/DerivationFrameworkMuons/MuonIDCovMatrixDecorator.h
@@ -0,0 +1,39 @@
+/*
+  Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
+*/
+
+///////////////////////////////////////////////////////////////////
+// MuonIDCovMatrixDecorator.h
+///////////////////////////////////////////////////////////////////
+#ifndef DERIVATIONFRAMEWORK_MuonIDCovMatrixDecorator_H
+#define DERIVATIONFRAMEWORK_MuonIDCovMatrixDecorator_H
+
+#include<string>
+#include<vector>
+
+// Gaudi & Athena basics
+#include "AthenaBaseComps/AthAlgTool.h"
+#include "GaudiKernel/ToolHandle.h"
+#include "DerivationFrameworkInterfaces/IAugmentationTool.h"
+
+namespace DerivationFramework {
+  class MuonIDCovMatrixDecorator : public AthAlgTool, public IAugmentationTool {
+    
+  public: 
+    /** Constructor with parameters */
+    MuonIDCovMatrixDecorator( const std::string& t, const std::string& n, const IInterface* p);
+    
+    /** Destructor */
+    ~MuonIDCovMatrixDecorator();
+ 
+    // Athena algtool's Hooks
+    StatusCode  initialize();
+    StatusCode  finalize();
+    
+    virtual StatusCode addBranches() const;
+    
+  private:
+    std::string m_muonSGKey;
+  }; 
+}
+#endif //
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/DerivationFrameworkMuons/MuonTPExtrapolationTool.h b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/DerivationFrameworkMuons/MuonTPExtrapolationTool.h
new file mode 100644
index 00000000000..4e685ad76f3
--- /dev/null
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/DerivationFrameworkMuons/MuonTPExtrapolationTool.h
@@ -0,0 +1,71 @@
+//////////////////////////////////////////////////////////////////////////////
+// MuonTPExtrapolationTool
+//  ASG Tool performing extrapolations
+//
+//  (c) ATLAS Muon Combined Performance Software
+//////////////////////////////////////////////////////////////////////////////
+#ifndef MuonTPExtrapolationTool_H
+#define MuonTPExtrapolationTool_H
+
+#include "DerivationFrameworkMuons/IMuonTPExtrapolationTool.h"
+#include "AsgTools/AsgTool.h"
+#include "AsgTools/ToolHandle.h"
+
+namespace Trk { 
+  class IExtrapolator; 
+}
+
+class MuonTPExtrapolationTool
+: public asg::AsgTool,
+  virtual public IMuonTPExtrapolationTool {
+  ASG_TOOL_CLASS(MuonTPExtrapolationTool, IMuonTPExtrapolationTool)
+    
+    public:  
+  MuonTPExtrapolationTool(std::string myname);
+  virtual ~MuonTPExtrapolationTool();
+  
+  virtual StatusCode initialize();
+  
+  /// compute dR on trigger pivot plane
+  /// see interface class for full description
+  double dROnTriggerPivotPlane(const xAOD::Muon& tag, const xAOD::IParticle* probe);
+
+  // this method is intended for use in the DAOD production. It takes only one particle as argument, and handles the decoration. 
+  virtual StatusCode decoratePivotPlaneCoords(const xAOD::IParticle* particle);
+
+#ifndef XAOD_ANALYSIS
+  /// run the extrapolation - only available in full athena
+  const Trk::TrackParameters* extrapolateToTriggerPivotPlane(const xAOD::TrackParticle& track);
+#endif
+
+  // Utility method to handle extrapolation and decoration for one TrackParticle. 
+  // In AthAnalysis, it attempts to read the decoration that should be present in the DAODs we use (MUON1/2).
+  // In full athena, it looks for the decoration, and, if it is missing, runs track extrapolation, decorating the result
+  // to the particle to avoid repeating the process unnecessarily. 
+  // Returns success (true) or failure (false) of the procedure, fills eta and phi coordinates via reference
+  // If the extrapolation fails or the decoration is missing in AthAnalysis, it will *not* change eta and phi
+  // So you can set them to defaults before calling this guy, and they will be preserved in case of failure. 
+  bool extrapolateAndDecorateTrackParticle(const xAOD::TrackParticle* particle, float & eta, float & phi);
+  
+ private:
+
+#ifndef XAOD_ANALYSIS
+  ToolHandle<Trk::IExtrapolator> m_extrapolator;
+#endif
+
+  // utility method: Obtains the track particle which we want to extrapolate into the MS. 
+  // Works for all kinds of probes. 
+  const xAOD::TrackParticle* getPreferredTrackParticle (const xAOD::IParticle* probe);
+
+  // these define the surfaces that we extrapolate to. 
+  // We approximate the pivot plane in the form of a cylinder surface and two disks
+  double m_endcapPivotPlaneZ;
+  double m_endcapPivotPlaneMinimumRadius;
+  double m_endcapPivotPlaneMaximumRadius;
+  double m_barrelPivotPlaneRadius;
+  double m_barrelPivotPlaneHalfLength;
+  
+
+  };
+
+#endif
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/python/JPsiVertexFitSetup.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/python/JPsiVertexFitSetup.py
new file mode 100644
index 00000000000..9bba723fa90
--- /dev/null
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/python/JPsiVertexFitSetup.py
@@ -0,0 +1,105 @@
+
+def AddJPsiVertexingAlgs(prefix='',addAlgo=True):
+
+  from AthenaCommon.Include import include
+  from AthenaCommon.AlgSequence import AlgSequence
+  job = AlgSequence()
+  from AthenaCommon.AppMgr import ToolSvc
+  include( "JpsiUpsilonTools/configureServices.py" )
+
+
+
+  from TrkVertexFitterUtils.TrkVertexFitterUtilsConf import Trk__KalmanVertexUpdator
+  VertexUpdater = Trk__KalmanVertexUpdator(name             = "MuonTP_KalmanVertexUpdator")
+  ToolSvc += VertexUpdater
+  print      VertexUpdater
+
+
+
+  MuContainer = "Muons"
+  if hasattr(job, "CalibratedMuonsProvider"):
+    MuContainer = job.CalibratedMuonsProvider.Output
+
+
+  from AthenaCommon.Constants import INFO,DEBUG,WARNING
+  from JpsiUpsilonTools.JpsiUpsilonToolsConf import Analysis__JpsiFinder
+  ExampleJpsiFinder = Analysis__JpsiFinder(name                        = prefix+"JpsiFinderName",
+                                           muAndMu                     = False,
+                                           muAndTrack                  = False,
+                                           TrackAndTrack               = True,
+                                           assumeDiMuons               = True,    # If true, will assume dimu hypothesis and use PDG value for mu mass
+                                           invMassUpper                = 3500.0,
+                                           invMassLower                = 2700.0,
+                                           Chi2Cut                     = 2000.,
+                                           allChargeCombinations       = True,
+                                           oppChargesOnly              = False,
+                                           sameChargesOnly             = False,
+                                           trackThresholdPt            = 2500,
+                                           muonThresholdPt             = 4000,
+                                           atLeastOneComb              = False,
+                                           useCombinedMeasurement      = False, # Only takes effect if combOnly=True  
+                                           muonCollectionKey           = MuContainer,
+                                           # muonCollectionKey           = MuContainer,
+                                           TrackParticleCollection     = "InDetTrackParticles",
+                                           V0VertexFitterTool          = ToolSvc.TrkV0FitterName,             # V0 vertex fitter
+                                           useV0Fitter                 = False,                   # if False a TrkVertexFitterTool will be used
+                                           TrkVertexFitterTool         = ToolSvc.VKalVrtFitterName,        # VKalVrt vertex fitter
+                                           TrackSelectorTool           = ToolSvc.InDetDetailedTrackSelectorTool,
+                                           ConversionFinderHelperTool  = ToolSvc.InDetConversionFinderUtils,
+                                           VertexPointEstimator        = ToolSvc.VtxPointEstimator,
+                                           useMCPCuts                  = True, 
+                                           OutputLevel                 = WARNING)
+  ToolSvc += ExampleJpsiFinder
+
+
+  # Here, we are stealing a ton of code from the BPHY1 derivation... Sorry! 
+  # The reason that we don't simply import the BPHY code here is that we don't run the derivation kernel
+  # So we need to plug our tools into a custom alg. 
+
+
+  from DerivationFrameworkBPhys.DerivationFrameworkBPhysConf import DerivationFramework__Reco_mumu
+  MuonTP_Reco_mumu = DerivationFramework__Reco_mumu(
+  name                   = prefix+"MuonTP_Reco_mumu",
+  JpsiFinder             = ExampleJpsiFinder,
+  OutputVtxContainerName = prefix+"JpsiCandidates",
+  PVContainerName        = "PrimaryVertices",
+  RefPVContainerName     = prefix+"RefittedPrimaryVertices",
+  RefitPV                = True,
+  MaxPVrefit             = 100000,
+  DoVertexType           = 7,
+  OutputLevel           = WARNING )
+
+  ToolSvc += MuonTP_Reco_mumu
+  print MuonTP_Reco_mumu
+
+
+  from DerivationFrameworkBPhys.DerivationFrameworkBPhysConf import DerivationFramework__Select_onia2mumu
+
+  ## a/ augment and select Jpsi->mumu candidates
+  MuonTP_Select_Jpsi2mumu = DerivationFramework__Select_onia2mumu(
+  name                  = prefix+"MuonTP_Select_Jpsi2mumu",
+  HypothesisName        = "Jpsi",
+  InputVtxContainerName = prefix+"JpsiCandidates",
+  VtxMassHypo           = 3096.916,
+  MassMin               = 2700.0,
+  MassMax               = 3500.0,
+  Chi2Max               = 200,
+  DoVertexType          = 7,
+  OutputLevel           = WARNING)
+
+  ToolSvc += MuonTP_Select_Jpsi2mumu
+  print MuonTP_Select_Jpsi2mumu
+
+  if addAlgo:
+      from DerivationFrameworkMuons.DerivationFrameworkMuonsConf import MuonTPJpsiVertexFittingAlg
+      job += MuonTPJpsiVertexFittingAlg ( name = "MuonTPJpsiVertexFittingAlg",OutputLevel=WARNING)
+      job.MuonTPJpsiVertexFittingAlg.AugmentationTools = [MuonTP_Reco_mumu, MuonTP_Select_Jpsi2mumu]
+  else:
+      return [MuonTP_Reco_mumu, MuonTP_Select_Jpsi2mumu]
+
+
+  # from JpsiUpsilonTools.JpsiUpsilonToolsConf import JpsiAlg
+
+  # job += JpsiAlg(JpsiCandidatesOutputName = "JpsiCandidates", OutputLevel=WARNING,
+  #                        JpsiFinderName           = ToolSvc.JpsiFinderName)
+
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/python/MuonsCPContent.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/python/MuonsCPContent.py
index 1215897d23f..39e408a6381 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/python/MuonsCPContent.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/python/MuonsCPContent.py
@@ -2,7 +2,7 @@
 
 MuonsCPContent = [
 "CombinedMuonTrackParticles",
-"CombinedMuonTrackParticlesAux.phi.theta.qOverP.numberOfPixelHits.numberOfPixelHoles.numberOfPixelDeadSensors.numberOfSCTHits.numberOfSCTHoles.numberOfSCTDeadSensors.numberOfTRTHits.numberOfTRTOutliers.numberOfPrecisionLayers.numberOfPrecisionHoleLayers.d0.z0.vz.definingParametersCovMatrix.vertexLink.truthParticleLink.chiSquared.numberDoF.numberOfPhiLayers.numberOfPhiHoleLayers.numberOfInnermostPixelLayerHits",
+"CombinedMuonTrackParticlesAux.phi.theta.qOverP.numberOfPixelHits.numberOfPixelHoles.numberOfPixelDeadSensors.numberOfSCTHits.numberOfSCTHoles.numberOfSCTDeadSensors.numberOfTRTHits.numberOfTRTOutliers.numberOfPrecisionLayers.numberOfPrecisionHoleLayers.d0.z0.vz.definingParametersCovMatrix.vertexLink.truthParticleLink.chiSquared.numberDoF.numberOfPhiLayers.numberOfPhiHoleLayers.numberOfInnermostPixelLayerHits.alignEffectChId.alignEffectDeltaTrans.alignEffectSigmaDeltaTrans.alignEffectDeltaAngle.alignEffectSigmaDeltaAngle",
 "ExtrapolatedMuonTrackParticles",
 "GSFTrackParticles",
 "InDetTrackParticles",
@@ -16,12 +16,12 @@ MuonsCPContent = [
 "InDetTrackParticlesAux.phi.theta.qOverP.numberOfPixelHits.numberOfPixelHoles.numberOfPixelDeadSensors.numberOfSCTHits.numberOfSCTHoles.numberOfSCTDeadSensors.numberOfTRTHits.numberOfTRTOutliers.numberOfPrecisionLayers.d0.z0.vz.definingParametersCovMatrix.vertexLink.truthParticleLink.chiSquared.numberDoF.numberOfPhiLayers.numberOfPhiHoleLayers.numberOfPrecisionHoleLayers",
 "MuonSpectrometerTrackParticles",
 "MuonSpectrometerTrackParticlesAux.phi.d0.z0.vz.definingParametersCovMatrix.vertexLink.theta.qOverP.truthParticleLink",
-"MuonsAux.pt.eta.phi.truthType.truthOrigin.author.muonType.quality.inDetTrackParticleLink.muonSpectrometerTrackParticleLink.combinedTrackParticleLink.InnerDetectorPt.MuonSpectrometerPt.DFCommonGoodMuon.momentumBalanceSignificance.clusterLink.ptcone20.ptcone30.ptcone40.ptvarcone20.ptvarcone30.ptvarcone40.topoetcone20.topoetcone30.topoetcone40.innerSmallHits.truthParticleLink.charge.CaloLRLikelihood.CaloMuonIDTag.extrapolatedMuonSpectrometerTrackParticleLink.numberOfPrecisionLayers.numberOfPrecisionHoleLayers.innerLargeHits.muonSegmentLinks.numberOfGoodPrecisionLayers.innerSmallHoles.innerLargeHoles.middleSmallHoles.middleLargeHoles.outerSmallHoles.outerLargeHoles.extendedSmallHoles.extendedLargeHoles.innerClosePrecisionHits.middleClosePrecisionHits.outerClosePrecisionHits.extendedClosePrecisionHits.innerOutBoundsPrecisionHits.middleOutBoundsPrecisionHits.outerOutBoundsPrecisionHits.extendedOutBoundsPrecisionHits.combinedTrackOutBoundsPrecisionHits.isEndcapGoodLayers.isSmallGoodSectors.middleLargeHits.middleSmallHits.outerLargeHits.outerSmallHits.extendedSmallHits.extendedLargeHits",
+"MuonsAux.pt.eta.phi.truthType.truthOrigin.author.muonType.quality.inDetTrackParticleLink.muonSpectrometerTrackParticleLink.combinedTrackParticleLink.InnerDetectorPt.MuonSpectrometerPt.DFCommonGoodMuon.momentumBalanceSignificance.clusterLink.ptcone20.ptcone30.ptcone40.ptvarcone20.ptvarcone30.ptvarcone40.topoetcone20.topoetcone30.topoetcone40.innerSmallHits.truthParticleLink.charge.CaloLRLikelihood.CaloMuonIDTag.extrapolatedMuonSpectrometerTrackParticleLink.numberOfPrecisionLayers.numberOfPrecisionHoleLayers.innerLargeHits.muonSegmentLinks.numberOfGoodPrecisionLayers.innerSmallHoles.innerLargeHoles.middleSmallHoles.middleLargeHoles.outerSmallHoles.outerLargeHoles.extendedSmallHoles.extendedLargeHoles.innerClosePrecisionHits.middleClosePrecisionHits.outerClosePrecisionHits.extendedClosePrecisionHits.innerOutBoundsPrecisionHits.middleOutBoundsPrecisionHits.outerOutBoundsPrecisionHits.extendedOutBoundsPrecisionHits.combinedTrackOutBoundsPrecisionHits.isEndcapGoodLayers.isSmallGoodSectors.middleLargeHits.middleSmallHits.outerLargeHits.outerSmallHits.extendedSmallHits.extendedLargeHits.cscEtaHits.cscUnspoiledEtaHits.spectrometerFieldIntegral.scatteringCurvatureSignificance.scatteringNeighbourSignificance.msOnlyExtrapolatedMuonSpectrometerTrackParticleLink.allAuthors",
 "PhotonsAux.pt.eta.phi.m.caloClusterLinks.author.f1.topoetcone40.Tight.truthParticleLink.vertexLinks",
 "egammaClustersAux.calEta.calPhi.calE.calM",
 "egammaTopoSeededClusters",
 "egammaTopoSeededClustersAux.calEta.calPhi",
 "InDetForwardTrackParticles",
 "InDetForwardTrackParticlesAux.theta.phi.qOverP.numberOfPrecisionLayers.numberOfPrecisionHoleLayers.numberOfPixelHits.numberOfPixelDeadSensors.numberOfSCTHits.numberOfSCTDeadSensors.d0.z0.vz.definingParametersCovMatrix.numberOfPixelHoles.numberOfSCTHoles.numberOfTRTHits.numberOfTRTOutliers",
-"ExtrapolatedMuonTrackParticlesAux.numberOfPrecisionHoleLayers.numberOfPixelHoles.numberOfSCTHits.numberOfSCTHoles.numberOfSCTDeadSensors.numberOfTRTHits.numberOfTRTOutliers.phi.qOverP.theta.definingParametersCovMatrix.numberOfPixelDeadSensors.numberOfPixelHits.numberOfPrecisionLayers",
-]
\ No newline at end of file
+"ExtrapolatedMuonTrackParticlesAux.numberOfPrecisionHoleLayers.numberOfPixelHoles.numberOfSCTHits.numberOfSCTHoles.numberOfSCTDeadSensors.numberOfTRTHits.numberOfTRTOutliers.phi.qOverP.theta.definingParametersCovMatrix.numberOfPixelDeadSensors.numberOfPixelHits.numberOfPrecisionLayers.alignEffectChId.alignEffectDeltaTrans.alignEffectSigmaDeltaTrans.alignEffectDeltaAngle.alignEffectSigmaDeltaAngle",
+]
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/python/MuonsCommon.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/python/MuonsCommon.py
index 9e38d4034bb..0c4c3e39394 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/python/MuonsCommon.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/python/MuonsCommon.py
@@ -60,6 +60,13 @@ ToolSvc += DFCommonMuonToolWrapperPreselection
 print DFCommonMuonToolWrapperPreselection
 DFCommonMuonToolWrapperTools.append(DFCommonMuonToolWrapperPreselection)
 
+### Decoration of the muon objects with the ID track covariances
+#from DerivationFrameworkMuons.DerivationFrameworkMuonsConf import DerivationFramework__MuonIDCovMatrixDecorator
+#DFCommonMuonIDCovMatrixDecorator = DerivationFramework__MuonIDCovMatrixDecorator( name = "DFCommonMuonIDCovMatrixDecorator")
+#ToolSvc += DFCommonMuonIDCovMatrixDecorator
+#print DFCommonMuonIDCovMatrixDecorator
+#DFCommonMuonToolWrapperTools.append(DFCommonMuonIDCovMatrixDecorator)
+
 #############
 #  Add tools
 #############
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/python/StreamConfig.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/python/StreamConfig.py
index 98445c585f6..e0aa3e5e86e 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/python/StreamConfig.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/python/StreamConfig.py
@@ -46,7 +46,7 @@ class MuonsDxAODStreamConfigurer:
 
     ### all varaible containers
 #     commonAllVarList = ["Muons", "PrimaryVertices", "InDetTrackParticles", "MuonSegments", "MuonTruthParticles", "CombinedMuonTrackParticles", "ExtrapolatedMuonTrackParticles", "MuonSpectrometerTrackParticles", "InDetForwardTrackParticles"]
-    commonAllVarList = ["Muons", "InDetTrackParticles", "MuonSegments", "MuonTruthParticles", "CombinedMuonTrackParticles", "ExtrapolatedMuonTrackParticles", "MuonSpectrometerTrackParticles", "InDetForwardTrackParticles"]
+    commonAllVarList = ["Muons", "InDetTrackParticles", "MuonSegments", "MuonTruthParticles", "CombinedMuonTrackParticles", "ExtrapolatedMuonTrackParticles", "MuonSpectrometerTrackParticles", "InDetForwardTrackParticles","MSOnlyExtrapolatedMuonTrackParticles"]
     MUON0OnlyAllVar = ['Staus','ExtrapolatedStauTrackParticles','CombinedStauTrackParticles','SlowMuons'] # slow muons
     MUON1OnlyAllVar = ['CaloCalTopoClusters', 'MuonClusterCollection']
     MUON2OnlyAllVar = ['PrimaryVertices']
@@ -84,6 +84,7 @@ class MuonsDxAODStreamConfigurer:
     ### For FSR check
     extraVariables['MUON1'].append('Photons.truthType.truthOrigin.topoetcone40')
     extraVariables['MUON1'].append('Electrons.truthType.truthOrigin.topoetcone40')
+    extraVariables['MUON1'].append('InDetTrackParticles.deltaphi_0.deltatheta_0.sigmadeltaphi_0.sigmadeltatheta_0.deltaphi_1.deltatheta_1.sigmadeltaphi_1.sigmadeltatheta_1')
 
     ### PV slimming for size reduction
     pvExtra = 'PrimaryVertices.numberDoF.chiSquared.sumPt2.x.y.z'
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/scripts/trival_test.sh b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/scripts/trival_test.sh
index dbd9113d24d..cdef58cc00e 100755
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/scripts/trival_test.sh
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/scripts/trival_test.sh
@@ -10,13 +10,13 @@ Reco_tf.py --inputFileValidation False --preExec 'rec.doApplyAODFix.set_Value_an
 mv log.AODtoDAOD log_${output}.AODtoDAOD
 }
 
-# INPUT=root://eosatlas.cern.ch//eos/atlas/user/m/mdobre/forRTTmc15/MC15_207.AOD.pool.root
+# INPUT=root://eosatlas//eos/atlas/user/m/mdobre/forRTTmc15/MC15_207.AOD.pool.root
 # runJob $INPUT ${OUT}1 "--passThrough True"
 # 
 # INPUT=/net/s3_datad/Data15/MC15/AOD/mc15_13TeV.424107.Pythia8B_A14_CTEQ6L1_Jpsimu8mu8.merge.AOD.e5290_s2726_r7772_r7676/AOD.09264436._001199.pool.root.1
 # runJob $INPUT ${OUT}2 "--passThrough True"
 
-INPUT=root://eosatlas.cern.ch//eos/atlas/user/m/mdobre/forRTTdata15/Data16_207.AOD.pool.root
+INPUT=root://eosatlas//eos/atlas/user/m/mdobre/forRTTdata15/Data16_207.AOD.pool.root
 runJob $INPUT ${OUT}3
 
 INPUT4=/home/dzhang/links/SAMPLES/R20/MC15/AOD/mc15_13TeV.361107.PowhegPythia8EvtGen_AZNLOCTEQ6L1_Zmumu.merge.AOD.e3601_s2576_s2132_r7773_r7676/AOD.07981188._000211.pool.root.1
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/share/MUON0.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/share/MUON0.py
index 7f614f8e185..872429414cf 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/share/MUON0.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/share/MUON0.py
@@ -21,15 +21,19 @@ MUON0Stream.AcceptAlgs(["MUON0Kernel"])
 # augStream = MSMgr.GetStream( streamName )
 # evtStream = augStream.GetEventStream()
 
-# triggerList = ['HLT_.*mu\d+.*', 'L1_.*MU\d+.*', 'HLT_noalg_L1.*MU\d+.*']
-triggerList1 = ['HLT_.*mu\d+.*', 'L1_.*MU.*', 'HLT_noalg_L1.*MU.*']
-triggerList = ['HLT_.*mu.*', 'L1_.*MU.*', 'HLT_noalg_L1.*MU.*']
+triggerList1 = ['HLT_.*mu\d+.*', 'L1_.*MU\d+.*', 'HLT_noalg_L1.*MU\d+.*']
+#triggerList1 = []
+triggerList = ['HLT_.*mu.*', 'L1_.*MU.*','HLT_noalg_L1.*MU.*']
 
 from DerivationFrameworkCore.ThinningHelper import ThinningHelper
 MUON0ThinningHelper = ThinningHelper( "MUON0ThinningHelper" )
 MUON0ThinningHelper.TriggerChains = '|'.join(triggerList1)
 print MUON0ThinningHelper.TriggerChains
 MUON0ThinningHelper.AppendToStream( MUON0Stream )
+thinningSvc = getattr( svcMgr, "MUON0ThinningSvc" )
+thinningHelperTool = getattr( ToolSvc, "MUON0ThinningHelperSlim" )
+thinningHelperTool.FeatureInclusionList += ['HLT_xAOD__L2StandAloneMuonContainer_MuonL2SAInfo','HLT_xAOD__L2StandAloneMuonContainer_MuonL2SAInfoAux.','HLT_xAOD__L2CombinedMuonContainer_MuonL2CBInfo','HLT_xAOD__L2CombinedMuonContainer_MuonL2CBInfoAux.','HLT_xAOD__L2IsoMuonContainer_MuonL2ISInfo','HLT_xAOD__L2IsoMuonContainer_MuonL2ISInfoAux.','HLT_TrigRoiDescriptorCollection_forMS','HLT_TrigRoiDescriptorCollection_forMSAux.','HLT_TrigRoiDescriptorCollection_forID','HLT_TrigRoiDescriptorCollection_forIDAux.']
+
 
 
 #====================================================================
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/share/MUON1.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/share/MUON1.py
index c52ea5d7f50..f78835f5942 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/share/MUON1.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/share/MUON1.py
@@ -10,7 +10,19 @@ from DerivationFrameworkMuons.MuonsCommon import *
 # from DerivationFrameworkJetEtMiss.METCommon import *
 import AthenaCommon.SystemOfUnits as Units
 
-from MuonPerformanceAlgs.CommonMuonTPConfig import GetIDTrackCaloDepositsDecorator
+#from MuonPerformanceAlgs.CommonMuonTPConfig import GetIDTrackCaloDepositsDecorator
+if not hasattr(ToolSvc,"IDTrackCaloDepositsDecoratorTool"):
+  from DerivationFrameworkMuons.DerivationFrameworkMuonsConf import IDTrackCaloDepositsDecoratorTool
+  DecoTool = IDTrackCaloDepositsDecoratorTool("IDTrackCaloDepositsDecoratorTool")
+  if hasattr(DecoTool, "TrackDepositInCaloTool"):
+    if not hasattr(ToolSvc,"TrkDepositInCaloTool"):
+        from CaloTrkMuIdTools.CaloTrkMuIdToolsConf import TrackDepositInCaloTool
+        TrkDepositInCaloTool = TrackDepositInCaloTool("TrkDepositInCaloTool")
+        TrkDepositInCaloTool.CaloCellContainerName = "AODCellContainer"
+        ToolSvc += TrkDepositInCaloTool
+    DecoTool.TrackDepositInCaloTool = ToolSvc.TrkDepositInCaloTool
+
+    ToolSvc += DecoTool
 
 
 #====================================================================
@@ -40,7 +52,7 @@ thinningORs = []
 brPrefix1a = 'MUON1a'
 from DerivationFrameworkMuons.DerivationFrameworkMuonsConf import DerivationFramework__dimuonTaggingTool
 MUON1AugmentTool1a = DerivationFramework__dimuonTaggingTool(name = "MUON1AugmentTool1a",
-                                                           IDTrackCaloDepoDecoTool = GetIDTrackCaloDepositsDecorator(),
+                                                           IDTrackCaloDepoDecoTool = ToolSvc.IDTrackCaloDepositsDecoratorTool,
                                                            Mu1PtMin = 24*Units.GeV,
                                                            Mu1AbsEtaMax = 2.5,
                                                            Mu1Types = [0],
@@ -69,11 +81,11 @@ print MUON1AugmentTool1a
 
 ### Jpsi for tag-probe
 andTriggers1b = ['HLT_mu20_iloose_L1MU15', 'HLT_mu24', 'HLT_mu26', 'HLT_mu24_imedium', 'HLT_mu26_imedium']
-orTriggers1b = ['HLT_mu4','HLT_mu6','HLT_mu14','HLT_mu6_idperf','HLT_mu4_bJpsi_Trkloose','HLT_mu6_bJpsi_Trkloose ','HLT_mu10_bJpsi_Trkloose','HLT_mu18_bJpsi_Trkloose']
+orTriggers1b = ['HLT_mu4','HLT_mu6','HLT_mu14','HLT_mu6_idperf','HLT_mu4_bJpsi_Trkloose','HLT_mu6_bJpsi_Trkloose ','HLT_mu10_bJpsi_Trkloose','HLT_mu18_bJpsi_Trkloose','HLT_mu20_2mu0noL1_JpsimumuFS','HLT_mu18_2mu0noL1_JpsimumuFS','HLT_mu20_2mu4_JpsimumuL2','HLT_mu18_2mu4_JpsimumuL2','HLT_mu4_mu4_idperf_bJpsimumu_noid','HLT_mu4_bJpsi_TrkPEB','HLT_mu6_bJpsi_TrkPEB','HLT_mu10_bJpsi_TrkPEB','HLT_mu14_bJpsi_TrkPEB','HLT_mu20_bJpsi_TrkPEB']
 
 brPrefix1b = 'MUON1b'
 MUON1AugmentTool1b = DerivationFramework__dimuonTaggingTool(name = "MUON1AugmentTool1b",
-                                                           IDTrackCaloDepoDecoTool = GetIDTrackCaloDepositsDecorator(),
+                                                           IDTrackCaloDepoDecoTool = ToolSvc.IDTrackCaloDepositsDecoratorTool,
                                                            OrTrigs = orTriggers1b,
                                                            AndTrigs = andTriggers1b,
                                                            Mu1PtMin = 4*Units.GeV,
@@ -108,7 +120,7 @@ orTriggers1c = []
 andTriggers1c = []
 
 MUON1AugmentTool1c = DerivationFramework__dimuonTaggingTool(name = "MUON1AugmentTool1c",
-                                                           IDTrackCaloDepoDecoTool = GetIDTrackCaloDepositsDecorator(),
+                                                           IDTrackCaloDepoDecoTool = ToolSvc.IDTrackCaloDepositsDecoratorTool,
                                                            OrTrigs = orTriggers1c,
                                                            AndTrigs = andTriggers1c,
                                                            Mu1PtMin = 5.*Units.GeV,
@@ -254,15 +266,16 @@ theCaloCellDFGetter = CaloCellDFGetter(inputClusterKeys=["MuonClusterCollection"
 #====================================================================
 # JetTagNonPromptLepton decorations
 #====================================================================
+import JetTagNonPromptLepton.JetTagNonPromptLeptonConfig as JetTagConfig
 if not hasattr(DerivationFrameworkJob,"MUONSequence"):
     MUONSeq = CfgMgr.AthSequencer("MUONSequence")
-    DerivationFrameworkJob += MUONSeq
 
     if not hasattr(MUONSeq,"Muons_decoratePromptLepton"):
-        import JetTagNonPromptLepton.JetTagNonPromptLeptonConfig as Config
-        MUONSeq += Config.GetDecoratePromptLeptonAlgs()
+        JetTagConfig.ConfigureAntiKt4PV0TrackJets(MUONSeq,"MUON1")
+        MUONSeq += JetTagConfig.GetDecoratePromptLeptonAlgs()
+    DerivationFrameworkJob += MUONSeq
 
-from MuonPerformanceAlgs import  JPsiVertexFitSetup
+from DerivationFrameworkMuons import  JPsiVertexFitSetup
 MUON1AugmentTools += JPsiVertexFitSetup.AddJPsiVertexingAlgs('MUON1',False)
 for t in MUON1AugmentTools: print t
 
@@ -277,6 +290,79 @@ MUON1Thin_vtxTrk = DerivationFramework__Thin_vtxTrk(
 ToolSvc += MUON1Thin_vtxTrk
 MUON1ThinningTools.append(MUON1Thin_vtxTrk)
 
+#Custom isolation configurations for testing new recommendations
+from IsolationTool.IsolationToolConf import xAOD__CaloIsolationTool, xAOD__TrackIsolationTool
+from AthenaCommon import CfgMgr
+
+tighttrackvertexassotool=CfgMgr.CP__TightTrackVertexAssociationTool("TightTrackVertexAssociationTool", dzSinTheta_cut=3, doPV=True) 
+ToolSvc+=tighttrackvertexassotool 
+
+from IsolationAlgs.IsolationAlgsConf import IsolationBuilder
+TrackIsolationLoose500 = xAOD__TrackIsolationTool(name = 'TrackIsolationToolLoose500')
+TrackIsolationLoose500.TrackSelectionTool.minPt         = 500
+TrackIsolationLoose500.TrackSelectionTool.CutLevel      = "Loose"
+TrackIsolationLoose500.TrackSelectionTool.maxZ0SinTheta = 3.
+TrackIsolationLoose500.UseTTVAtool = False
+ToolSvc += TrackIsolationLoose500
+TrackIsolationTight1000 = xAOD__TrackIsolationTool(name = 'TrackIsolationToolTight1000')
+TrackIsolationTight1000.TrackSelectionTool.minPt         = 1000
+TrackIsolationTight1000.TrackSelectionTool.CutLevel      = "Loose"
+TrackIsolationTight1000.UseTTVAtool = True
+TrackIsolationTight1000.TrackVertexAssociationTool = tighttrackvertexassotool
+ToolSvc += TrackIsolationTight1000
+TrackIsolationTight500 = xAOD__TrackIsolationTool(name = 'TrackIsolationToolTight500')
+TrackIsolationTight500.TrackSelectionTool.minPt         = 500
+TrackIsolationTight500.TrackSelectionTool.CutLevel      = "Loose"
+TrackIsolationTight500.UseTTVAtool = True
+TrackIsolationTight500.TrackVertexAssociationTool = tighttrackvertexassotool
+ToolSvc += TrackIsolationTight500
+
+import ROOT, PyCintex
+PyCintex.loadDictionary('xAODCoreRflxDict')
+PyCintex.loadDictionary('xAODPrimitivesDict')
+isoPar = ROOT.xAOD.Iso
+ptconeList = [[isoPar.ptcone40,isoPar.ptcone30,isoPar.ptcone20]]
+
+isoBuilderLoose500 = IsolationBuilder(
+    name                   = "IsolationBuilderLoose500",
+    CaloCellIsolationTool  = None,
+    CaloTopoIsolationTool  = None,
+    PFlowIsolationTool     = None,
+    TrackIsolationTool     = TrackIsolationLoose500, 
+    EgIsoTypes             = [[]],
+    MuIsoTypes             = ptconeList,
+    CustomConfigurationNameMu = "LooseTTVA_pt500",
+    IsAODFix = True,
+    LeakageTool = None,
+    OutputLevel            = 3)
+DerivationFrameworkJob += isoBuilderLoose500
+isoBuilderTight1000 = IsolationBuilder(
+    name                   = "IsolationBuilderTight1000",
+    CaloCellIsolationTool  = None,
+    CaloTopoIsolationTool  = None,
+    PFlowIsolationTool     = None,
+    TrackIsolationTool     = TrackIsolationTight1000, 
+    EgIsoTypes             = [[]],
+    MuIsoTypes             = ptconeList,
+    CustomConfigurationNameMu = "TightTTVA_pt1000",
+    IsAODFix = True,
+    LeakageTool = None,
+    OutputLevel            = 3)
+DerivationFrameworkJob += isoBuilderTight1000
+isoBuilderTight500 = IsolationBuilder(
+    name                   = "IsolationBuilderTight500",
+    CaloCellIsolationTool  = None,
+    CaloTopoIsolationTool  = None,
+    PFlowIsolationTool     = None,
+    TrackIsolationTool     = TrackIsolationTight500, 
+    EgIsoTypes             = [[]],
+    MuIsoTypes             = ptconeList,
+    CustomConfigurationNameMu = "TightTTVA_pt500",
+    IsAODFix = True,
+    LeakageTool = None,
+    OutputLevel            = 3)
+DerivationFrameworkJob += isoBuilderTight500
+
 #====================================================================
 # CREATE THE DERIVATION KERNEL ALGORITHM AND PASS THE ABOVE TOOLS 
 #====================================================================
@@ -298,4 +384,5 @@ if hasattr(ToolSvc,"MUON1MuonTP_Reco_mumu"):
 
 conf.Items['MUON1']+=["CaloCellContainer#DFMUONCellContainer"]
 conf.Items['MUON1']+=["CaloClusterCellLinkContainer#MuonClusterCollection_links"]
+conf.extraVariables['MUON1'] += JetTagConfig.GetExtraPromptVariablesForDxAOD()
 conf.Config(MUON1Stream, 'MUON1')
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/share/MUON2.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/share/MUON2.py
index b78ca859992..844311497e8 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/share/MUON2.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/share/MUON2.py
@@ -1,138 +1,450 @@
 #====================================================================
-# MUON2.py for Jpsi->mumu tag&probe
-# This requires the reductionConf flag MUON2 in Reco_tf.py   
+# MUON2.py
+# Bs>J/psiKK 
+# It requires the reductionConf flag MUON2 in Reco_tf.py   
 #====================================================================
 
-# Set up common services and job object.
+# Set up common services and job object. 
 # This should appear in ALL derivation job options
 from DerivationFrameworkCore.DerivationFrameworkMaster import *
-from DerivationFrameworkMuons.MuonsCommon import *
-# from DerivationFrameworkJetEtMiss.METCommon import *
-import AthenaCommon.SystemOfUnits as Units
-from MuonPerformanceAlgs.CommonMuonTPConfig import GetIDTrackCaloDepositsDecorator
 
-#====================================================================
-# AUGMENTATION TOOLS
-#====================================================================
-# enum    MuonType {
-#   Combined, MuonStandAlone, SegmentTagged, CaloTagged,
-#   SiliconAssociatedForwardMuon
-# }
-# isolation cuts: check xAODPrimitives/xAODPrimitives/IsolationType.h for definitions
-orTriggers_run1 = ['EF_mu6_Trk_Jpsi_loose','EF_2mu4T_Jpsimumu_IDTrkNoCut','EF_mu4Tmu6_Jpsimumu_IDTrkNoCut']
-orTriggers_run2 = ['HLT_mu4_bJpsi_Trkloose','HLT_mu6_bJpsi_Trkloose','HLT_mu10_bJpsi_Trkloose','HLT_mu18_bJpsi_Trkloose']
-andTriggers_run1 = ['EF_mu24i_tight', 'EF_mu24i_tight_MuonEF', 'EF_mu24i_tight_MG', 'EF_mu24i_tight_l2muonSA']
-andTriggers_run2 = ['HLT_mu20_iloose_L1MU15', 'HLT_mu24', 'HLT_mu26', 'HLT_mu24_imedium', 'HLT_mu26_imedium']
-orTriggers = orTriggers_run2
-andTriggers = andTriggers_run2
-# andTriggers = []
-brPrefix = 'MUON2'
-from DerivationFrameworkMuons.DerivationFrameworkMuonsConf import DerivationFramework__dimuonTaggingTool
-MUON2AugmentTool1 = DerivationFramework__dimuonTaggingTool(name = "MUON2AugmentTool1",
-                                                           IDTrackCaloDepoDecoTool = GetIDTrackCaloDepositsDecorator(),
-                                                           OrTrigs = orTriggers,
-                                                           AndTrigs = andTriggers,
-                                                           Mu1PtMin = 4*Units.GeV,
-                                                           Mu1AbsEtaMax = 2.5,
-                                                           Mu1Types = [0],
-                                                           Mu1Trigs = [],
-                                                           Mu1IsoCuts = {},
-                                                           Mu2PtMin = 2.5*Units.GeV,
-                                                           Mu2AbsEtaMax = 9999.,
-                                                           Mu2Types = [],
-                                                           Mu2Trigs = [],
-                                                           Mu2IsoCuts = {},
-                                                           UseTrackProbe = True, # bool
-                                                           TrackContainerKey = 'InDetTrackParticles', # str
-                                                           OppositeCharge = False,
-                                                           InvariantMassLow = 2.0*Units.GeV,
-                                                           InvariantMassHigh = 4.8*Units.GeV,
-                                                           IDTrackThinningConeSize = 0.5,
-                                                           BranchPrefix = brPrefix
-                                                           )
-
-ToolSvc += MUON2AugmentTool1
-print MUON2AugmentTool1
-
-
-from DerivationFrameworkMuons.TrackIsolationDecorator import MUON2IDTrackDecorator as MUON2AugmentTool2
-ToolSvc += MUON2AugmentTool2
-print MUON2AugmentTool2
-
-from DerivationFrameworkMuons.TrackIsolationDecorator import MUON2MSTrackDecorator as MUON2AugmentTool3
-ToolSvc += MUON2AugmentTool3
-print MUON2AugmentTool3
+isSimulation = False
+if globalflags.DataSource()=='geant4':
+    isSimulation = True
 
-#====================================================================
-# SKIMMING
-#====================================================================
-# expression = 'EventInfo.eventTypeBitmask==1||'+brPrefix+'DIMU_pass>0'
-expression = brPrefix+'DIMU_pass>0'
-from DerivationFrameworkTools.DerivationFrameworkToolsConf import DerivationFramework__xAODStringSkimmingTool
-MUON2SkimmingTool1 = DerivationFramework__xAODStringSkimmingTool( name = "MUON2SkimmingTool1",
-                                                                         expression = expression)
-ToolSvc += MUON2SkimmingTool1
+print isSimulation
 
 #====================================================================
-# THINNING
+# AUGMENTATION TOOLS 
 #====================================================================
-# keep tracks marked in augmentation
-thinning_expression = brPrefix+"DIMU_trkStatus>0"
-from DerivationFrameworkInDet.DerivationFrameworkInDetConf import DerivationFramework__TrackParticleThinning
-MUON2ThinningTool1 = DerivationFramework__TrackParticleThinning(name                    = "MUON2ThinningTool1",
-                                                                ThinningService         = "MUON2ThinningSvc",
-                                                                SelectionString         = thinning_expression,
-                                                                InDetTrackParticlesKey  = "InDetTrackParticles",
-                                                                ApplyAnd                = False)
-ToolSvc += MUON2ThinningTool1
-
-# keep tracks around muons
-thinning_expression2 = ""
+## 1/ setup vertexing tools and services
+#include( "JpsiUpsilonTools/configureServices.py" )
+
+include("DerivationFrameworkBPhys/configureVertexing.py")
+MUON2_VertexTools = BPHYVertexTools("MUON2")
+
+
+from DerivationFrameworkBPhys.DerivationFrameworkBPhysConf import DerivationFramework__AugOriginalCounts
+MUON2_AugOriginalCounts = DerivationFramework__AugOriginalCounts(
+   name = "MUON2_AugOriginalCounts",
+   VertexContainer = "PrimaryVertices",
+   TrackContainer = "InDetTrackParticles" )
+ToolSvc += MUON2_AugOriginalCounts
+
+
+#--------------------------------------------------------------------
+## 2/ setup JpsiFinder tool
+##    These are general tools independent of DerivationFramework that do the 
+##    actual vertex fitting and some pre-selection.
+from JpsiUpsilonTools.JpsiUpsilonToolsConf import Analysis__JpsiFinder
+MUON2JpsiFinder = Analysis__JpsiFinder(name                         = "MUON2JpsiFinder",
+                                        OutputLevel                 = INFO,
+                                        muAndMu                     = True,
+                                        muAndTrack                  = False,
+                                        TrackAndTrack               = False,
+                                        assumeDiMuons               = True, 
+                                        invMassUpper                = 3600.0,
+                                        invMassLower                = 2600.0,
+                                        Chi2Cut                     = 30.,
+                                        oppChargesOnly	            = True,
+                                        combOnly		            = True,
+                                        atLeastOneComb              = False,
+                                        useCombinedMeasurement      = False, # Only takes effect if combOnly=True	
+                                        muonCollectionKey           = "Muons",
+                                        TrackParticleCollection     = "InDetTrackParticles",
+                                        V0VertexFitterTool          = MUON2_VertexTools.TrkV0Fitter,             # V0 vertex fitter
+                                        useV0Fitter                 = False,                   # if False a TrkVertexFitterTool will be used
+                                        TrkVertexFitterTool         = MUON2_VertexTools.TrkVKalVrtFitter,        # VKalVrt vertex fitter
+                                        TrackSelectorTool           = MUON2_VertexTools.InDetTrackSelectorTool,
+                                        ConversionFinderHelperTool  = MUON2_VertexTools.InDetConversionHelper,
+                                        VertexPointEstimator        = MUON2_VertexTools.VtxPointEstimator,
+                                        useMCPCuts                  = False)
+ToolSvc += MUON2JpsiFinder
+print      MUON2JpsiFinder
+
+#--------------------------------------------------------------------
+## 3/ setup the vertex reconstruction "call" tool(s). They are part of the derivation framework.
+##    These Augmentation tools add output vertex collection(s) into the StoreGate and add basic 
+##    decorations which do not depend on the vertex mass hypothesis (e.g. lxy, ptError, etc).
+##    There should be one tool per topology, i.e. Jpsi and Psi(2S) do not need two instance of the
+##    Reco tool is the JpsiFinder mass window is wide enough.
+from DerivationFrameworkBPhys.DerivationFrameworkBPhysConf import DerivationFramework__Reco_mumu
+MUON2JpsiSelectAndWrite = DerivationFramework__Reco_mumu(name                 = "MUON2JpsiSelectAndWrite",
+                                                       JpsiFinder             = MUON2JpsiFinder,
+                                                       OutputVtxContainerName = "MUON2JpsiCandidates",
+                                                       PVContainerName        = "PrimaryVertices",
+                                                       RefPVContainerName     = "SHOULDNOTBEUSED",
+                                                       DoVertexType           =1)
+ToolSvc += MUON2JpsiSelectAndWrite
+print MUON2JpsiSelectAndWrite
+
+
+from DerivationFrameworkBPhys.DerivationFrameworkBPhysConf import DerivationFramework__Select_onia2mumu
+
+## a/ augment and select Jpsi->mumu candidates
+MUON2_Select_Jpsi2mumu = DerivationFramework__Select_onia2mumu(
+  name                  = "MUON2_Select_Jpsi2mumu",
+  HypothesisName        = "Jpsi",
+  InputVtxContainerName = "MUON2JpsiCandidates",
+  VtxMassHypo           = 3096.916,
+  MassMin               = 2000.0,
+  MassMax               = 3600.0,
+  Chi2Max               = 200,
+  DoVertexType =1)
+
+  
+ToolSvc += MUON2_Select_Jpsi2mumu
+print      MUON2_Select_Jpsi2mumu
+
+
+
+
+## 4/ setup a new vertexing tool (necessary due to use of mass constraint) 
+from TrkVKalVrtFitter.TrkVKalVrtFitterConf import Trk__TrkVKalVrtFitter
+BsKKVertexFit = Trk__TrkVKalVrtFitter(
+                                         name                = "BsKKVertexFit",
+                                         Extrapolator        = MUON2_VertexTools.InDetExtrapolator,
+                                         FirstMeasuredPoint  = True,
+                                         MakeExtendedVertex  = True)
+ToolSvc += BsKKVertexFit
+print      BsKKVertexFit
+
+from TrkVKalVrtFitter.TrkVKalVrtFitterConf import Trk__TrkVKalVrtFitter
+BplKplVertexFit = Trk__TrkVKalVrtFitter(
+                                         name                = "BplKplVertexFit",
+                                         Extrapolator        = MUON2_VertexTools.InDetExtrapolator,
+                                         FirstMeasuredPoint  = True,
+                                         MakeExtendedVertex  = True)
+ToolSvc += BplKplVertexFit
+print      BplKplVertexFit
+
+
+## 5/ setup the Jpsi+2 track finder
+from JpsiUpsilonTools.JpsiUpsilonToolsConf import Analysis__JpsiPlus2Tracks
+MUON2BsJpsiKK = Analysis__JpsiPlus2Tracks(name = "MUON2BsJpsiKK",
+                                        OutputLevel = INFO,
+kaonkaonHypothesis			= True,
+pionpionHypothesis                      = False,
+kaonpionHypothesis                      = False,
+trkThresholdPt			        = 800.0,
+trkMaxEta				    = 3.0,
+BMassUpper				    = 5800.0,
+BMassLower				    = 5000.0,
+#DiTrackMassUpper = 1019.445 + 100.,
+#DiTrackMassLower = 1019.445 - 100.,
+Chi2Cut                     = 20.0,
+TrkQuadrupletMassUpper      = 6000.0,
+TrkQuadrupletMassLower      = 4800.0,
+JpsiContainerKey		    = "MUON2JpsiCandidates",
+TrackParticleCollection     = "InDetTrackParticles",
+MuonsUsedInJpsi			    = "Muons",
+ExcludeJpsiMuonsOnly        = True,
+ExcludeCrossJpsiTracks      = False,
+TrkVertexFitterTool		    = BsKKVertexFit,
+TrackSelectorTool		    = MUON2_VertexTools.InDetTrackSelectorTool,
+UseMassConstraint		    = True)
+
+ToolSvc += MUON2BsJpsiKK
+print      MUON2BsJpsiKK    
+
+## 5a/ setup the Jpsi+1 track finder
+from JpsiUpsilonTools.JpsiUpsilonToolsConf import Analysis__JpsiPlus1Track
+MUON2BplJpsiKpl = Analysis__JpsiPlus1Track(name = "MUON2BplJpsiKpl",
+OutputLevel             = INFO,#DEBUG,
+pionHypothesis			= True,
+kaonHypothesis			= True,
+trkThresholdPt			= 750.0,
+trkMaxEta			= 3.0,
+BThresholdPt			= 4000.0,
+BMassUpper			= 7000.0,
+BMassLower			= 4500.0,
+Chi2Cut                         = 60.0,
+TrkTrippletMassUpper            = 8000,
+TrkTrippletMassLower            = 4000,
+JpsiContainerKey		= "MUON2JpsiCandidates",
+TrackParticleCollection         = "InDetTrackParticles",
+MuonsUsedInJpsi			= "Muons",
+TrkVertexFitterTool		= BplKplVertexFit,
+TrackSelectorTool		= MUON2_VertexTools.InDetTrackSelectorTool,
+UseMassConstraint		= True)
+        
+ToolSvc += MUON2BplJpsiKpl
+print      MUON2BplJpsiKpl    
+
+
+## 6/ setup the combined augmentation/skimming tool for the Bpm
+from DerivationFrameworkBPhys.DerivationFrameworkBPhysConf import DerivationFramework__Reco_dimuTrkTrk	
+MUON2BsKKSelectAndWrite = DerivationFramework__Reco_dimuTrkTrk(name                 = "MUON2BsKKSelectAndWrite",
+                                                           Jpsi2PlusTrackName       = MUON2BsJpsiKK,
+                                                           OutputVtxContainerName   = "BsJpsiKKCandidates",
+                                                           PVContainerName          = "PrimaryVertices",
+                                                           RefPVContainerName       = "MUON2RefittedPrimaryVertices",
+                                                           RefitPV                  = True,
+                                                           MaxPVrefit               = 10000, DoVertexType = 7)
+ToolSvc += MUON2BsKKSelectAndWrite 
+print      MUON2BsKKSelectAndWrite
+
+from DerivationFrameworkBPhys.DerivationFrameworkBPhysConf import DerivationFramework__Reco_dimuTrk
+MUON2BplKplSelectAndWrite = DerivationFramework__Reco_dimuTrk(name				     	= "MUON2BplKplSelectAndWrite",
+															  Jpsi1PlusTrackName	    =  MUON2BplJpsiKpl,
+															  OutputVtxContainerName 	= "BpmJpsiKpmCandidates",
+                                                              PVContainerName           = "PrimaryVertices",
+                                                              RefPVContainerName        = "MUON2RefBplJpsiKplPrimaryVertices",                                                              
+                                                              RefitPV                   = True,
+                                                              MaxPVrefit                = 10000 )
+ToolSvc += MUON2BplKplSelectAndWrite
+print      MUON2BplKplSelectAndWrite
+
+
+## b/ augment and select Bs->JpsiKK candidates
+MUON2_Select_Bs2JpsiKK = DerivationFramework__Select_onia2mumu(
+  name                       = "MUON2_Select_Bs2JpsiKK",
+  HypothesisName             = "Bs",
+  InputVtxContainerName      = "BsJpsiKKCandidates",
+  TrkMasses                  = [105.658, 105.658, 493.677, 493.677],
+  VtxMassHypo                = 5366.3,
+  MassMin                    = 5000.0,
+  MassMax                    = 5800.0,
+  Chi2Max                    = 200)
+
+ToolSvc += MUON2_Select_Bs2JpsiKK
+print      MUON2_Select_Bs2JpsiKK
+
+MUON2_Select_Bpl2JpsiKpl     = DerivationFramework__Select_onia2mumu(
+  name                       = "MUON2_Select_Bpl2JpsiKpl",
+  HypothesisName             = "Bplus",
+  InputVtxContainerName      = "BpmJpsiKpmCandidates",
+  TrkMasses                  = [105.658, 105.658, 493.677],
+  VtxMassHypo                = 5279.26,
+  MassMin                    = 5279.26 - 500,
+  MassMax                    = 5279.26 + 500,
+  Chi2Max                    = MUON2BplJpsiKpl.Chi2Cut)
+
+ToolSvc += MUON2_Select_Bpl2JpsiKpl
+print      MUON2_Select_Bpl2JpsiKpl
+
+MUON2_Select_Bpl2JpsiPi      = DerivationFramework__Select_onia2mumu(
+  name                       = "MUON2_Select_Bpl2JpsiPi",
+  HypothesisName             = "Bc",
+  InputVtxContainerName      = "BpmJpsiKpmCandidates",
+  TrkMasses                  = [105.658, 105.658, 139.570],
+  VtxMassHypo                = 6275.1,
+  MassMin                    = 6275.1 - 500,
+  MassMax                    = 6275.1 + 500,
+  Chi2Max                    = MUON2BplJpsiKpl.Chi2Cut)
+
+ToolSvc += MUON2_Select_Bpl2JpsiPi
+print      MUON2_Select_Bpl2JpsiPi
+
+#expression = "count(BpmJpsiKpmCandidates.passed_Bplus) > 0"
+#from DerivationFrameworkTools.DerivationFrameworkToolsConf import DerivationFramework__xAODStringSkimmingTool
+#MUON2_SelectEvent = DerivationFramework__xAODStringSkimmingTool(name = "MUON2_SelectEvent",
+#                                                                expression = expression)
+#ToolSvc += MUON2_SelectEvent
+#print MUON2_SelectEvent
+
+
+#from DerivationFrameworkBPhys.DerivationFrameworkBPhysConf import DerivationFramework__SelectEvent
+
+if not isSimulation: #Only Skim Data
+   from DerivationFrameworkTools.DerivationFrameworkToolsConf import DerivationFramework__xAODStringSkimmingTool
+   MUON2_SelectBsJpsiKKEvent = DerivationFramework__xAODStringSkimmingTool(
+     name = "MUON2_SelectBsJpsiKKEvent",
+     expression = "count(BsJpsiKKCandidates.passed_Bs > 0) > 0")
+                                                    
+   ToolSvc += MUON2_SelectBsJpsiKKEvent
+   print MUON2_SelectBsJpsiKKEvent
+
+   MUON2_SelectBplJpsiKplEvent = DerivationFramework__xAODStringSkimmingTool(name = "MUON2_SelectBplJpsiKplEvent",
+                                                                    expression = "count(BpmJpsiKpmCandidates.passed_Bplus>0) > 0")
+   ToolSvc += MUON2_SelectBplJpsiKplEvent
+   print      MUON2_SelectBplJpsiKplEvent
+
+   MUON2_SelectBplJpsiKplEventBc = DerivationFramework__xAODStringSkimmingTool(name = "MUON2_SelectBplJpsiKplEventBc",
+                                                                    expression = "count(BpmJpsiKpmCandidates.passed_Bc>0) > 0")
+   ToolSvc += MUON2_SelectBplJpsiKplEventBc
+   print      MUON2_SelectBplJpsiKplEventBc
+   
+   #====================================================================
+   # Make event selection based on an OR of the input skimming tools
+   #====================================================================
+   from DerivationFrameworkTools.DerivationFrameworkToolsConf import DerivationFramework__FilterCombinationOR
+   MUON2SkimmingOR = CfgMgr.DerivationFramework__FilterCombinationOR("MUON2SkimmingOR",
+                                                                     FilterList = [MUON2_SelectBsJpsiKKEvent, MUON2_SelectBplJpsiKplEvent, MUON2_SelectBplJpsiKplEventBc])
+   ToolSvc += MUON2SkimmingOR
+   print      MUON2SkimmingOR
+
+from DerivationFrameworkBPhys.DerivationFrameworkBPhysConf import DerivationFramework__Thin_vtxTrk
+MUON2_thinningTool_Tracks = DerivationFramework__Thin_vtxTrk(
+  name                       = "MUON2_thinningTool_Tracks",
+  ThinningService            = "MUON2ThinningSvc",
+  TrackParticleContainerName = "InDetTrackParticles",
+  VertexContainerNames       = ["BsJpsiKKCandidates", "BpmJpsiKpmCandidates"],
+  PassFlags                  = ["passed_Bs", "passed_Bplus", "passed_Bc"] )
+
+ToolSvc += MUON2_thinningTool_Tracks
+
+from DerivationFrameworkBPhys.DerivationFrameworkBPhysConf import DerivationFramework__BPhysPVThinningTool
+MUON2_thinningTool_PV = DerivationFramework__BPhysPVThinningTool(
+  name                       = "MUON2_thinningTool_PV",
+  ThinningService            = "MUON2ThinningSvc",
+  CandidateCollections       = ["BsJpsiKKCandidates", "BpmJpsiKpmCandidates"],
+  KeepPVTracks  =True
+ )
+
+ToolSvc += MUON2_thinningTool_PV
+
+
+## b) thinning out tracks that are not attached to muons. The final thinning decision is based on the OR operation
+##    between decision from this and the previous tools.
 from DerivationFrameworkInDet.DerivationFrameworkInDetConf import DerivationFramework__MuonTrackParticleThinning
-MUON2ThinningTool2 = DerivationFramework__MuonTrackParticleThinning(name                    = "MUON2ThinningTool2",
-                                                                    ThinningService         = "MUON2ThinningSvc",
-                                                                    MuonKey                 = "Muons",
-                                                                    SelectionString         = thinning_expression2,
-                                                                    ConeSize                = 0.5,
-                                                                    ApplyAnd                = False,
-                                                                    InDetTrackParticlesKey  = "InDetTrackParticles")
-ToolSvc += MUON2ThinningTool2
+MUON2MuonTPThinningTool = DerivationFramework__MuonTrackParticleThinning(name                    = "MUON2MuonTPThinningTool",
+                                                                         ThinningService         = "MUON2ThinningSvc",
+                                                                         MuonKey                 = "Muons",
+                                                                         InDetTrackParticlesKey  = "InDetTrackParticles")
+ToolSvc += MUON2MuonTPThinningTool
+
+from DerivationFrameworkInDet.DerivationFrameworkInDetConf import DerivationFramework__EgammaTrackParticleThinning
+MUON2ElectronTPThinningTool = DerivationFramework__EgammaTrackParticleThinning(  
+    name                    = "MUON2ElectronTPThinningTool",
+    ThinningService         = "MUON2ThinningSvc",
+    SGKey                   = "Electrons",
+    GSFTrackParticlesKey = "GSFTrackParticles",        
+    InDetTrackParticlesKey  = "InDetTrackParticles",
+    SelectionString = "",
+    BestMatchOnly = True,
+    ConeSize = 0.3,
+    ApplyAnd = False)
 
+ToolSvc+=MUON2ElectronTPThinningTool
 #====================================================================
-# JetTagNonPromptLepton decorations
+# CREATE THE DERIVATION KERNEL ALGORITHM AND PASS THE ABOVE TOOLS  
 #====================================================================
-if not hasattr(DerivationFrameworkJob,"MUONSequence"):
-    MUONSeq = CfgMgr.AthSequencer("MUONSequence")
-    DerivationFrameworkJob += MUONSeq
 
-    if not hasattr(MUONSeq,"Muons_decoratePromptLepton"):
-        import JetTagNonPromptLepton.JetTagNonPromptLeptonConfig as Config
-        MUONSeq += Config.GetDecoratePromptLeptonAlgs()
+thiningCollection = [] 
+print thiningCollection
 
-#====================================================================
-# CREATE THE DERIVATION KERNEL ALGORITHM AND PASS THE ABOVE TOOLS 
-#====================================================================
+from DerivationFrameworkJetEtMiss.JetCommon import *
+bphy5Seq = CfgMgr.AthSequencer("MUON2Sequence")
+DerivationFrameworkJob += bphy5Seq
+
+# The name of the kernel (MUON2Kernel in this case) must be unique to this derivation
 from DerivationFrameworkCore.DerivationFrameworkCoreConf import DerivationFramework__DerivationKernel
-DerivationFrameworkJob += CfgMgr.DerivationFramework__DerivationKernel("MUON2Kernel",
-                                                                       AugmentationTools = [MUON2AugmentTool1, MUON2AugmentTool2, MUON2AugmentTool3],
-                                                                       SkimmingTools = [MUON2SkimmingTool1],
-                                                                       ThinningTools = [MUON2ThinningTool1, MUON2ThinningTool2]
+bphy5Seq += CfgMgr.DerivationFramework__DerivationKernel("MUON2Kernel",
+                                                                       AugmentationTools = [MUON2JpsiSelectAndWrite,  MUON2_Select_Jpsi2mumu,
+                                                                                            MUON2BsKKSelectAndWrite,  MUON2_Select_Bs2JpsiKK,
+                                                                                            MUON2BplKplSelectAndWrite,MUON2_Select_Bpl2JpsiKpl, MUON2_Select_Bpl2JpsiPi,
+                                                                                            MUON2_AugOriginalCounts],
+                                                                       #Only skim if not MC
+                                                                       SkimmingTools     = [MUON2SkimmingOR] if not isSimulation else [],
+                                                                       ThinningTools     = thiningCollection
+                                                                       
                                                                        )
+
 #====================================================================
 # SET UP STREAM   
 #====================================================================
-streamName = derivationFlags.WriteDAOD_MUON2Stream.StreamName
-fileName   = buildFileName( derivationFlags.WriteDAOD_MUON2Stream )
-MUON2Stream = MSMgr.NewPoolRootStream( streamName, fileName )
+streamName   = derivationFlags.WriteDAOD_MUON2Stream.StreamName
+fileName     = buildFileName( derivationFlags.WriteDAOD_MUON2Stream )
+MUON2Stream  = MSMgr.NewPoolRootStream( streamName, fileName )
 MUON2Stream.AcceptAlgs(["MUON2Kernel"])
+
 # Special lines for thinning
 # Thinning service name must match the one passed to the thinning tools
 from AthenaServices.Configurables import ThinningSvc, createThinningSvc
 augStream = MSMgr.GetStream( streamName )
 evtStream = augStream.GetEventStream()
-svcMgr += createThinningSvc( svcName="MUON2ThinningSvc", outStreams=[evtStream] )
+
+MUON2ThinningSvc = createThinningSvc( svcName="MUON2ThinningSvc", outStreams=[evtStream] )
+svcMgr += MUON2ThinningSvc
+
 #====================================================================
-# Add the containers to the output stream - slimming done here
+# Slimming 
 #====================================================================
-from DerivationFrameworkMuons.StreamConfig import MuonsDxAODStreamConfigurer as conf
-conf.Config(MUON2Stream, 'MUON2')
+
+# Added by ASC
+from DerivationFrameworkCore.SlimmingHelper import SlimmingHelper
+MUON2SlimmingHelper = SlimmingHelper("MUON2SlimmingHelper")
+AllVariables  = []
+StaticContent = []
+
+# Needed for trigger objects
+MUON2SlimmingHelper.IncludeMuonTriggerContent  = TRUE
+MUON2SlimmingHelper.IncludeBPhysTriggerContent = TRUE
+
+## primary vertices
+AllVariables  += ["PrimaryVertices"]
+StaticContent += ["xAOD::VertexContainer#MUON2RefittedPrimaryVertices"]
+StaticContent += ["xAOD::VertexAuxContainer#MUON2RefittedPrimaryVerticesAux."]
+StaticContent += ["xAOD::VertexContainer#MUON2RefBplJpsiKplPrimaryVertices"]
+StaticContent += ["xAOD::VertexAuxContainer#MUON2RefBplJpsiKplPrimaryVerticesAux."]
+
+
+
+## ID track particles
+AllVariables += ["InDetTrackParticles"]
+
+## combined / extrapolated muon track particles 
+## (note: for tagged muons there is no extra TrackParticle collection since the ID tracks
+##        are store in InDetTrackParticles collection)
+AllVariables += ["CombinedMuonTrackParticles"]
+AllVariables += ["ExtrapolatedMuonTrackParticles"]
+
+## muon container
+AllVariables += ["Muons"] 
+
+
+## Jpsi candidates 
+StaticContent += ["xAOD::VertexContainer#%s"        %                 MUON2JpsiSelectAndWrite.OutputVtxContainerName]
+## we have to disable vxTrackAtVertex branch since it is not xAOD compatible
+StaticContent += ["xAOD::VertexAuxContainer#%sAux.-vxTrackAtVertex" % MUON2JpsiSelectAndWrite.OutputVtxContainerName]
+
+StaticContent += ["xAOD::VertexContainer#%s"        %                 MUON2BsKKSelectAndWrite.OutputVtxContainerName]
+StaticContent += ["xAOD::VertexAuxContainer#%sAux.-vxTrackAtVertex" % MUON2BsKKSelectAndWrite.OutputVtxContainerName]
+
+StaticContent += ["xAOD::VertexContainer#%s"        %                 MUON2BplKplSelectAndWrite.OutputVtxContainerName]
+StaticContent += ["xAOD::VertexAuxContainer#%sAux.-vxTrackAtVertex" % MUON2BplKplSelectAndWrite.OutputVtxContainerName]
+
+
+# Tagging information (in addition to that already requested by usual algorithms)
+#AllVariables += ["Electrons"] 
+AllVariables += ["GSFTrackParticles", "Electrons" , "Photons", "MuonSpectrometerTrackParticles" ]
+tagJetCollections = ['AntiKt4LCTopoJets', 'AntiKt4EMTopoJets', 'AntiKt4PV0TrackJets']
+
+AllVariables += [ "Kt4LCTopoOriginEventShape", "Kt4EMTopoOriginEventShape" ]
+SmartVar = [] #[ tagJetCollections ]
+
+
+
+
+for jet_collection in tagJetCollections:
+    AllVariables   += [jet_collection]
+    AllVariables   += ["BTagging_%s"       % (jet_collection[:-4]) ]
+    AllVariables   += ["BTagging_%sJFVtx"  % (jet_collection[:-4]) ]
+    AllVariables   += ["BTagging_%sSecVtx" % (jet_collection[:-4]) ]
+
+#addStandardJets("AntiKt", 0.4, "PV0Track", 2000, mods="track_ungroomed", algseq=bphy5Seq, outputGroup="MUON2")
+
+
+# Added by ASC
+# Truth information for MC only
+if isSimulation:
+    AllVariables += ["TruthEvents","TruthParticles","TruthVertices","MuonTruthParticles", "egammaTruthParticles" ]
+    AllVariables += ["AntiKt4TruthJets", "AntiKt4TruthWZJets" ]
+#    addStandardJets("AntiKt", 0.4, "Truth", 5000, mods="truth_ungroomed", algseq=bphy5Seq, outputGroup="MUON2")
+#    addStandardJets("AntiKt", 0.4, "TruthWZ", 5000, mods="truth_ungroomed", algseq=bphy5Seq, outputGroup="MUON2")
+    tagJetCollections += [ "AntiKt4TruthJets", "AntiKt4TruthWZJets"  ]
+
+from DerivationFrameworkJetEtMiss.ExtendedJetCommon import replaceAODReducedJets
+replaceAODReducedJets(tagJetCollections, bphy5Seq  ,  "MUON2" )
+
+
+AllVariables = list(set(AllVariables)) # remove duplicates
+
+MUON2SlimmingHelper.AllVariables = AllVariables
+MUON2SlimmingHelper.StaticContent = StaticContent
+MUON2SlimmingHelper.SmartCollections = SmartVar
+
+MUON2SlimmingHelper.AppendContentToStream(MUON2Stream)
+
+
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/share/MUON3.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/share/MUON3.py
index 9ff2c08304c..b2b18fa09d5 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/share/MUON3.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/share/MUON3.py
@@ -9,7 +9,18 @@ from DerivationFrameworkCore.DerivationFrameworkMaster import *
 from DerivationFrameworkMuons.MuonsCommon import *
 # from DerivationFrameworkJetEtMiss.METCommon import *
 import AthenaCommon.SystemOfUnits as Units
-from MuonPerformanceAlgs.CommonMuonTPConfig import GetIDTrackCaloDepositsDecorator
+if not hasattr(ToolSvc,"IDTrackCaloDepositsDecoratorTool"):
+  from DerivationFrameworkMuons.DerivationFrameworkMuonsConf import IDTrackCaloDepositsDecoratorTool
+  DecoTool = IDTrackCaloDepositsDecoratorTool("IDTrackCaloDepositsDecoratorTool")
+  if hasattr(DecoTool, "TrackDepositInCaloTool"):
+    if not hasattr(ToolSvc,"TrkDepositInCaloTool"):
+        from CaloTrkMuIdTools.CaloTrkMuIdToolsConf import TrackDepositInCaloTool
+        TrkDepositInCaloTool = TrackDepositInCaloTool("TrkDepositInCaloTool")
+        TrkDepositInCaloTool.CaloCellContainerName = "AODCellContainer"
+        ToolSvc += TrkDepositInCaloTool
+    DecoTool.TrackDepositInCaloTool = ToolSvc.TrkDepositInCaloTool
+
+    ToolSvc += DecoTool
 
 #====================================================================
 # AUGMENTATION TOOLS
@@ -35,7 +46,7 @@ andTriggers1_run2 = [] # No trigger in 8TeV data
 
 andTriggers1 = andTriggers1_run2
 MUON3AugmentTool1 = DerivationFramework__dimuonTaggingTool(name = "MUON3AugmentTool1",
-                                                           IDTrackCaloDepoDecoTool = GetIDTrackCaloDepositsDecorator(),
+                                                           IDTrackCaloDepoDecoTool = ToolSvc.IDTrackCaloDepositsDecoratorTool,
                                                            OrTrigs = orTriggers1,
                                                            AndTrigs = andTriggers1,
                                                            Mu1PtMin = 5.*Units.GeV,
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/share/MUON5.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/share/MUON5.py
new file mode 100644
index 00000000000..4260315f0b9
--- /dev/null
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/share/MUON5.py
@@ -0,0 +1,297 @@
+#**********************************************************************
+# MUON5.py 
+#
+# reductionConf flag MUON5 in Reco_tf.py 
+#
+# -- For training and analysing non-prompt lepton tagging algorithms --
+# -- Saves electron, muon and taus for matching with track-jets and 
+#    associated b-tagging containers                                 --
+#
+#**********************************************************************
+
+#======================================================================
+# IMPORT DERIVATION MODULES
+#======================================================================
+
+from DerivationFrameworkCore.DerivationFrameworkMaster import *
+from DerivationFrameworkInDet.InDetCommon              import *
+from DerivationFrameworkJetEtMiss.JetCommon            import *
+from DerivationFrameworkEGamma.EGammaCommon            import *
+from DerivationFrameworkMuons.MuonsCommon              import *
+from DerivationFrameworkFlavourTag.FlavourTagCommon    import *
+from DerivationFrameworkHiggs.TruthCategories          import *
+
+from AthenaCommon.GlobalFlags import globalflags
+
+# Check if is MC
+is_MC = (globalflags.DataSource()=='geant4')
+
+if is_MC:
+  from DerivationFrameworkMCTruth.MCTruthCommon import addStandardTruthContents
+  addStandardTruthContents()
+
+#======================================================================
+# SET UP STREAM   
+#======================================================================
+
+streamName  = derivationFlags.WriteDAOD_MUON5Stream.StreamName
+fileName    = buildFileName(derivationFlags.WriteDAOD_MUON5Stream)
+MUON5Stream = MSMgr.NewPoolRootStream(streamName, fileName)
+MUON5Stream.AcceptAlgs(["MUON5Kernel"])
+
+#====================================================================
+# CREATE PRIVATE SEQUENCE  
+#====================================================================
+
+MUON5Seq = CfgMgr.AthSequencer("MUON5Sequence")
+
+#====================================================================
+# RESTORE JET COLLECTIONS AND RUN BTAGGING
+#====================================================================
+
+# Replace jet collections dropped from primaries in r21
+from DerivationFrameworkJetEtMiss.ExtendedJetCommon import replaceAODReducedJets
+
+# Replace missing collections
+replaceAODReducedJets(["AntiKt4PV0TrackJets", "AntiKt4TruthJets"], MUON5Seq, "MUON5")
+
+# Run b-tagging on AntiKt4PV0TrackJets
+btag_algs  = ['IP2D', 'IP3D', 'MultiSVbb1',  'MultiSVbb2', 'SV1', 'JetFitterNN', 'SoftMu', 'MV2c10', 'MV2c10mu', 'MV2c10rnn']
+btag_algs += ['JetVertexCharge', 'MV2c100', 'MV2cl100' , 'DL1', 'DL1rnn', 'DL1mu', 'RNNIP']
+
+ReTag(btag_algs, ['AntiKt4PV0TrackJets'], MUON5Seq)
+
+#======================================================================
+# AUGMENTATION TOOLS
+#======================================================================
+
+augmentationTools = []
+
+#======================================================================
+# TAU TRUTH MATCHING TOOL
+#======================================================================
+
+if is_MC:
+    from DerivationFrameworkTau.TauTruthCommon import *
+    
+#======================================================================
+# TAU OVERLAPPING ELECTRON LLH DECORATORS 
+#======================================================================
+
+from TauAnalysisTools.TauAnalysisToolsConf             import TauAnalysisTools__TauOverlappingElectronLLHDecorator
+from DerivationFrameworkTau.DerivationFrameworkTauConf import DerivationFramework__TauOverlappingElectronLLHDecoratorWrapper
+
+# Tau Overlapping Electron LLH Decorator
+MUON5TauOrlElLLHDec = TauAnalysisTools__TauOverlappingElectronLLHDecorator(name                  = "MUON5TauOrlElLLHDec",
+                                                                           ElectronContainerName = "Electrons")  
+ToolSvc += MUON5TauOrlElLLHDec
+   
+# Tau Overlapping Electron LLH Decorator Wrapper
+MUON5TauOrlElLLHDecWrapper = DerivationFramework__TauOverlappingElectronLLHDecoratorWrapper(name                               = "MUON5TauOrlElLLHDecWrapper",
+                                                                                            TauOverlappingElectronLLHDecorator = MUON5TauOrlElLLHDec,
+                                                                                            TauContainerName                   = "TauJets")
+ToolSvc += MUON5TauOrlElLLHDecWrapper
+
+augmentationTools.append(MUON5TauOrlElLLHDecWrapper)
+
+#======================================================================
+# BACKGROUND ELECTRON DECORATION TYPE/ORIGIN
+#======================================================================
+# PhysicsAnalysis/DerivationFramework/DerivationFrameworkEGamma/trunk/src/BkgElectronClassification.cxx
+
+if is_MC:
+    from MCTruthClassifier.MCTruthClassifierBase import MCTruthClassifier as BkgElectronMCTruthClassifier   
+    from DerivationFrameworkEGamma.DerivationFrameworkEGammaConf import DerivationFramework__BkgElectronClassification 
+
+    MUON5BkgElectronClassificationTool = DerivationFramework__BkgElectronClassification (name                  = "MUON5BkgElectronClassificationTool",
+                                                                                         MCTruthClassifierTool = BkgElectronMCTruthClassifier)
+
+    ToolSvc += MUON5BkgElectronClassificationTool
+
+    augmentationTools.append(MUON5BkgElectronClassificationTool)
+
+    print "BkgElectronClassificationTool: ", MUON5BkgElectronClassificationTool
+
+#====================================================================
+# THINNING TOOLS
+#====================================================================
+
+thinningTools = []
+
+# Establish the thinning helper (which will set up the services behind the scenes)
+from DerivationFrameworkCore.ThinningHelper import ThinningHelper
+
+MUON5ThinningHelper = ThinningHelper("MUON5ThinningHelper")
+
+# Trigger Thinning Tool
+MUON5ThinningHelper.TriggerChains = 'HLT_e.*|HLT_mu.*|HLT_2e.*|HLT_2mu.*|HLT_tau.*'
+MUON5ThinningHelper.AppendToStream(MUON5Stream)
+
+#====================================================================
+# TRACK THINNING
+#====================================================================
+
+do_track_thinning = False
+
+from DerivationFrameworkInDet.DerivationFrameworkInDetConf import DerivationFramework__TrackParticleThinning
+MUON5TrackThinningTool = DerivationFramework__TrackParticleThinning(name                    = "MUON5TrackThinningTool",
+                                                                    ThinningService         = MUON5ThinningHelper.ThinningSvc(),
+                                                                    SelectionString         = "abs(DFCommonInDetTrackZ0AtPV) < 10.0",
+                                                                    InDetTrackParticlesKey  = "InDetTrackParticles")
+if do_track_thinning:
+    ToolSvc += MUON5TrackThinningTool
+    thinningTools.append(MUON5TrackThinningTool)
+
+#====================================================================
+# TRUTH THINNING
+#====================================================================
+
+do_truth_thinning = False
+
+truth_cond_ew    = "((abs(TruthParticles.pdgId) >= 23) && (abs(TruthParticles.pdgId) <= 25))" # W, Z and Higgs
+truth_cond_lep   = "((abs(TruthParticles.pdgId) >= 11) && (abs(TruthParticles.pdgId) <= 16))" # Leptons
+truth_cond_top   = "((abs(TruthParticles.pdgId) == 6))"                                       # Top quark
+truth_cond_b     = "((abs(TruthParticles.pdgId) == 5))"                                       # b quark
+truth_cond_c     = "((abs(TruthParticles.pdgId) == 4))"                                       # c quark
+truth_cond_final = '(TruthParticles.status == 1 && TruthParticles.barcode < 200000)'          # stable particles
+
+truth_expression = '('+truth_cond_ew+' || '+truth_cond_lep+' || '+truth_cond_top+' || '+truth_cond_b+' || '+truth_cond_c+') || ('+truth_cond_final+')'
+
+# PreserveGeneratorDescendants only keeps particles that came directly from the event generator
+# PreserveDescendants keeps all particles including those that come from Geant processes
+
+from DerivationFrameworkMCTruth.DerivationFrameworkMCTruthConf import DerivationFramework__GenericTruthThinning
+from DerivationFrameworkMCTruth.DerivationFrameworkMCTruthConf import DerivationFramework__MenuTruthThinning
+
+MUON5TruthTool = DerivationFramework__GenericTruthThinning(name                         = "MUON5TruthThinningTool",
+                                                           ThinningService              = MUON5ThinningHelper.ThinningSvc(),
+                                                           ParticleSelectionString      = truth_expression,
+                                                           PreserveDescendants          = True,
+                                                           PreserveGeneratorDescendants = False,
+                                                           PreserveAncestors            = True)
+
+if is_MC and do_truth_thinning:
+    ToolSvc += MUON5TruthTool
+    thinningTools.append(MUON5TruthTool)    
+
+#====================================================================
+# CALO CLUSTER THINNING
+#====================================================================
+#  These tools thin any calorimeter clusters not associated to the 
+#  objects specified below
+
+from DerivationFrameworkCalo.DerivationFrameworkCaloConf import DerivationFramework__CaloClusterThinning
+
+# Egamma clusters associated with electrons
+MUON5ElectronEgammaCThinningTool = DerivationFramework__CaloClusterThinning( name                    = "MUON5ElectronEgammaCThinningTool",
+                                                                             ThinningService         = MUON5ThinningHelper.ThinningSvc(),
+                                                                             SGKey                   = "Electrons",
+                                                                             CaloClCollectionSGKey   = "egammaClusters",
+                                                                             SelectionString         = "Electrons.pt >= 4*GeV",
+                                                                             ConeSize                = 0.4)
+ToolSvc += MUON5ElectronEgammaCThinningTool
+thinningTools.append(MUON5ElectronEgammaCThinningTool)
+
+#====================================================================
+# SKIMMING TOOL 
+#====================================================================
+
+# Apply skimming requirement: at least one electron, muon or tau
+eleRequirements = '(Electrons.pt > 5*GeV) && (abs(Electrons.eta) < 2.6) && (Electrons.Loose || Electrons.DFCommonElectronsLHLoose)'
+muRequirements  = '(Muons.DFCommonGoodMuon) && (Muons.muonType == 0) && (Muons.pt > 5*GeV) && (abs(Muons.eta) < 2.6)'
+tauRequirements = '(TauJets.pt > 15*GeV) && (abs(TauJets.charge)==1.0) && ((TauJets.nTracks == 1) || (TauJets.nTracks == 3)) && (abs(TauJets.eta) < 2.6)'
+
+eSelection   = '(count('+eleRequirements+') >= 1)'
+mSelection   = '(count('+muRequirements +') >= 1)'
+tauSelection = '(count('+tauRequirements+') >= 1)'
+
+lepSelection = eSelection+' || '+mSelection+' || '+tauSelection
+
+from DerivationFrameworkTools.DerivationFrameworkToolsConf import DerivationFramework__xAODStringSkimmingTool
+
+MUON5SkimmingTool = DerivationFramework__xAODStringSkimmingTool(name       = "MUON5SkimmingTool",
+                                                                expression = lepSelection)
+ToolSvc += MUON5SkimmingTool
+
+#====================================================================
+# CREATE THE DERIVATION KERNEL ALGORITHM   
+#====================================================================
+
+from DerivationFrameworkCore.DerivationFrameworkCoreConf import DerivationFramework__DerivationKernel
+
+if is_MC:
+    from DerivationFrameworkCore.LHE3WeightMetadata import *
+
+DerivationFrameworkJob += CfgMgr.DerivationFramework__DerivationKernel("MUON5Kernel",
+                                                                       ThinningTools     = thinningTools,
+                                                                       AugmentationTools = augmentationTools,
+                                                                       SkimmingTools     = [MUON5SkimmingTool])
+# Add private sequence to DerivationFrameworkJob
+DerivationFrameworkJob += MUON5Seq
+
+#====================================================================
+# SLIMMING TOOL
+#====================================================================
+
+from DerivationFrameworkCore.SlimmingHelper import SlimmingHelper
+
+MUON5SlimmingHelper = SlimmingHelper("MUON5SlimmingHelper")
+
+# Smart slimming containers
+MUON5SlimmingHelper.SmartCollections = ["Electrons",
+                                        "Muons",
+                                        "TauJets",
+                                        "TauMVATESJets",
+                                        "MET_Reference_AntiKt4EMTopo",
+                                        "AntiKt4EMTopoJets",
+                                        "BTagging_AntiKt4EMTopo",
+                                        "PrimaryVertices"]
+
+# Append new b-tagging container to dictionary for saving
+MUON5SlimmingHelper.AppendToDictionary = {'BTagging_AntiKt4Track'   : 'xAOD::BTaggingContainer',
+                                          'BTagging_AntiKt4TrackAux': 'xAOD::BTaggingAuxContainer'}
+
+# Add extra variables to collections
+MUON5SlimmingHelper.ExtraVariables = ["Muons.clusterLink.allAuthors.charge.extrapolatedMuonSpectrometerTrackParticleLink."
+                                      "scatteringCurvatureSignificance.scatteringNeighbourSignificance",
+                                      "Electrons.author.charge",
+                                      "AntiKt4EMTopoJets.JetEMScaleMomentum_pt.JetEMScaleMomentum_eta.JetEMScaleMomentum_phi.JetEMScaleMomentum_m."
+                                      "ConeTruthLabelID.PartonTruthLabelID.SumPtTrkPt1000.Jvt.JvtJvfcorr.JvtRpt.TileStatus",
+                                      "GSFTrackParticles.z0.vz.definingParametersCovMatrix",
+                                      "CombinedMuonTrackParticles.z0.vz.definingParametersCovMatrix",
+                                      "ExtrapolatedMuonTrackParticles.z0.vz.definingParametersCovMatrix",
+                                      "PrimaryVertices.x.y.z.trackParticleLinks.vertexType.neutralParticleLinks",
+                                      "TauJets.pantau_CellBasedInput_isPanTauCandidate.pantau_CellBasedInput_DecayMode."
+                                      "ptPanTauCellBased.etaPanTauCellBased.phiPanTauCellBased.mPanTauCellBased."
+                                      "pantau_CellBasedInput_BDTValue_1p0n_vs_1p1n.pantau_CellBasedInput_BDTValue_1p1n_vs_1pXn."
+                                      "pantau_CellBasedInput_BDTValue_3p0n_vs_3pXn.ele_match_lhscore.ele_olr_pass."
+                                      "electronLink.ptDetectorAxis.etaDetectorAxis.phiDetectorAxis.mDetectorAxis",
+                                      "TauNeutralParticleFlowObjects.pt.eta.phi.m.e.rapidity.bdtPi0Score",
+                                      "TauChargedParticleFlowObjects.pt.eta.phi.m"]
+
+MUON5SlimmingHelper.AllVariables = ["egammaClusters", "CaloCalTopoClusters", "AntiKt4PV0TrackJets", "BTagging_AntiKt4Track", "InDetTrackParticles"]
+
+if is_MC:
+    MUON5SlimmingHelper.AllVariables += ["TruthParticles", "TruthEvents", "TruthVertices", "AntiKt4TruthJets"]
+
+    MUON5SlimmingHelper.ExtraVariables += ["Electrons.truthOrigin.truthType.truthParticleLink.bkgTruthType.bkgTruthOrigin."
+                                           "bkgTruthParticleLink.bkgMotherPdgId.deltaPhi1",
+                                           "MuonTruthParticles.truthOrigin.truthType.truthParticleLink",
+                                           "InDetTrackParticles.truthOrigin.truthType.truthParticleLink",
+                                           "CombinedMuonTrackParticles.truthOrigin.truthType.truthParticleLink",
+                                           "TauJets.IsTruthMatched.truthParticleLink.truthJetLink"]
+    
+    MUON5SlimmingHelper.StaticContent = ["xAOD::TruthParticleContainer#TruthMuons",
+                                         "xAOD::TruthParticleAuxContainer#TruthMuonsAux.",
+                                         "xAOD::TruthParticleContainer#TruthElectrons",
+                                         "xAOD::TruthParticleAuxContainer#TruthElectronsAux.",
+                                         "xAOD::TruthParticleContainer#TruthNeutrinos",
+                                         "xAOD::TruthParticleAuxContainer#TruthNeutrinosAux.",
+                                         "xAOD::TruthParticleContainer#TruthTaus",
+                                         "xAOD::TruthParticleAuxContainer#TruthTausAux."]    
+    
+MUON5SlimmingHelper.IncludeMuonTriggerContent  =True
+MUON5SlimmingHelper.IncludeEGammaTriggerContent=True
+MUON5SlimmingHelper.IncludeTauTriggerContent   =True
+ 
+MUON5SlimmingHelper.AppendContentToStream(MUON5Stream)
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/src/IDTrackCaloDepositsDecoratorTool.cxx b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/src/IDTrackCaloDepositsDecoratorTool.cxx
new file mode 100644
index 00000000000..6182cabb8c7
--- /dev/null
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/src/IDTrackCaloDepositsDecoratorTool.cxx
@@ -0,0 +1,191 @@
+/*
+ * IDTrackCaloDepositsDecoratorTool.cxx
+ *
+ *  Created on: Sep 29, 2015
+ *      Author: goblirsc
+ */
+
+
+#include "DerivationFrameworkMuons/IDTrackCaloDepositsDecoratorTool.h"
+
+#ifndef XAOD_ANALYSIS
+#include "muonEvent/DepositInCalo.h"
+#include "CaloEvent/CaloCellContainer.h"
+#endif
+
+#include "xAODMuon/Muon.h"
+#include "xAODTracking/TrackParticle.h"
+
+IDTrackCaloDepositsDecoratorTool::IDTrackCaloDepositsDecoratorTool(
+		std::string myname) :
+		AsgTool(myname),
+#ifndef XAOD_ANALYSIS
+		m_trkDepositInCalo("TrackDepositInCaloTool/TrackDepositInCaloTool"),
+#endif
+		m_dec_EMB1_dep("EMB1_dep"),
+		m_dec_EMB1_eloss("EMB1_eloss"),
+		m_dec_EMB2_dep("EMB2_dep"),
+		m_dec_EMB2_eloss("EMB2_eloss"),
+		m_dec_EMB3_dep("EMB3_dep"),
+		m_dec_EMB3_eloss("EMB3_eloss"),
+		m_dec_EME1_dep("EME1_dep"),
+		m_dec_EME1_eloss("EME1_eloss"),
+		m_dec_EME2_dep("EME2_dep"),
+		m_dec_EME2_eloss("EME2_eloss"),
+		m_dec_EME3_dep("EME3_dep"),
+		m_dec_EME3_eloss("EME3_eloss"),
+		m_dec_TileBar0_dep("TileBar0_dep"),
+		m_dec_TileBar0_eloss("TileBar0_eloss"),
+		m_dec_TileBar1_dep("TileBar1_dep"),
+		m_dec_TileBar1_eloss("TileBar1_eloss"),
+		m_dec_TileBar2_dep("TileBar2_dep"),
+		m_dec_TileBar2_eloss("TileBar2_eloss"),
+		m_dec_TileExt0_dep("TileExt0_dep"),
+		m_dec_TileExt0_eloss("TileExt0_eloss"),
+		m_dec_TileExt1_dep("TileExt1_dep"),
+		m_dec_TileExt1_eloss("TileExt1_eloss"),
+		m_dec_TileExt2_dep("TileExt2_dep"),
+		m_dec_TileExt2_eloss("TileExt2_eloss"),
+		m_dec_HEC0_dep("HEC0_dep"),
+		m_dec_HEC0_eloss("HEC0_eloss"),
+		m_dec_HEC1_dep("HEC1_dep"),
+		m_dec_HEC1_eloss("HEC1_eloss"),
+		m_dec_HEC2_dep("HEC2_dep"),
+		m_dec_HEC2_eloss("HEC2_eloss"),
+		m_dec_HEC3_dep("HEC3_dep"),
+		m_dec_HEC3_eloss("HEC3_eloss")
+{
+#ifndef XAOD_ANALYSIS
+	declareProperty("TrackDepositInCaloTool", m_trkDepositInCalo);
+#endif
+}
+
+StatusCode IDTrackCaloDepositsDecoratorTool::initialize() {
+
+#ifndef XAOD_ANALYSIS
+	ATH_CHECK(m_trkDepositInCalo.retrieve());
+#endif
+	return StatusCode::SUCCESS;
+
+}
+
+StatusCode IDTrackCaloDepositsDecoratorTool::decorate(const xAOD::IParticle* part) const 
+{
+	static SG::AuxElement::Decorator< bool > appliedDec( "AppliedIso" );
+
+	// remember if we already decorated a track, saves CPU time
+	if (part->isAvailable<bool>("AppliedCaloDep") && part->auxdataConst<bool>("AppliedCaloDep")){
+		ATH_MSG_DEBUG("Already decorated this track!");
+		return StatusCode::SUCCESS;
+	}
+
+	return recompute_and_decorate(part);
+}
+
+StatusCode IDTrackCaloDepositsDecoratorTool::recompute_and_decorate(const xAOD::IParticle* part) const
+{
+	static SG::AuxElement::Decorator< bool > appliedDec( "AppliedCaloDep" );
+	ATH_MSG_DEBUG("Recomputing calo deposition by hand");
+
+	const xAOD::TrackParticle* tp = dynamic_cast<const xAOD::TrackParticle*>(part);
+	if(!tp) {
+		const xAOD::Muon* muon = dynamic_cast<const xAOD::Muon*>(part);
+		if (muon) {
+			tp = muon->trackParticle(xAOD::Muon::Primary);
+		}
+	}
+
+	if(!tp) {
+		ATH_MSG_ERROR("Unable to retrieve xAOD::TrackParticle from probe object");
+		return StatusCode::FAILURE;
+	}
+
+
+#ifndef XAOD_ANALYSIS
+	const CaloCellContainer* caloCellCont = 0;
+	std::vector<DepositInCalo> deposits = m_trkDepositInCalo->getDeposits(&(tp->perigeeParameters()), caloCellCont);
+	appliedDec(*part) = true;
+
+	std::vector<DepositInCalo>::const_iterator it = deposits.begin();
+	for (;it!=deposits.end(); it++) {
+
+		CaloCell_ID::CaloSample sample = it->subCaloId();
+
+		double dep   = it->energyDeposited();
+		double eloss = it->muonEnergyLoss();
+
+		if (sample==CaloCell_ID::EMB1) {
+			m_dec_EMB1_dep(*part) = dep;
+			m_dec_EMB1_eloss(*part) = eloss;
+		}
+		else if (sample==CaloCell_ID::EMB2) {
+			m_dec_EMB2_dep(*part) = dep;
+			m_dec_EMB2_eloss(*part) = eloss;
+		}
+		else if (sample==CaloCell_ID::EMB3) {
+			m_dec_EMB3_dep(*part) = dep;
+			m_dec_EMB3_eloss(*part) = eloss;
+		}
+
+		else if (sample==CaloCell_ID::EME1) {
+			m_dec_EME1_dep(*part) = dep;
+			m_dec_EME1_eloss(*part) = eloss;
+		}
+		else if (sample==CaloCell_ID::EME2) {
+			m_dec_EME2_dep(*part) = dep;
+			m_dec_EME2_eloss(*part) = eloss;
+		}
+		else if (sample==CaloCell_ID::EME3) {
+			m_dec_EME3_dep(*part) = dep;
+			m_dec_EME3_eloss(*part) = eloss;
+		}
+
+
+		else if (sample==CaloCell_ID::TileBar0) {
+			m_dec_TileBar0_dep(*part) = dep;
+			m_dec_TileBar0_eloss(*part) = eloss;
+		}
+		else if (sample==CaloCell_ID::TileBar1) {
+			m_dec_TileBar1_dep(*part) = dep;
+			m_dec_TileBar1_eloss(*part) = eloss;
+		}
+		else if (sample==CaloCell_ID::TileBar2) {
+			m_dec_TileBar2_dep(*part) = dep;
+			m_dec_TileBar2_eloss(*part) = eloss;
+		}
+
+
+		else if (sample==CaloCell_ID::TileExt0) {
+			m_dec_TileExt0_dep(*part) = dep;
+			m_dec_TileExt0_eloss(*part) = eloss;
+		}
+		else if (sample==CaloCell_ID::TileExt1) {
+			m_dec_TileExt1_dep(*part) = dep;
+			m_dec_TileExt1_eloss(*part) = eloss;
+		}
+		else if (sample==CaloCell_ID::TileExt2) {
+			m_dec_TileExt2_dep(*part) = dep;
+			m_dec_TileExt2_eloss(*part) = eloss;
+		}
+
+
+		else if (sample==CaloCell_ID::HEC0) {
+			m_dec_HEC0_dep(*part) = dep;
+			m_dec_HEC0_eloss(*part) = eloss;
+		}
+		else if (sample==CaloCell_ID::HEC1) {
+			m_dec_HEC1_dep(*part) = dep;
+			m_dec_HEC1_eloss(*part) = eloss;
+		}
+		else if (sample==CaloCell_ID::HEC2) {
+			m_dec_HEC2_dep(*part) = dep;
+			m_dec_HEC2_eloss(*part) = eloss;
+		}
+		else if (sample==CaloCell_ID::HEC3) {
+			m_dec_HEC3_dep(*part) = dep;
+			m_dec_HEC3_eloss(*part) = eloss;
+		}
+	}
+#endif
+	return StatusCode::SUCCESS;
+}
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/src/MuonIDCovMatrixDecorator.cxx b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/src/MuonIDCovMatrixDecorator.cxx
new file mode 100644
index 00000000000..17ea939aac6
--- /dev/null
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/src/MuonIDCovMatrixDecorator.cxx
@@ -0,0 +1,73 @@
+/*
+  Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
+*/
+
+/////////////////////////////////////////////////////////////////
+// MuonIDCovMatrixDecorator.cxx, (c) ATLAS Detector software
+///////////////////////////////////////////////////////////////////
+// Author: James Catmore (james.catmore@cern.ch) 
+// Decorates muon objects with the covariance matrix (std::vector<float>) 
+// from the corresponding inner detector track particle
+#include "DerivationFrameworkMuons/MuonIDCovMatrixDecorator.h"
+#include "AthenaKernel/errorcheck.h"
+#include <vector>
+#include <string>
+#include <memory>
+#include "CLHEP/Units/SystemOfUnits.h"
+#include "xAODMuon/MuonContainer.h"
+
+// Constructor
+DerivationFramework::MuonIDCovMatrixDecorator::MuonIDCovMatrixDecorator(const std::string& t,
+							    const std::string& n,
+							    const IInterface* p):
+  AthAlgTool(t, n, p)
+{
+  declareInterface<DerivationFramework::IAugmentationTool>(this);
+  declareProperty("MuonContainerKey", m_muonSGKey="Muons");
+}
+  
+// Destructor
+DerivationFramework::MuonIDCovMatrixDecorator::~MuonIDCovMatrixDecorator() {
+}  
+
+// Athena initialize and finalize
+StatusCode DerivationFramework::MuonIDCovMatrixDecorator::initialize()
+{
+  ATH_MSG_VERBOSE("initialize() ...");
+  return StatusCode::SUCCESS;
+}
+
+StatusCode DerivationFramework::MuonIDCovMatrixDecorator::finalize()
+{
+  ATH_MSG_VERBOSE("finalize() ...");
+  return StatusCode::SUCCESS;
+}
+
+StatusCode DerivationFramework::MuonIDCovMatrixDecorator::addBranches() const
+{
+ 
+  // Retrieve main TrackParticle collection
+  const xAOD::MuonContainer* muons;
+  if (evtStore()->retrieve(muons,m_muonSGKey).isFailure()) {
+    ATH_MSG_ERROR("No Muon collection with name " << m_muonSGKey << " found in StoreGate!");
+    return StatusCode::FAILURE;
+  }
+
+  // Set up the decorator
+  SG::AuxElement::Decorator< std::vector<float>  > decorator("inDet_definingParametersCovarianceMatrix"); 
+
+  // Loop over the muons and apply the decoration
+  std::vector<float> defaultCovarianceMatrix(15,0.0); // in case the ID track doesn't exist
+  for (auto mu : *muons) {
+    auto trackParticle = mu->trackParticle(xAOD::Muon::TrackParticleType::InnerDetectorTrackParticle);
+    if (trackParticle==nullptr) {
+      decorator(*mu) = defaultCovarianceMatrix;            
+    } else {
+     auto covarianceMatrix = trackParticle->definingParametersCovMatrixVec();
+     decorator(*mu) = covarianceMatrix;      
+    }
+  }
+
+  return StatusCode::SUCCESS;
+}
+
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/src/MuonTPExtrapolationTool.cxx b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/src/MuonTPExtrapolationTool.cxx
new file mode 100644
index 00000000000..29177bfb8ca
--- /dev/null
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/src/MuonTPExtrapolationTool.cxx
@@ -0,0 +1,329 @@
+// MuonTPExtrapolationTool.cxx
+#include "DerivationFrameworkMuons/MuonTPExtrapolationTool.h"
+#include "xAODTruth/TruthParticleContainer.h"
+#include "xAODEventInfo/EventInfo.h"
+#ifndef XAOD_ANALYSIS
+  #include "TrkSurfaces/DiscSurface.h"
+  #include "TrkSurfaces/CylinderSurface.h"
+  #include "TrkExInterfaces/IExtrapolator.h"
+#endif
+#include "TVector2.h"
+
+//**********************************************************************
+
+MuonTPExtrapolationTool::MuonTPExtrapolationTool(std::string myname)
+  : 
+  #ifndef XAOD_ANALYSIS
+    AsgTool(myname),
+    m_extrapolator("Trk::Extrapolator/AtlasExtrapolator")
+  #else
+    AsgTool(myname)
+  #endif
+{    
+  declareProperty("EndcapPivotPlaneZ",             m_endcapPivotPlaneZ = 15525.);// z position of pivot plane in endcap region
+  declareProperty("EndcapPivotPlaneMinimumRadius", m_endcapPivotPlaneMinimumRadius = 0.);// minimum radius of pivot plane in endcap region
+  declareProperty("EndcapPivotPlaneMaximumRadius", m_endcapPivotPlaneMaximumRadius = 11977.); // maximum radius of pivot plane in endcap region
+  declareProperty("BarrelPivotPlaneRadius",        m_barrelPivotPlaneRadius = 8000.);// radius of pivot plane in barrel region
+  declareProperty("BarrelPivotPlaneHalfLength",    m_barrelPivotPlaneHalfLength = 9700.);// half length of pivot plane in barrel region
+#ifndef XAOD_ANALYSIS
+  declareProperty("Extrapolator", m_extrapolator);
+#endif
+}
+
+MuonTPExtrapolationTool::~MuonTPExtrapolationTool()
+{
+}
+
+
+//**********************************************************************
+
+
+StatusCode MuonTPExtrapolationTool::initialize()
+{
+#ifndef XAOD_ANALYSIS
+  ATH_CHECK(m_extrapolator.retrieve());
+#endif
+  
+  return StatusCode::SUCCESS;
+}
+
+
+//**********************************************************************
+
+bool MuonTPExtrapolationTool::extrapolateAndDecorateTrackParticle(const xAOD::TrackParticle* particle, float & eta, float & phi){
+
+#ifndef XAOD_ANALYSIS
+  // decorators used to access or store the information 
+  static SG::AuxElement::Decorator< char > Decorated ("DecoratedPivotEtaPhi");
+  static SG::AuxElement::Decorator< std::string > DecoOutcome ("DecorationOutcome");
+  static SG::AuxElement::Decorator< float > Eta ("EtaTriggerPivot");
+  static SG::AuxElement::Decorator< float > Phi ("PhiTriggerPivot");
+#else
+  static SG::AuxElement::Accessor< char > Decorated ("DecoratedPivotEtaPhi");
+  static SG::AuxElement::Accessor< std::string > DecoOutcome ("DecorationOutcome");
+  static SG::AuxElement::Accessor< float > Eta ("EtaTriggerPivot");
+  static SG::AuxElement::Accessor< float > Phi ("PhiTriggerPivot");
+#endif
+
+  if (! Decorated.isAvailable(*particle) || !Decorated(*particle)){
+    // in the athena release, we can run the extrapolation if needed
+    #ifndef XAOD_ANALYSIS
+      const Trk::TrackParameters* pTag = extrapolateToTriggerPivotPlane(*particle);
+      if(!pTag) {
+        // complain only if the particle has sufficient pt to actually make it to the MS... 
+        if (particle->pt() > 3500) ATH_MSG_WARNING("Warning - Pivot plane extrapolation failed for a track particle with IP pt "<<particle->pt()<<", eta "<<particle->eta()<<", phi "<<particle->phi());
+        Decorated(*particle) = false;
+        DecoOutcome(*particle) = "Extrapolation Failed";
+        return false;
+      }
+      Eta(*particle) = pTag->position().eta();
+      Phi(*particle) = pTag->position().phi();
+      DecoOutcome(*particle) = "Extrapolation Success";
+      Decorated(*particle) = true;
+      delete pTag;
+    // in AthAnalysis, we can only give up if the decoration is missing...
+    #else 
+      std::string outcome = "Not Decorated";
+      try {
+        outcome = DecoOutcome(*particle);
+        ATH_MSG_DEBUG("Pivot plane extrapolation failed for a track particle at pt "<<particle->pt()<<", eta "<<particle->eta()<<", phi "<<particle->phi());
+
+      }
+      catch (SG::ExcBadAuxVar &){
+        ATH_MSG_WARNING("Pivot plane extrapolation not decorated to a track particle at pt "<<particle->pt()<<", eta "<<particle->eta()<<", phi "<<particle->phi()<<" - decoration outcome: "<<outcome);
+      }
+      return false;
+    #endif
+    }
+    // if we get here, the decoration was either already present or just added by us
+    // so we can finally read the values
+    eta = Eta(*particle);
+    phi = Phi(*particle);
+    return true;
+}
+
+//**********************************************************************
+
+const xAOD::TrackParticle* MuonTPExtrapolationTool::getPreferredTrackParticle (const xAOD::IParticle* probe){
+  if (dynamic_cast<const xAOD::TruthParticle*>(probe)){
+    ATH_MSG_WARNING("Pivot plane extrapolation not supported for Truth probes!");
+    return 0;
+  }
+  const xAOD::TrackParticle* probeTrack = dynamic_cast<const xAOD::TrackParticle*>(probe);
+  if(!probeTrack && dynamic_cast<const xAOD::Muon*>(probe)) {
+    const xAOD::Muon* probeMuon = dynamic_cast<const xAOD::Muon*>(probe);
+    probeTrack = probeMuon->trackParticle( xAOD::Muon::MuonSpectrometerTrackParticle );
+    if(!probeTrack) {
+      probeTrack = probeMuon->primaryTrackParticle();
+      if(!probeTrack) {
+       probeTrack = probeMuon->trackParticle( xAOD::Muon::InnerDetectorTrackParticle );
+      }
+    }
+  }
+  if(!probeTrack){
+    ATH_MSG_WARNING("no valid track found for extrapolating the probe to the pivot plane!");
+  }
+  return probeTrack;
+
+}
+// **********************************************************************
+StatusCode MuonTPExtrapolationTool::decoratePivotPlaneCoords(const xAOD::IParticle* particle){
+
+  const xAOD::TrackParticle* track = getPreferredTrackParticle(particle);
+  float eta, phi = 0;
+  if (!extrapolateAndDecorateTrackParticle(track, eta, phi)){
+    return StatusCode::FAILURE;
+  }
+  else {
+    return StatusCode::SUCCESS;
+  }
+}
+
+// **********************************************************************
+
+double MuonTPExtrapolationTool::dROnTriggerPivotPlane(const xAOD::Muon& tag, const xAOD::IParticle* probe)
+{
+  // should never happen, but better be safe than sorry
+  if(!probe){
+    ATH_MSG_WARNING("No valid probe provided to MuonTPExtrapolationTool::dROnTriggerPivotPlane! ");
+    return 0;
+  }
+const xAOD::EventInfo* info = 0;
+  ATH_MSG_DEBUG(""<<evtStore());
+  if (evtStore()->retrieve(info, "EventInfo").isFailure()){
+    ATH_MSG_FATAL( "Unable to retrieve Event Info" );
+  }
+  int run = info->runNumber();
+  int evt = info->eventNumber();
+  // static bool isMC = info->eventType(xAOD::EventInfo::IS_SIMULATION);
+
+  // starting values: Track direction @ IP
+  float tag_eta = tag.eta();
+  float tag_phi = tag.phi();
+  float probe_eta = probe->eta();
+  float probe_phi = probe->phi();
+
+  // Try to replace the starting values by the extrapolated pivot plane coordinates
+  // 
+  // First, we need to pick the TrackParticle to extrapolate.
+  const xAOD::TrackParticle* tagTrack = getPreferredTrackParticle(&tag);
+  if(tagTrack){
+    // If we have the track particle, we load the existing decorations for the
+    // pivot plane eta/phi, or (in full athena) to run the extrapolation and decorate. 
+    // If the method returns true, we know that eta/phi were successfully updated
+    // If this does not work, the method returns a false. 
+    // In that case, eta/phi are not changed and we are stuck with the IP direction.
+    // Print a warning just to let the user know.
+    // std::cout << "     ===> Checking the tag muon, with type "<<tag.muonType()<<" and author "<<tag.author() << std::endl;
+    if (!extrapolateAndDecorateTrackParticle(tagTrack,tag_eta,tag_phi)){
+      ATH_MSG_WARNING("Could not get the tag eta/phi @ pivot plane in event "<<evt<<" / run "<<run<<" , using direction at IP!");
+    }
+  }
+
+  // Now we repeat exactly the same exercise as above for the probe
+  
+  // Special flag in case an ID track doesn't reach the MS, causing the extrap to fail.
+  // In this case, we fill an unphysical dummy value of -1 for the delta R, and -10 each eta / phi / dphi / deta. 
+  // In the selection code, we accept these probes, since they can not cause a trigger-related bias
+  bool IDProbeMissesMS = false;
+  
+  const xAOD::TrackParticle* probeTrack = getPreferredTrackParticle(probe);
+  // std::cout << "     ===> Checking the probe"<< std::endl;
+  if(probeTrack){
+    if (!extrapolateAndDecorateTrackParticle(probeTrack,probe_eta,probe_phi)){
+      // if an ID probe does not make it into the MS, we kick it out by returning an unphysical delta R of -100. 
+      if (dynamic_cast<const xAOD::TrackParticle*>(probe)){
+        ATH_MSG_DEBUG("ID probe does not reach MS, returning unphysical dummy value for the exTP branches!");
+        IDProbeMissesMS = true;
+      }
+      else{ 
+        const xAOD::Muon* mu = dynamic_cast<const xAOD::Muon*>(probe);
+        ATH_MSG_DEBUG("Could not get the muon probe eta/phi @ pivot plane, muon type and author are "<<mu->muonType()<<" and "<<mu->author());
+      }
+    }
+  }
+
+  // here we compute the angle in eta and phi
+  float deta = tag_eta - probe_eta;
+  float dphi = TVector2::Phi_mpi_pi(tag_phi-probe_phi);
+  float dr = sqrt( deta*deta + dphi*dphi);
+
+  // decorators for the delta eta and delta phi and dR
+  static SG::AuxElement::Decorator< float > DecDeta ("probe_dEtaTriggerPivot");
+  static SG::AuxElement::Decorator< float > DecDphi ("probe_dPhiTriggerPivot");
+  static SG::AuxElement::Decorator< float > DecDR ("probe_dRTriggerPivot");
+    
+  // here, we copy the eta and phi decorations from the TrackParticles to the 
+  // tag and probe IParticles - to make them easier to access during the 
+  // further processing
+  // In the case of an unsuccessful extrap, this additionally ensures that the 
+  // IP direction for eta/phi is written to the output tree
+  // instead of a garbage value that would result from a missing decoration
+  static SG::AuxElement::Decorator< float > DecEta ("probe_EtaTriggerPivot");
+  static SG::AuxElement::Decorator< float > DecPhi ("probe_PhiTriggerPivot");
+
+  // special unphysical values to signify an ID probe not reaching the pivot plane
+  if (IDProbeMissesMS){
+    deta = -10;
+    dphi = -10;
+    dr = -1;
+    probe_eta = -10;
+    probe_phi = -10;
+  }
+
+  // note that here we only decorate the tag muon with the properties of the TP pair.
+  // This has the background that, for ID probes, the probe may be a non-const TrackParticle
+  // with a locked AuxStore.
+  // If we attempted to overwrite an existing (e.g from DAOD) decoration, we would not be able to
+  // and get an exception. The tag, being a shallow copy of a muon, is fine however and suited for our purpose
+  DecDeta(tag) = deta;  
+  DecDphi(tag) = dphi;
+  DecDR(tag) = dr;
+
+
+  // here, unlike the above, we can get away with simply ignoring the exception if the store is locked
+  // since the eta and the phi in the original decoration continue to be valid. 
+  try { 
+    DecEta(tag) = tag_eta;
+    DecPhi(tag) = tag_phi;
+    DecEta(*probe) = probe_eta;
+    DecPhi(*probe) = probe_phi;
+  }
+  catch (SG::ExcStoreLocked & ){
+   // Maintain a nice, passive agressive silence here.
+  }
+
+  // the final variable we care about is the delta R.
+  return dr;
+}
+//**********************************************************************
+
+#ifndef XAOD_ANALYSIS
+const Trk::TrackParameters* MuonTPExtrapolationTool::extrapolateToTriggerPivotPlane(const xAOD::TrackParticle& track)
+{
+  // BARREL
+  const Trk::Perigee& perigee = track.perigeeParameters();
+  
+  // create the barrel as a cylinder surface centered at 0,0,0
+  Amg::Vector3D barrelCentre(0., 0., 0.);
+  Amg::Transform3D* matrix = new Amg::Transform3D(Amg::RotationMatrix3D::Identity(), barrelCentre);
+  
+  Trk::CylinderSurface* cylinder = 
+    new Trk::CylinderSurface(matrix,
+			     m_barrelPivotPlaneRadius,
+			     m_barrelPivotPlaneHalfLength);
+  if (!cylinder) {
+    ATH_MSG_WARNING("extrapolateToTriggerPivotPlane :: new Trk::CylinderSurface failed.");
+    delete matrix;
+    matrix = 0;
+    return 0;
+  }
+  // and then attempt to extrapolate our track to this surface, checking for the boundaries of the barrel
+  bool boundaryCheck = true;
+  const Trk::Surface* surface = cylinder;
+  const Trk::TrackParameters* p = m_extrapolator->extrapolate(perigee,
+							      *surface,
+							      Trk::alongMomentum,
+							      boundaryCheck,
+							      Trk::muon);
+  delete cylinder;
+  // if the extrapolation worked out (so we are in the barrel) we are done and can return the 
+  // track parameters at this surface. 
+  if (p) return p;
+
+  // if we get here, the muon did not cross the barrel surface
+  // so we assume it is going into the endcap. 
+  // ENDCAP
+
+  // After 2 years of using this code, we realised that ATLAS actually has endcaps on both sides ;-)
+  // So better make sure we place our endcap at the correct side of the detector!  
+  // Hopefully no-one will ever read this comment... 
+  float SignOfEta = track.eta() > 0 ? 1. : -1.;
+
+  Amg::Vector3D endcapCentre(0., 0., m_endcapPivotPlaneZ);
+  // much better!
+  matrix = new Amg::Transform3D(Amg::RotationMatrix3D::Identity(), SignOfEta * endcapCentre);
+  
+  Trk::DiscSurface* disc = 
+    new Trk::DiscSurface(matrix,
+			 m_endcapPivotPlaneMinimumRadius,
+			 m_endcapPivotPlaneMaximumRadius);
+  if (!disc) {
+    ATH_MSG_WARNING("extrapolateToTriggerPivotPlane :: new Trk::DiscSurface failed."); 
+    delete matrix; 
+    matrix = 0; 
+    return 0;
+  }
+  
+  // for the endcap, we turn off the boundary check, extending the EC infinitely to catch stuff heading for the transition region
+  boundaryCheck = false;
+  surface = disc;
+  p = m_extrapolator->extrapolate(perigee,
+				  *surface,
+				  Trk::alongMomentum,
+				  boundaryCheck,
+				  Trk::muon);
+  delete disc; 
+  return p;
+}
+#endif
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/src/MuonTPJpsiVertexFittingAlg.cxx b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/src/MuonTPJpsiVertexFittingAlg.cxx
new file mode 100644
index 00000000000..7b598be6ee7
--- /dev/null
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/src/MuonTPJpsiVertexFittingAlg.cxx
@@ -0,0 +1,61 @@
+#include "MuonTPJpsiVertexFittingAlg.h"
+#include "GaudiKernel/Property.h"
+#include "GaudiKernel/ITHistSvc.h"
+#include "xAODEventInfo/EventInfo.h"
+
+# if !defined(XAOD_ANALYSIS)    
+#include "DerivationFrameworkInterfaces/IAugmentationTool.h"
+#endif
+
+using std::string;
+
+//**********************************************************************
+
+MuonTPJpsiVertexFittingAlg::MuonTPJpsiVertexFittingAlg(const std::string& name, ISvcLocator* pSvcLocator) :
+            AthAlgorithm(name, pSvcLocator) {
+# if !defined(XAOD_ANALYSIS)
+    declareProperty("AugmentationTools", m_augmentation_tools);
+#endif
+}
+
+//**********************************************************************
+
+MuonTPJpsiVertexFittingAlg::~MuonTPJpsiVertexFittingAlg() {
+}
+
+//**********************************************************************
+
+StatusCode MuonTPJpsiVertexFittingAlg::initialize() {
+
+    ATH_MSG_DEBUG("in initialize - retrieving tools");
+
+# if !defined(XAOD_ANALYSIS)    
+    ATH_CHECK(m_augmentation_tools.retrieve());
+#endif
+
+    return StatusCode::SUCCESS;
+}
+
+//**********************************************************************
+
+StatusCode MuonTPJpsiVertexFittingAlg::finalize() {
+
+    return StatusCode::SUCCESS;
+}
+
+//**********************************************************************
+
+StatusCode MuonTPJpsiVertexFittingAlg::execute() {
+
+    ATH_MSG_DEBUG("in execute");
+
+# if !defined(XAOD_ANALYSIS)    
+    for (auto tool : m_augmentation_tools) {
+        ATH_MSG_DEBUG("now calling addBranches for " << tool->name());
+        ATH_CHECK(tool->addBranches());
+    }
+#endif
+    return StatusCode::SUCCESS;
+}
+
+//**********************************************************************
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/src/MuonTPJpsiVertexFittingAlg.h b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/src/MuonTPJpsiVertexFittingAlg.h
new file mode 100644
index 00000000000..4cc7518fb56
--- /dev/null
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/src/MuonTPJpsiVertexFittingAlg.h
@@ -0,0 +1,47 @@
+// MuonTPAlg.h 
+
+#ifndef MuonTPJpsiVertexFittingAlg__H
+#define MuonTPJpsiVertexFittingAlg__H
+
+#include "AthenaBaseComps/AthAlgorithm.h"
+#include "GaudiKernel/ToolHandle.h"
+
+namespace DerivationFramework{
+    class IAugmentationTool;
+}
+
+// algorithm that calls the jpsi finder and applies BPhys decorations to the vertices
+// essentially takes the role of the derivation kernel when running in AOD analysis mode 
+// in AthAnalysisBase, this alg has no function 
+class ITHistSvc;
+class IMuonTPTool;
+
+class MuonTPJpsiVertexFittingAlg : public AthAlgorithm { 
+
+public:
+  MuonTPJpsiVertexFittingAlg(const std::string& name, ISvcLocator* pSvcLocator);
+
+  /// Destructor: 
+  ~MuonTPJpsiVertexFittingAlg(); 
+
+  /// Athena algorithm's Hooks
+  StatusCode  initialize();
+  StatusCode  execute();
+  StatusCode  finalize();
+
+private: 
+
+  /// Default constructor: 
+  MuonTPJpsiVertexFittingAlg();
+
+protected:
+
+# if !defined(XAOD_ANALYSIS)    
+    // the augmentation tools which we want to run
+    ToolHandleArray <DerivationFramework::IAugmentationTool> m_augmentation_tools;
+#endif
+
+};
+
+
+#endif //MuonTPJpsiVertexFittingAlg__H
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/src/components/DerivationFrameworkMuons_entries.cxx b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/src/components/DerivationFrameworkMuons_entries.cxx
index 447800ad68e..8bc3ed98372 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/src/components/DerivationFrameworkMuons_entries.cxx
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/src/components/DerivationFrameworkMuons_entries.cxx
@@ -1,9 +1,25 @@
+#include "GaudiKernel/DeclareFactoryEntries.h"
 #include "DerivationFrameworkMuons/dimuonTaggingTool.h"
 #include "DerivationFrameworkMuons/isolationDecorator.h"
 #include "DerivationFrameworkMuons/mcpDecorator.h"
+#include "DerivationFrameworkMuons/MuonTPExtrapolationTool.h"
+#include "DerivationFrameworkMuons/IDTrackCaloDepositsDecoratorTool.h"
+#include "DerivationFrameworkMuons/MuonIDCovMatrixDecorator.h"
 using namespace DerivationFramework;
 
-DECLARE_COMPONENT( dimuonTaggingTool )
-DECLARE_COMPONENT( isolationDecorator )
-DECLARE_COMPONENT( mcpDecorator )
+DECLARE_TOOL_FACTORY( dimuonTaggingTool )
+DECLARE_TOOL_FACTORY( isolationDecorator )
+DECLARE_TOOL_FACTORY( mcpDecorator )
+DECLARE_TOOL_FACTORY (MuonTPExtrapolationTool)
+DECLARE_TOOL_FACTORY (IDTrackCaloDepositsDecoratorTool)
+DECLARE_TOOL_FACTORY (MuonIDCovMatrixDecorator)
+
+DECLARE_FACTORY_ENTRIES( DerivationFrameworkMuons ) {
+   DECLARE_TOOL( dimuonTaggingTool )
+   DECLARE_TOOL( isolationDecorator )
+   DECLARE_TOOL( mcpDecorator )
+   DECLARE_TOOL(MuonTPExtrapolationTool)
+   DECLARE_TOOL(IDTrackCaloDepositsDecoratorTool)
+   DECLARE_TOOL(MuonIDCovMatrixDecorator)
+}
 
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/src/components/DerivationFrameworkMuons_load.cxx b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/src/components/DerivationFrameworkMuons_load.cxx
new file mode 100644
index 00000000000..53b825b3359
--- /dev/null
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/src/components/DerivationFrameworkMuons_load.cxx
@@ -0,0 +1,3 @@
+#include "GaudiKernel/LoadFactoryEntries.h"
+
+LOAD_FACTORY_ENTRIES( DerivationFrameworkMuons )
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/src/dimuonTaggingTool.cxx b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/src/dimuonTaggingTool.cxx
index 5df4df341c8..f801b3a1dd4 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/src/dimuonTaggingTool.cxx
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/src/dimuonTaggingTool.cxx
@@ -18,8 +18,8 @@
 #include "xAODTracking/TrackingPrimitives.h"
 #include "xAODTracking/TrackParticleContainer.h"
 #include "xAODTruth/TruthParticleContainer.h"
-#include "MuonTPTools/IMuonTPExtrapolationTool.h"
-#include "MuonTPTools/IIDTrackCaloDepositsDecoratorTool.h"
+#include "DerivationFrameworkMuons/IMuonTPExtrapolationTool.h"
+#include "DerivationFrameworkMuons/IIDTrackCaloDepositsDecoratorTool.h"
 
 // Constructor
 DerivationFramework::dimuonTaggingTool::dimuonTaggingTool(const std::string& t,
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/src/isolationDecorator.cxx b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/src/isolationDecorator.cxx
index 468c4ad0b05..ea457e4e339 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/src/isolationDecorator.cxx
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/src/isolationDecorator.cxx
@@ -72,14 +72,14 @@ StatusCode DerivationFramework::isolationDecorator::initialize()
   m_ptconeTypes.clear();
   for(auto c: m_ptcones){
     xAOD::Iso::IsolationType t = static_cast<xAOD::Iso::IsolationType>(c);
-    m_decorators[c] = new SG::AuxElement::Decorator< float >(m_prefix+xAOD::Iso::toCString(t));
-    m_decorators[c+NDIFF] = new SG::AuxElement::Decorator< float >(m_prefix+xAOD::Iso::toCString(static_cast<xAOD::Iso::IsolationType>(c+NDIFF)));
+    m_decorators[c] = new SG::AuxElement::Decorator< float >(m_prefix+xAOD::Iso::toString(t));
+    m_decorators[c+NDIFF] = new SG::AuxElement::Decorator< float >(m_prefix+xAOD::Iso::toString(static_cast<xAOD::Iso::IsolationType>(c+NDIFF)));
     m_ptconeTypes.push_back(t);
   }
   m_topoetconeTypes.clear();
   for(auto c: m_topoetcones) {
     xAOD::Iso::IsolationType t = static_cast<xAOD::Iso::IsolationType>(c);
-    m_decorators[c] = new SG::AuxElement::Decorator< float >(m_prefix+xAOD::Iso::toCString(t));
+    m_decorators[c] = new SG::AuxElement::Decorator< float >(m_prefix+xAOD::Iso::toString(t));
     m_topoetconeTypes.push_back(t);
   }
 
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/src/mcpDecorator.cxx b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/src/mcpDecorator.cxx
index 2bada954053..9a19121c16d 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/src/mcpDecorator.cxx
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/src/mcpDecorator.cxx
@@ -2,14 +2,10 @@
   Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
 */
 
-// DerivationFrameworkMuons includes
 #include "DerivationFrameworkMuons/mcpDecorator.h"
 #include "ExpressionEvaluation/ExpressionParser.h"
 #include "ExpressionEvaluation/MultipleProxyLoader.h"
 #include "ExpressionEvaluation/SGxAODProxyLoader.h"
-// #include "TrkExInterfaces/IExtrapolator.h"
-// #include "MuonRecToolInterfaces/IMuonTrackExtrapolationTool.h"
-// #include "xAODTracking/TrackParticleContainer.h"
 #include "xAODMuon/MuonContainer.h"
 
 #include "AthenaKernel/errorcheck.h"
@@ -17,19 +13,12 @@
 namespace DerivationFramework {
   mcpDecorator::mcpDecorator(const std::string& t, const std::string& n, const IInterface* p):
     AthAlgTool(t, n, p),
-//     m_trackExtrapoTool("Muon::MuonTrackExtrapolationTool/MuonTrackExtrapolationTool"),
-//     m_extrapolator("Trk::Extrapolator/AtlasExtrapolator"),
-//     m_trackingGeometrySvc("TrackingGeometrySvc/AtlasTrackingGeometrySvc",p),
     m_parser(nullptr)
   {
     declareInterface<DerivationFramework::IAugmentationTool>(this);
-//      declareProperty("Extrapolator", m_extrapolator);
-//     declareProperty("TrackExtrapoTool",   m_trackExtrapoTool);
     declareProperty("TargetContainer",    m_containerName = "InDetTrackParticles");
     declareProperty("SelectionString",    m_selectionString = "");
     declareProperty("Prefix",             m_prefix="MuonEntry_");
-//     declareProperty("MuonSystemEntranceName", m_msEntranceName = "MuonSpectrometerEntrance" );
-//     declareProperty("TrackingGeometrySvc", m_trackingGeometrySvc);
   }
 
   mcpDecorator::~mcpDecorator() {}
@@ -37,14 +26,6 @@ namespace DerivationFramework {
   StatusCode mcpDecorator::initialize() {
     ATH_MSG_INFO ("Initializing " << name() << "...");
 
-    // load the matching tool
-//     if( ! m_trackExtrapoTool.empty() ) {
-//        CHECK( m_trackExtrapoTool.retrieve() );
-//        ATH_MSG_INFO( "Successfully retrived the MuonTrackExtrapolationTool!" );
-//     }
-
-//     ATH_CHECK(m_extrapolator.retrieve());
-
     // Set up the text-parsing machinery for thinning the tracks directly according to user cuts
     if (m_selectionString!="") {
             ExpressionParsing::MultipleProxyLoader *proxyLoaders = new ExpressionParsing::MultipleProxyLoader(); // not deleted
@@ -87,118 +68,6 @@ namespace DerivationFramework {
             return StatusCode::FAILURE;
         }
     }
-
-//     const Trk::TrackingVolume* msEntrance = m_trackingGeometrySvc->trackingGeometry()->trackingVolume(m_msEntranceName.c_str());
-//     if( !msEntrance ) {
-//       ATH_MSG_WARNING("  MS entrance not found" );
-//       return 0;
-//     }
-
-    /// Loop over tracks
-    //int ipar=0;
-    //for(auto particle : *toDecorate) {
-    //  /// Only decorate those passed selection
-    //  if (!entries[ipar++]) continue;
-
-//     Trk::PropDirection dir = Trk::oppositeMomentum;
-//     if( msEntrance->inside( pars.position() ) ){
-//       dir = Trk::alongMomentum;
-//     }
-//     const Trk::TrackParameters* p m_extrapolator->extrapolateToVolume(pars,*msEntrance,dir,particleHypo);
-// 
-//       bool boundaryCheck = true;
-//       const Trk::Perigee& perigee = track.perigeeParameters();
-//       const Trk::TrackParameters* p = m_extrapolator->extrapolate(perigee,
-//                                                             *surface,
-//                                                             Trk::alongMomentum,
-//                                                             boundaryCheck,
-//                                                             Trk::muon);
-// 
-//      //// use the extrapolator tool
-//      //// get the muon entry layer
-//      //// save eta and phi
-// 
-// 
-//       auto trk = particle->primaryTrackParticle();
-      // 0047     typedef Eigen::Matrix<double, 3, 1>                 Vector3D;
-      // 0027     TrackParameters (const Amg::Vector3D&   position,   // point on track,
-      // 0028              const Amg::Vector3D&   direction,  // direction cosines at point,
-      // 0029              double         qOverP);    // signed inverse momentum at point
-      //
-      // #define    AmgVector(rows)   Eigen::Matrix<double, rows, 1, 0, rows, 1>
-      // typedef    xAOD::AmgVector (6) CurvilinearParameters_t
-//       auto pars = trk->trackParameters(0); //xAOD::AmgVector ----> (6,1)
-//       const unsigned int index1=0;
-//       Amg::Vector3D position;
-//       position(0,0) = trk->parameterX(index1);
-//       position(1,0) = trk->parameterY(index1);
-//       position(2,0) = trk->parameterZ(index1);
-//       Amg::Vector3D direction;
-//       direction(0,0) = trk->parameterPX(index1);
-//       direction(1,0) = trk->parameterPY(index1);
-//       direction(2,0) = trk->parameterPZ(index1);
-
-//       Amg::Vector3D position; position << trk->parameterX(index1) << trk->parameterY(index1) << trk->parameterZ(index1);
-//       Amg::Vector3D direction; direction << trk->parameterPX(index1) << trk->parameterPY(index1) << trk->parameterPZ(index1);
-//       const Trk::TrackParameters pars0(position, direction, Trk::Charged(const double& charge = 1.):);
-
-     
-//       auto track = trk->track();
-//       const Trk::TrackParameters* Pars = track->perigeeParameters();
-//       auto pars = m_trackExtrapoTool->extrapolateToMuonEntryRecord(Pars, track->info().particleHypothesis());
-//       auto pars = m_trackExtrapoTool->extrapolateToMuonEntryRecord(m_trackExtrapoTool->findClosestParametersToMuonEntry(*track), track->info().particleHypothesis());
-
-      /// add decoration
-//       static SG::AuxElement::Decorator< float > X  (m_prefix+"X");
-//       static SG::AuxElement::Decorator< float > Y  (m_prefix+"Y");
-//       static SG::AuxElement::Decorator< float > Z  (m_prefix+"Z");
-//       static SG::AuxElement::Decorator< float > cosPhi (m_prefix+"cosPhi");
-//       static SG::AuxElement::Decorator< float > sinPhi (m_prefix+"sinPhi");
-//       static SG::AuxElement::Decorator< float > cotTheta (m_prefix+"cotTheta");
-// 
-//       X(*particle) = pars.position()(0,0);
-//       Y(*particle) = pars.position()(1,0);
-//       Z(*particle) = pars.position()(2,0);
-//       cosPhi(*particle) = pars.transverseDirection()(0,0);
-//       sinPhi(*particle) = pars.transverseDirection()(1,0);
-//       cotTheta(*particle) = pars.transverseDirection()(2,0);
-
-//     const Trk::TrackParameters* pars = m_trackExtrapoTool->extrapolateToMuonEntryRecord(const Trk::TrackParameters& pars, Trk::ParticleHypothesis particleHypo);
-//     auto trk = particle->primaryTrackParticle();
-//       auto pars = m_trackExtrapoTool->extrapolateToMuonEntryRecord(trk->curvilinearParameters(0), trk->particleHypothesis());
-//       auto pars = m_trackExtrapoTool->extrapolateToMuonEntryRecord(trk->track()->, trk->particleHypothesis());
-//     const Trk::TrackParameters* pars = m_trackExtrapoTool->extrapolateToMuonEntryRecord(trk->curvilinearParameters(0), trk->particleHypothesis());
-    /// start decoration
-    //}
     return StatusCode::SUCCESS;
   }
-
-//   bool decorate(const Trk::Track& track)
-//   {
-//    auto tp = particle->primaryTrackParticle();
-//    if(!tp) return false;
-//    auto trk = tp->track();
-//    if(!track) return false;
-// 
-//    // if straightline track and the field is on return 0
-//    bool isSL = m_helper->isSLTrack(*track);
-//    if( m_magFieldSvc->toroidOn() && isSL ) {
-//      return 0;
-//    }
-// 
-//    const Trk::Perigee* pp = track->perigeeParameters();
-//    if( !pp ) return 0;
-// 
-//    const Trk::TrackParameters* firstPars = m_trackExtrapoTool->findClosestParametersToMuonEntry(*track);
-//    if( !firstPars ){
-//      ATH_MSG_WARNING("failed to find closest parameters to muon entry ");
-//      return 0;
-//    }
-//    
-//    // extrapolate to muon entry record
-//    Trk::ParticleHypothesis particleHypo = track.info().particleHypothesis();
-//    if( isSL ) particleHypo = Trk::nonInteracting;
-//    const Trk::TrackParameters* exPars = extrapolateToMuonEntryRecord(*firstPars,particleHypo);
-//   }
-
 }
-- 
GitLab