From ecbdcef78db6987a0714b38f900d126b2e2f06cb Mon Sep 17 00:00:00 2001
From: Dongliang Zhang <Dongliang.Zhang@cern.ch>
Date: Wed, 17 Aug 2016 15:11:00 +0200
Subject: [PATCH] Add missing HLT container (DerivationFrameworkMuons-00-12-01)

	* Add missing HLT container
	* Tagging as DerivationFrameworkMuons-00-12-01

2016-08-12 Dongliang Zhang <dongliang.zhang@cern.ch>
	* Coverity 109086
	* Update the MUON1/2 to keep EventShape info (ATLASG-530)
	* Tagging as DerivationFrameworkMuons-00-12-00

2016-05-26 Dongliang Zhang <dongliang.zhang@cern.ch>
	* Using MUON_ prefix for both MUON1 and MUON2 track iso decoration
	* Add decoratePromptLepton in MUON1 and MUON2
	* Tagged as DerivationFrameworkMuons-00-11-00

2016-05-18 Dongliang Zhang <dongliang.zhang@cern.ch>
	* Update smart-slimming list
	* And minor change of the script used to update the list
	* Tagging as DerivationFrameworkMuons-00-10-01

2016-05-12 Dongliang Zhang <dongliang.zhang@cern.ch>
	* Add IDTrackCaloDeposits decoration and trigger position for MUON0/1/2/3
...
(Long ChangeLog diff - truncated)


Former-commit-id: b3febe6395a69338ea08304294b0bff5e08a6505
---
 .../DerivationFrameworkMuons/CMakeLists.txt   |   2 +
 .../dimuonTaggingTool.h                       |   5 +
 .../DerivationFrameworkMuons/mcpDecorator.h   |  54 +++++
 .../DerivationFrameworkMuons/cmt/requirements |   4 +
 .../python/MuonsCPContent.py                  |  31 +--
 .../python/MuonsCommon.py                     | 140 ++----------
 .../python/StreamConfig.py                    |  18 +-
 .../python/TrackIsolationDecorator.py         |   4 +-
 .../scripts/grid_submit.sh                    |  12 ++
 .../scripts/trival_test.sh                    |  31 +++
 .../scripts/update_CPContent.py               |  50 +++++
 .../DerivationFrameworkMuons/share/MUON0.py   |  14 +-
 .../DerivationFrameworkMuons/share/MUON1.py   |  16 ++
 .../DerivationFrameworkMuons/share/MUON2.py   |  14 ++
 .../DerivationFrameworkMuons/share/MUON3.py   |   2 +
 .../DerivationFrameworkMuons_entries.cxx      |   7 +-
 .../src/dimuonTaggingTool.cxx                 |  17 ++
 .../src/isolationDecorator.cxx                |   5 +
 .../src/mcpDecorator.cxx                      | 204 ++++++++++++++++++
 19 files changed, 489 insertions(+), 141 deletions(-)
 create mode 100644 PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/DerivationFrameworkMuons/mcpDecorator.h
 create mode 100755 PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/scripts/grid_submit.sh
 create mode 100755 PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/scripts/trival_test.sh
 create mode 100755 PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/scripts/update_CPContent.py
 create mode 100644 PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/src/mcpDecorator.cxx

diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/CMakeLists.txt b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/CMakeLists.txt
index a14120f5868..a775a37543d 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/CMakeLists.txt
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/CMakeLists.txt
@@ -19,7 +19,9 @@ atlas_depends_on_subdirs( PUBLIC
                           Trigger/TrigAnalysis/TrigDecisionTool
                           Trigger/TrigAnalysis/TrigMuonMatching
                           PRIVATE
+			  PhysicsAnalysis/MuonID/MuonPerformanceAnalysis/MuonTPTools
                           Control/AthenaKernel
+			  Control/AthenaBaseComps
                           Event/xAOD/xAODEventInfo
                           Event/xAOD/xAODTracking
                           Event/xAOD/xAODTruth )
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/DerivationFrameworkMuons/dimuonTaggingTool.h b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/DerivationFrameworkMuons/dimuonTaggingTool.h
index 1cc6602b30e..07b090a033b 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/DerivationFrameworkMuons/dimuonTaggingTool.h
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/DerivationFrameworkMuons/dimuonTaggingTool.h
@@ -22,6 +22,9 @@
 // xAOD header files
 #include "xAODMuon/MuonContainer.h"
 
+class IMuonTPExtrapolationTool;
+class IIDTrackCaloDepositsDecoratorTool;
+
 namespace DerivationFramework {
   /** @class dimuonTaggingTool
       @author Dongliang.Zhang@cern.ch
@@ -50,6 +53,8 @@ namespace DerivationFramework {
     StatusCode fillInfo(int* keep, std::vector<int>& trackMask) const;
     void maskNearbyIDtracks(const xAOD::IParticle *mu, std::vector< int >& trackMask, const xAOD::TrackParticleContainer* tracks) const;
 
+    ToolHandle< IMuonTPExtrapolationTool > m_tpExpTool;
+    ToolHandle< IIDTrackCaloDepositsDecoratorTool > m_caloDepoTool;
     ToolHandle< Trig::ITrigMuonMatching > m_matchTool;
     float m_triggerMatchDeltaR;
     ToolHandle< Trig::TrigDecisionTool > m_trigDecisionTool;
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/DerivationFrameworkMuons/mcpDecorator.h b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/DerivationFrameworkMuons/mcpDecorator.h
new file mode 100644
index 00000000000..f4a1228a824
--- /dev/null
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/DerivationFrameworkMuons/mcpDecorator.h
@@ -0,0 +1,54 @@
+/*
+  Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
+*/
+
+#ifndef DERIVATIONFRAMEWORKMUONS_MCPDECORATOR_H
+#define DERIVATIONFRAMEWORKMUONS_MCPDECORATOR_H 1
+
+#include "AthenaBaseComps/AthAlgTool.h"
+#include "GaudiKernel/ToolHandle.h" //included under assumption you'll want to use some tools! Remove if you don't!
+#include "DerivationFrameworkInterfaces/IAugmentationTool.h"
+#include <string>
+
+// namespace Muon{
+// class IMuonTrackExtrapolationTool;
+// }
+
+namespace ExpressionParsing{
+class ExpressionParser;
+}
+
+// namespace Trk{
+//   class IExtrapolator;
+// }
+
+namespace DerivationFramework {
+  /** @class isolationDecorator
+      @author Dongliang.Zhang@cern.ch
+     */
+
+  class mcpDecorator: public ::AthAlgTool, public IAugmentationTool {
+   public: 
+    /** Constructor with parameters */
+    mcpDecorator( const std::string& t, const std::string& n, const IInterface* p);
+
+    /** Destructor */
+    virtual ~mcpDecorator(); 
+
+    // Athena algtool's Hooks
+    virtual StatusCode  initialize();
+    virtual StatusCode  finalize();
+    virtual StatusCode addBranches() const;
+
+   private: 
+    std::string m_containerName;
+    std::string m_selectionString;
+    std::string m_prefix;
+//     ToolHandle< Muon::IMuonTrackExtrapolationTool > m_trackExtrapoTool;
+//     ToolHandle< Trk::IExtrapolator > m_extrapolator;
+
+    ExpressionParsing::ExpressionParser* m_parser;
+  }; 
+}
+
+#endif //> !DERIVATIONFRAMEWORKMUONS_MCPDECORATOR_H
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/cmt/requirements b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/cmt/requirements
index 3a5a4495a17..0e5f0b297a9 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/cmt/requirements
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/cmt/requirements
@@ -19,9 +19,13 @@ use  xAODMuon                   xAODMuon-*                      Event/xAOD
 private
 use  AthenaKernel               AthenaKernel-*                  Control
 use  AtlasCLHEP                 AtlasCLHEP-*                    External
+#use  MuonRecToolInterfaces      MuonRecToolInterfaces-*         MuonSpectrometer/MuonReconstruction/MuonRecTools
 use  xAODEventInfo              xAODEventInfo-*                 Event/xAOD
 use  xAODTracking               xAODTracking-*                  Event/xAOD
 use  xAODTruth                  xAODTruth-*                     Event/xAOD
+use  MuonTPTools                MuonTPTools-*                   PhysicsAnalysis/MuonID/MuonPerformanceAnalysis
+#use  TrkExInterfaces            TrkExInterfaces-*               Tracking/TrkExtrapolation/TrkExInterfaces
+use AthenaBaseComps             AthenaBaseComps-*               Control
 end_private
 ################################################################
 #
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/python/MuonsCPContent.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/python/MuonsCPContent.py
index 7fa175d72d8..1215897d23f 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/python/MuonsCPContent.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/python/MuonsCPContent.py
@@ -2,19 +2,26 @@
 
 MuonsCPContent = [
 "CombinedMuonTrackParticles",
-"CombinedMuonTrackParticlesAux.phi.theta.qOverP.numberOfPixelHits.numberOfPixelHoles.numberOfPixelDeadSensors.numberOfSCTHits.numberOfSCTHoles.numberOfSCTDeadSensors.numberOfTRTHits.numberOfTRTOutliers.numberOfPrecisionLayers.numberOfPrecisionHoleLayers",
-"ElectronCollection",
-"ElectronCollectionAux.trackParticleLinks.pt.eta.phi.m.f1.topoetcone40",
+"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",
 "ExtrapolatedMuonTrackParticles",
-"ExtrapolatedMuonTrackParticlesAux.phi.theta.qOverP",
 "GSFTrackParticles",
-"GSFTrackParticlesAux.phi.theta",
 "InDetTrackParticles",
-"InDetTrackParticlesAux.phi.theta.qOverP",
 "Muons",
-"MuonsAux.pt.eta.phi.author.muonType.inDetTrackParticleLink.muonSpectrometerTrackParticleLink.combinedTrackParticleLink.momentumBalanceSignificance",
-"PhotonCollection",
-"PhotonCollectionAux.pt.eta.phi.m.caloClusterLinks.author.f1.topoetcone40.Tight",
-"egClusterCollection",
-"egClusterCollectionAux.calEta.calPhi"
-]
+"Photons",
+"egammaClusters",
+"Electrons",
+"ElectronsAux.trackParticleLinks.pt.eta.phi.m.f1.topoetcone40.truthParticleLink.caloClusterLinks",
+"ExtrapolatedMuonTrackParticlesAux.phi.theta.qOverP.numberOfPixelHits.numberOfPixelDeadSensors.numberOfPrecisionLayers.d0.z0.vz.definingParametersCovMatrix.vertexLink.truthParticleLink.chiSquared.numberDoF.numberOfPhiLayers.numberOfPhiHoleLayers.numberOfPixelHoles.numberOfPrecisionHoleLayers.numberOfSCTDeadSensors.numberOfSCTHits.numberOfSCTHoles.numberOfTRTHits.numberOfTRTOutliers",
+"GSFTrackParticlesAux.phi.theta.d0.z0.vz.definingParametersCovMatrix.vertexLink.truthParticleLink.originalTrackParticle.qOverP",
+"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",
+"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
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/python/MuonsCommon.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/python/MuonsCommon.py
index 0e187bb4bd6..706428cfe81 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/python/MuonsCommon.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/python/MuonsCommon.py
@@ -20,8 +20,10 @@ DFCommonMuonToolWrapperTools = []
 
 ### IDHits
 DFCommonMuonsSelector = CP__MuonSelectionTool(name = "DFCommonMuonsSelector")
-DFCommonMuonsSelector.MaxEta = 2.7
+DFCommonMuonsSelector.MaxEta = 3.
 DFCommonMuonsSelector.MuQuality = 3
+# turn of the momentum correction which is not needed for IDHits cut and Preselection
+DFCommonMuonsSelector.TurnOffMomCorr = True
 ToolSvc += DFCommonMuonsSelector
 print DFCommonMuonsSelector
 
@@ -34,126 +36,28 @@ ToolSvc += DFCommonMuonToolWrapper
 print DFCommonMuonToolWrapper
 DFCommonMuonToolWrapperTools.append(DFCommonMuonToolWrapper)
 
-### Loose
-DFCommonMuonsSelectorLoose = CP__MuonSelectionTool(name = "DFCommonMuonsSelectorLoose")
-DFCommonMuonsSelectorLoose.MaxEta = 2.7
-DFCommonMuonsSelectorLoose.MuQuality = 2
-ToolSvc += DFCommonMuonsSelectorLoose
-print DFCommonMuonsSelectorLoose
-
-DFCommonMuonToolWrapperLoose = DerivationFramework__AsgSelectionToolWrapper( name = "DFCommonMuonToolWrapperLoose",
-                                                                        AsgSelectionTool = DFCommonMuonsSelectorLoose,
-                                                                        CutType = "Quality",
-                                                                        StoreGateEntryName = "DFCommonMuonsLoose",
-                                                                        ContainerName = "Muons")
-ToolSvc += DFCommonMuonToolWrapperLoose
-print DFCommonMuonToolWrapperLoose
-DFCommonMuonToolWrapperTools.append(DFCommonMuonToolWrapperLoose)
-
-### Medium
-DFCommonMuonsSelectorMedium = CP__MuonSelectionTool(name = "DFCommonMuonsSelectorMedium")
-DFCommonMuonsSelectorMedium.MaxEta = 2.7
-DFCommonMuonsSelectorMedium.MuQuality = 1
-ToolSvc += DFCommonMuonsSelectorMedium
-print DFCommonMuonsSelectorMedium
-
-DFCommonMuonToolWrapperMedium = DerivationFramework__AsgSelectionToolWrapper( name = "DFCommonMuonToolWrapperMedium",
-                                                                        AsgSelectionTool = DFCommonMuonsSelectorMedium,
-                                                                        CutType = "Quality",
-                                                                        StoreGateEntryName = "DFCommonMuonsMedium",
+### Preselection
+DFCommonMuonsSelectorPreselection = CP__MuonSelectionTool(name = "DFCommonMuonsSelectorPreselection")
+DFCommonMuonsSelectorPreselection.MaxEta = 3.
+DFCommonMuonsSelectorPreselection.MuQuality = 3
+# turn of the momentum correction which is not needed for IDHits cut and Preselection
+DFCommonMuonsSelectorPreselection.TurnOffMomCorr = True
+ToolSvc += DFCommonMuonsSelectorPreselection
+print DFCommonMuonsSelectorPreselection
+
+DFCommonMuonToolWrapperPreselection = DerivationFramework__AsgSelectionToolWrapper( name = "DFCommonMuonToolWrapperPreselection",
+                                                                        AsgSelectionTool = DFCommonMuonsSelectorPreselection,
+                                                                        CutType = "Preselection",
+                                                                        StoreGateEntryName = "DFCommonMuonsPreselection",
                                                                         ContainerName = "Muons")
-ToolSvc += DFCommonMuonToolWrapperMedium
-print DFCommonMuonToolWrapperMedium
-DFCommonMuonToolWrapperTools.append(DFCommonMuonToolWrapperMedium)
-
-### Tight
-DFCommonMuonsSelectorTight = CP__MuonSelectionTool(name = "DFCommonMuonsSelectorTight")
-DFCommonMuonsSelectorTight.MaxEta = 2.7
-DFCommonMuonsSelectorTight.MuQuality = 0
-ToolSvc += DFCommonMuonsSelectorTight
-print DFCommonMuonsSelectorTight
-
-DFCommonMuonToolWrapperTight = DerivationFramework__AsgSelectionToolWrapper( name = "DFCommonMuonToolWrapperTight",
-                                                                        AsgSelectionTool = DFCommonMuonsSelectorTight,
-                                                                        CutType = "Quality",
-                                                                        StoreGateEntryName = "DFCommonMuonsTight",
-                                                                        ContainerName = "Muons")
-ToolSvc += DFCommonMuonToolWrapperTight
-print DFCommonMuonToolWrapperTight
-DFCommonMuonToolWrapperTools.append(DFCommonMuonToolWrapperTight)
-
-##====================================================================
-## FOR MUON ISOLATION
-##====================================================================
-##WARNING: duplicate with the EventDensityTool in EGammaCommon.py
-##This should be handled in a better way
-#run_EDEgamma = False
-#if not hasattr (ToolSvc, 'EDEgammaCentralTool'):
-#    from EventShapeTools.EventDensityConfig import configEventDensityTool, EventDensityAlg
-#    from JetRec.JetRecStandard import jtm
-#    tc=configEventDensityTool("EDEgammaCentralTool", jtm.emget,
-#                              radius          = 0.5,
-#                              AbsRapidityMin  = 0.0,
-#                              AbsRapidityMax  = 1.5,
-#                              OutputContainer = "DensityForEgammaCentral",
-#                              OutputLevel     = 3
-#                              )
-#    ToolSvc += tc
-#    tf=configEventDensityTool("EDEgammaForwardTool", jtm.emget,
-#                              radius          = 0.5,
-#                              AbsRapidityMin  = 1.5,
-#                              AbsRapidityMax  = 3.0,
-#                              OutputContainer = "DensityForEgammaForward",
-#                              OutputLevel     = 3
-#                              )
-#    ToolSvc += tf
-#    run_EDEgamma = True
-#
-##if not hasattr (ToolSvc, 'DFIsoTrackSelectorTool'):
-##bug with this: "NameError: name 'tit' is not defined" ==> NOT USED FOR NOW
-##Track selection
-#from InDetTrackSelectorTool.InDetTrackSelectorToolConf import InDet__InDetDetailedTrackSelectorTool
-#IsoTrackSelectorTool_Muons = InDet__InDetDetailedTrackSelectorTool(
-#    name    = "DFIsoTrackSelectorTool_Muons",
-#    pTMin       = 1000.,
-#    nHolesPixel = 0,
-#    nHitSi      = 9,
-#    IPz0Max     = 3.,
-#    IPd0Max     = 999999.,
-#    etaMax = 2.5,
-#    nHitBLayer = 0,
-#    nHitPix = 0,
-#    nHitSiPhysical = 0,
-#    TrackSummaryTool = ToolSvc.InDetTrackSummaryTool,
-#    Extrapolator     = ToolSvc.InDetExtrapolator
-#    )
-#ToolSvc +=IsoTrackSelectorTool_Muons
-#
-##Track isolation tool
-#from IsolationTool.IsolationToolConf import xAOD__TrackIsolationTool
-#tit_Muons = xAOD__TrackIsolationTool(
-#    name               = "DFTrackIsolationTool_Muons",
-#    TrackSelectionTool = IsoTrackSelectorTool_Muons
-#    )
-#ToolSvc += tit_Muons
-#
-#from DerivationFrameworkMuons.DerivationFrameworkMuonsConf import DerivationFramework__IsolationAugmentationToolMuons
-#DFCommonIsolationMuons = DerivationFramework__IsolationAugmentationToolMuons(name               = "DFCommonIsolationMuons",
-#                                                                             TrackIsolationTool = tit_Muons,
-#                                                                             OutputLevel        = 3
-#                                                                             )
-#ToolSvc += DFCommonIsolationMuons
-#
-##=======================================
-## CREATE THE DERIVATION KERNEL ALGORITHM   
-##=======================================
-#if run_EDEgamma:
-#    DerivationFrameworkJob += EventDensityAlg("EDEgammaCentralAlg", EventDensityTool = tc)
-#    DerivationFrameworkJob += EventDensityAlg("EDEgammaForwardAlg", EventDensityTool = tf)
+ToolSvc += DFCommonMuonToolWrapperPreselection
+print DFCommonMuonToolWrapperPreselection
+DFCommonMuonToolWrapperTools.append(DFCommonMuonToolWrapperPreselection)
 
+#############
+#  Add tools
+#############
 from DerivationFrameworkCore.DerivationFrameworkCoreConf import DerivationFramework__CommonAugmentation
 DerivationFrameworkJob += CfgMgr.DerivationFramework__CommonAugmentation("DFCommonMuonsKernel",
-                                                                         #AugmentationTools = [DFCommonMuonToolWrapper,DFCommonIsolationMuons]
-#                                                                          AugmentationTools = [DFCommonMuonToolWrapper]
                                                                          AugmentationTools = DFCommonMuonToolWrapperTools
                                                                         )
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/python/StreamConfig.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/python/StreamConfig.py
index 3fde7a7d37f..0287077967e 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/python/StreamConfig.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/python/StreamConfig.py
@@ -19,6 +19,7 @@ def getMUON0TriggerContainers():
 'xAOD::MuonContainer#HLT_xAOD__MuonContainer_MuonEFInfo':'xAOD::MuonAuxContainer#HLT_xAOD__MuonContainer_MuonEFInfoAux.',
 'xAOD::MuonContainer#HLT_xAOD__MuonContainer_MuTagIMO_EF':'xAOD::MuonAuxContainer#HLT_xAOD__MuonContainer_MuTagIMO_EFAux.',
 'xAOD::MuonContainer#HLT_xAOD__MuonContainer_eMuonEFInfo':'xAOD::MuonAuxContainer#HLT_xAOD__MuonContainer_eMuonEFInfoAux.',
+'xAOD::MuonContainer#HLT_xAOD__MuonContainer_MuonEFInfo_FullScan':'xAOD::MuonAuxContainer#HLT_xAOD__MuonContainer_MuonEFInfo_FullScanAux.',
 'xAOD::MuonRoIContainer#HLT_xAOD__MuonRoIContainer_L1TopoMuon':'xAOD::MuonRoIAuxContainer#HLT_xAOD__MuonRoIContainer_L1TopoMuonAux.',
 'xAOD::TrackParticleContainer#HLT_xAOD__TrackParticleContainer_MuonEFInfo_CombTrackParticles':'xAOD::TrackParticleAuxContainer#HLT_xAOD__TrackParticleContainer_MuonEFInfo_CombTrackParticlesAux.',
 'xAOD::TrackParticleContainer#HLT_xAOD__TrackParticleContainer_MuonEFInfo_ExtrapTrackParticles':'xAOD::TrackParticleAuxContainer#HLT_xAOD__TrackParticleContainer_MuonEFInfo_ExtrapTrackParticlesAux.',
@@ -43,11 +44,11 @@ class MuonsDxAODStreamConfigurer:
     MUON0OnlyItems += ['xAOD::TrigNavigation#*','xAOD::TrigNavigationAuxInfo#*'] ## be careful, they could go to smart slimming...
 
     ### samrt slimming containers
-    comSmSlList = []
-    smSlContainer = {'MUON0':[], 'MUON1':['AntiKt4LCTopoJets'], 'MUON2':['AntiKt4LCTopoJets'], 'MUON3':[]}
+    comSmSlList = ["Muons", "PrimaryVertices", "InDetTrackParticles"]
+    smSlContainer = {'MUON0':[], 'MUON1':['AntiKt4LCTopoJets','AntiKt4EMTopoJets'], 'MUON2':['AntiKt4LCTopoJets','AntiKt4EMTopoJets'], 'MUON3':[]}
 
     ### all varaible containers
-    commonAllVarList = ["Muons", "PrimaryVertices", "InDetTrackParticles", "MuonSegments", "MuonTruthParticles", "CombinedMuonTrackParticles", "ExtrapolatedMuonTrackParticles", "MuonSpectrometerTrackParticles"]
+    commonAllVarList = ["Muons", "PrimaryVertices", "InDetTrackParticles", "MuonSegments", "MuonTruthParticles", "CombinedMuonTrackParticles", "ExtrapolatedMuonTrackParticles", "MuonSpectrometerTrackParticles", "InDetForwardTrackParticles"]
     MUON0OnlyAllVar = ['Staus','ExtrapolatedStauTrackParticles','CombinedStauTrackParticles','SlowMuons'] # slow muons
     MUON1OnlyAllVar = ['CaloCalTopoClusters', 'MuonClusterCollection']
 
@@ -66,6 +67,15 @@ class MuonsDxAODStreamConfigurer:
 
     checkContainers = {'MUON0':getMUON0TriggerContainers(), 'MUON1':getMUON0TriggerContainers(), 'MUON2':getMUON0TriggerContainers(), 'MUON3':getMUON0TriggerContainers()}
 
+    ### Extra variables
+    eventShapeVars = ['TopoClusterIsoCentralEventShape.DensitySigma.Density.DensityArea',
+                      'TopoClusterIsoForwardEventShape.DensitySigma.Density.DensityArea',
+                      'NeutralParticleFlowIsoCentralEventShape.DensitySigma.Density.DensityArea',
+                      'NeutralParticleFlowIsoForwardEventShape.DensitySigma.Density.DensityArea']
+
+    extraVariables = {'MUON1':eventShapeVars, 'MUON2':eventShapeVars}
+
+
     ### get final lists
     for s in Items: Items[s]+=commonItems
     for s in allVarContainer: allVarContainer[s]+=commonAllVarList
@@ -80,7 +90,7 @@ class MuonsDxAODStreamConfigurer:
         useSmartSlimmingIfSupported(self.checkContainers.get(configKey, []),self.allVarContainer[configKey], self.Items[configKey], SlHelper.NamesAndTypes)
         SlHelper.AllVariables = self.allVarContainer[configKey]
 #         SlHelper.StaticContent = self.Items[configKey]
-#         SlHelper.ExtraVariables = self.extraVariables.get(configKey, [])
+        SlHelper.ExtraVariables = self.extraVariables.get(configKey, [])
         SlHelper.IncludeMuonTriggerContent = self.UseTriggerContent.get(configKey, True)
         SlHelper.AppendContentToStream(stream)
 
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/python/TrackIsolationDecorator.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/python/TrackIsolationDecorator.py
index 415973072f9..37e58d42620 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/python/TrackIsolationDecorator.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/python/TrackIsolationDecorator.py
@@ -43,7 +43,7 @@ isoPar = ROOT.xAOD.Iso
 
 deco_ptcones = [isoPar.ptcone40, isoPar.ptcone30]
 deco_topoetcones = [isoPar.topoetcone40, isoPar.topoetcone20]
-deco_prefix = 'MUON1_'
+deco_prefix = 'MUON_'
 
 from DerivationFrameworkMuons.DerivationFrameworkMuonsConf import DerivationFramework__isolationDecorator
 MUON1IDTrackDecorator = DerivationFramework__isolationDecorator(name = "MUON1IDTrackDecorator",
@@ -71,7 +71,7 @@ MUON1MSTrackDecorator = DerivationFramework__isolationDecorator(name = "MUON1MST
                                                                 Prefix = deco_prefix
                                                                )
 
-deco_prefix2 = 'MUON2_'
+deco_prefix2 = 'MUON_'
 MUON2IDTrackDecorator = DerivationFramework__isolationDecorator(name = "MUON2IDTrackDecorator",
                                                                 TrackIsolationTool = TrackIsoTool,
                                                                 CaloIsolationTool = CaloIsoTool,
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/scripts/grid_submit.sh b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/scripts/grid_submit.sh
new file mode 100755
index 00000000000..8678d7d4cc9
--- /dev/null
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/scripts/grid_submit.sh
@@ -0,0 +1,12 @@
+# pathena --trf "Reco_tf.py --inputAODFile %IN --outputDAODFile T1.pool.root --reductionConf BPHY1 MUON2 --postExec='svcMgr.IOVDbSvc.CacheTime=100000' --passThrough True" --extOutFile DAOD_BPHY1.T1.pool.root,DAOD_MUON2.T1.test.pool.root --individualOutDS --inDS mc15_13TeV.300001.Pythia8BPhotospp_A14_CTEQ6L1_pp_Jpsimu4mu4.merge.AOD.e4397_s2608_r7042_r6282/ --outDS user.dzhang.daod_dev_MUON2_t2
+
+# pathena --trf "Reco_tf.py --inputAODFile %IN --outputDAODFile T1.pool.root --reductionConf BPHY1 MUON2 --postExec='svcMgr.IOVDbSvc.CacheTime=100000' --passThrough True" --extOutFile DAOD_BPHY1.T1.pool.root,DAOD_MUON2.T1.pool.root --individualOutDS --inDS mc15_13TeV.424100.Pythia8B_A14_CTEQ6L1_Jpsimu4mu4.merge.AOD.e3735_s2608_s2183_r7310_r6318/ --outDS user.dzhang.daod_dev_MUON2_t1e
+
+#non-prompt Jpsi MC
+pathena --trf "Reco_tf.py --inputAODFile %IN --outputDAODFile T1.pool.root --reductionConf BPHY1 MUON2 --postExec='svcMgr.IOVDbSvc.CacheTime=100000' --passThrough True" --extOutFile DAOD_BPHY1.T1.pool.root,DAOD_MUON2.T1.pool.root --individualOutDS --inDS mc15_13TeV:mc15_13TeV.300200.Pythia8BPhotospp_A14_CTEQ6L1_bb_Jpsimu2p5mu2p5.merge.AOD.e3989_a766_a807_r6282/ --outDS user.dzhang.daod_dev_MUON2_300200_a807_r6282_t2
+
+# pathena --trf "Reco_tf.py --inputAODFile %IN --outputDAODFile T1.pool.root --reductionConf BPHY1 MUON2 --postExec='svcMgr.IOVDbSvc.CacheTime=100000'" --extOutFile DAOD_BPHY1.T1.pool.root,DAOD_MUON2.T1.pool.root --individualOutDS --inDS data15_13TeV.00278880.physics_Main.merge.AOD.f628_m1497 --outDS user.dzhang.daod_dev_MUON2_00278880_m1497
+
+# pathena --trf "Reco_tf.py --inputAODFile %IN --outputDAODFile T1.pool.root --reductionConf BPHY1 MUON2 --postExec='svcMgr.IOVDbSvc.CacheTime=100000' --passThrough True" --extOutFile DAOD_BPHY1.T1.pool.root,DAOD_MUON2.T1.test.pool.root --individualOutDS --inDS mc15_13TeV.424100.Pythia8B_A14_CTEQ6L1_Jpsimu4mu4.merge.AOD.e3735_s2608_s2183_r7310_r6318/ --outDS user.dzhang.daod_dev_MUON2_t1c --excludedSite ANALY_FZK
+# pathena --trf "Reco_tf.py --inputAODFile %IN --outputDAODFile T1.pool.root --reductionConf BPHY1 MUON2 --postExec='svcMgr.IOVDbSvc.CacheTime=100000' --passThrough True" --extOutFile DAOD_BPHY1.T1.pool.root,DAOD_MUON2.T1.test.pool.root --nFilesPerJob=2 --nFiles=4 --individualOutDS --inDS mc15_13TeV.424100.Pythia8B_A14_CTEQ6L1_Jpsimu4mu4.merge.AOD.e3735_s2608_s2183_r7310_r6318/ --outDS user.dzhang.daod_dev_MUON2_t1
+# pathena --trf "Reco_tf.py --inputAODFile %IN --outputDAODFile T1.pool.root --reductionConf BPHY1 MUON2" --extOutFile DAOD_BPHY1.T1.pool.root,DAOD_MUON2.T1.test.pool.root --nFilesPerJob=1 --nFiles=1 --individualOutDS --official --voms atlas:/atlas/phys-GROUP/Role=production --inDS INPUTDATASET --outDS OUTPUTDATASET
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/scripts/trival_test.sh b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/scripts/trival_test.sh
new file mode 100755
index 00000000000..edb0ed74628
--- /dev/null
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/scripts/trival_test.sh
@@ -0,0 +1,31 @@
+OUT=Mar03_A
+
+runJob(){
+	input=$1
+	output=$2
+# 	Reco_tf.py --inputFileValidation False --inputAODFile $input --outputDAODFile ${output}.pool.root --reductionConf MUON0 MUON1 MUON2 MUON3 MUON4 --maxEvents 1000
+# 	Reco_tf.py --inputFileValidation False --inputAODFile $input --outputDAODFile ${output}.pool.root --reductionConf MUON0 MUON2 MUON3 --maxEvents 1000
+# 	Reco_tf.py --inputFileValidation False --inputAODFile $input --outputDAODFile ${output}.pool.root --reductionConf MUON0 --maxEvents 1000
+# 	Reco_tf.py --inputFileValidation False --inputAODFile $input --outputDAODFile ${output}.pool.root --reductionConf MUON0 --maxEvents 1000 --postExec="svcMgr.IOVDbSvc.CacheTime=100000"
+	Reco_tf.py --inputFileValidation False --inputAODFile $input --outputDAODFile ${output}.pool.root --reductionConf MUON0
+}
+
+OUT1=${OUT}1
+# INPUT=/home/dzhang/links/SAMPLES/R20/MC15/mc15_13TeV.361107.PowhegPythia8EvtGen_AZNLOCTEQ6L1_Zmumu.recon.AOD.e3601_s2576_s2132_r6630_tid05348608_00/AOD.05348608._004042.pool.root.1
+INPUT=root://eosatlas//eos/atlas/user/m/mdobre/forRTTmc15/MC15_AOD.pool.root
+runJob $INPUT $OUT1
+mv log.AODtoDAOD log_${OUT1}.AODtoDAOD
+
+# OUT2=${OUT}2
+# INPUT=/home/dzhang/links/SAMPLES/R20/MC15/mc15_13TeV.424100.Pythia8B_A14_CTEQ6L1_Jpsimu4mu4.merge.AOD.e3735_s2608_s2183_r6630_r6264_tid05382368_00/AOD.05382368._000014.pool.root.1
+# runJob $INPUT $OUT2
+# mv log.AODtoDAOD log_${OUT2}.AODtoDAOD
+
+OUT3=${OUT}3
+# INPUT=~/links/SAMPLES/R20/Data15/AOD/data15_13TeV.00267639.physics_Main.merge.AOD.r6818_p2358_tid05695962_00/AOD.05695962._000894.pool.root.1
+# INPUT=root://eosatlas//eos/atlas/user/m/mdobre/forRTTdata15/Data15_AOD.pool.root
+INPUT=root://eosatlas//eos/atlas/user/m/mdobre/forRTTdata15/Data15_207.AOD.pool.root
+runJob $INPUT $OUT3
+mv log.AODtoDAOD log_${OUT3}.AODtoDAOD
+
+for i in `ls DAOD_MUON*.${OUT}*.pool.root`; do j=${i##DAOD_}; k=${j%%.pool.root}; checkSG.py $i > ${k}_SG.txt; checkFile.py $i > ${k}_cF.txt; done
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/scripts/update_CPContent.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/scripts/update_CPContent.py
new file mode 100755
index 00000000000..dc98885e138
--- /dev/null
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/scripts/update_CPContent.py
@@ -0,0 +1,50 @@
+#!/usr/bin/env python
+
+# Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
+import sys 
+import os
+sys.path.append(os.path.abspath("../python"))
+import MuonsCPContent as mcc
+
+print mcc.MuonsCPContent
+
+def makeContent(l):
+    ct = 'MuonsCPContent = [\n'
+    for i in l:
+        ct += '"'+i+'",\n'
+    ct += ']'
+    return ct
+
+def mergeList(l1, l2, excludeList=[]):
+    l1a = []
+    for i in l1:
+        x = i.split('.')
+        tag=x[0]
+        found = False
+        for ji in range(len(l2)):
+            j = l2[ji]
+#         for j in l2:
+            y = j.split('.')
+            if tag!=y[0]: continue
+            found = True
+            for m in x[1:]:
+                if m in y[1:]: continue
+                print m, 'is not found for', tag
+                l2[ji] += '.'+m
+        if (not found) and (not (tag in excludeList)):
+            print tag, 'is not found'
+            l1a.append(i)
+    return l2+l1a
+
+ifile=sys.argv[1]
+list1 = []
+with open(ifile) as if1:
+    for line in if1.readlines():
+        list1.append(line.rstrip())
+print makeContent(list1)
+print makeContent(mcc.MuonsCPContent)
+
+kk = mergeList(list1, mcc.MuonsCPContent, ['EventInfo', 'EventInfoAux']) 
+nc = makeContent(kk)
+with open('new_MuonsCPContent.py','w') as fout1:
+    fout1.write(nc)
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/share/MUON0.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/share/MUON0.py
index 2d16cac80ba..8f1e9724067 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/share/MUON0.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/share/MUON0.py
@@ -55,11 +55,23 @@ MUON0ThinningTool2 = DerivationFramework__MuonTrackParticleThinning(name
                                                                     MuonKey                 = "Muons",
                                                                     SelectionString         = thinning_expression2,
                                                                     ConeSize                = 0.4,
-                                                                    ApplyAnd                = True,
+                                                                    ApplyAnd                = False,
                                                                     InDetTrackParticlesKey  = "InDetTrackParticles")
 ToolSvc += MUON0ThinningTool2
 MUON0_thinning_tools.append(MUON0ThinningTool2)
 
+### also for forward tracks
+# from DerivationFrameworkInDet.DerivationFrameworkInDetConf import DerivationFramework__MuonTrackParticleThinning
+# MUON0ThinningTool2f = DerivationFramework__MuonTrackParticleThinning(name                    = "MUON0ThinningTool2f",
+#                                                                     ThinningService         = "MUON0ThinningSvc",
+#                                                                     MuonKey                 = "Muons",
+#                                                                     SelectionString         = thinning_expression2,
+#                                                                     ConeSize                = 0.4,
+#                                                                     ApplyAnd                = False,
+#                                                                     InDetTrackParticlesKey  = "InDetForwardTrackParticles")
+# ToolSvc += MUON0ThinningTool2f
+# MUON0_thinning_tools.append(MUON0ThinningTool2f)
+
 ## keep tracks pt>2GeV
 # thinning_expression3 = "InDetTrackParticles.pt > 2*GeV"
 # from DerivationFrameworkInDet.DerivationFrameworkInDetConf import DerivationFramework__TrackParticleThinning
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/share/MUON1.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/share/MUON1.py
index a6d0279c310..a2cea6b178f 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/share/MUON1.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/share/MUON1.py
@@ -10,6 +10,8 @@ from DerivationFrameworkMuons.MuonsCommon import *
 # from DerivationFrameworkJetEtMiss.METCommon import *
 import AthenaCommon.SystemOfUnits as Units
 
+from MuonPerformanceAlgs.CommonMuonTPConfig import GetIDTrackCaloDepositsDecorator
+
 #====================================================================
 # AUGMENTATION TOOLS
 #====================================================================
@@ -21,6 +23,8 @@ import AthenaCommon.SystemOfUnits as Units
 brPrefix = 'MUON1'
 from DerivationFrameworkMuons.DerivationFrameworkMuonsConf import DerivationFramework__dimuonTaggingTool
 MUON1AugmentTool1 = DerivationFramework__dimuonTaggingTool(name = "MUON1AugmentTool1",
+#                                                            MuonTPExtrapoTool = CommonMuonTPConfig.
+                                                           IDTrackCaloDepoDecoTool = GetIDTrackCaloDepositsDecorator(),
                                                            Mu1PtMin = 24*Units.GeV,
                                                            Mu1AbsEtaMax = 2.5,
                                                            Mu1Types = [0],
@@ -112,6 +116,17 @@ ToolSvc += MUON1ThinningTool4
 print MUON1ThinningTool4
 MUON1ThinningTools.append(MUON1ThinningTool4)
 
+#====================================================================
+# JetTagNonPromptLepton decorations
+#====================================================================
+if not hasattr(DerivationFrameworkJob,"MUONSequence"):
+    MUONSeq = CfgMgr.AthSequencer("MUONSequence")
+    DerivationFrameworkJob += MUONSeq
+
+    if not hasattr(MUONSeq,"Muons_decoratePromptLepton"):
+        import JetTagNonPromptLepton.JetTagNonPromptLeptonConfig as Config
+        MUONSeq += Config.DecoratePromptLepton("Muons", "AntiKt4PV0TrackJets")
+
 #====================================================================
 # CREATE THE DERIVATION KERNEL ALGORITHM AND PASS THE ABOVE TOOLS 
 #====================================================================
@@ -122,6 +137,7 @@ DerivationFrameworkJob += CfgMgr.DerivationFramework__DerivationKernel("MUON1Ker
                                                                        SkimmingTools = [MUON1SkimmingTool1],
                                                                        ThinningTools = MUON1ThinningTools
                                                                        )
+
 #====================================================================
 # SET UP STREAM   
 #====================================================================
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/share/MUON2.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/share/MUON2.py
index e722747139e..5ceff732faf 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/share/MUON2.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/share/MUON2.py
@@ -9,6 +9,7 @@ from DerivationFrameworkCore.DerivationFrameworkMaster import *
 from DerivationFrameworkMuons.MuonsCommon import *
 # from DerivationFrameworkJetEtMiss.METCommon import *
 import AthenaCommon.SystemOfUnits as Units
+from MuonPerformanceAlgs.CommonMuonTPConfig import GetIDTrackCaloDepositsDecorator
 
 #====================================================================
 # AUGMENTATION TOOLS
@@ -28,6 +29,7 @@ andTriggers = andTriggers_run2
 brPrefix = 'MUON2'
 from DerivationFrameworkMuons.DerivationFrameworkMuonsConf import DerivationFramework__dimuonTaggingTool
 MUON2AugmentTool1 = DerivationFramework__dimuonTaggingTool(name = "MUON2AugmentTool1",
+                                                           IDTrackCaloDepoDecoTool = GetIDTrackCaloDepositsDecorator(),
                                                            OrTrigs = orTriggers,
                                                            AndTrigs = andTriggers,
                                                            Mu1PtMin = 4*Units.GeV,
@@ -95,6 +97,18 @@ MUON2ThinningTool2 = DerivationFramework__MuonTrackParticleThinning(name
                                                                     ApplyAnd                = False,
                                                                     InDetTrackParticlesKey  = "InDetTrackParticles")
 ToolSvc += MUON2ThinningTool2
+
+#====================================================================
+# JetTagNonPromptLepton decorations
+#====================================================================
+if not hasattr(DerivationFrameworkJob,"MUONSequence"):
+    MUONSeq = CfgMgr.AthSequencer("MUONSequence")
+    DerivationFrameworkJob += MUONSeq
+
+    if not hasattr(MUONSeq,"Muons_decoratePromptLepton"):
+        import JetTagNonPromptLepton.JetTagNonPromptLeptonConfig as Config
+        MUONSeq += Config.DecoratePromptLepton("Muons", "AntiKt4PV0TrackJets")
+
 #====================================================================
 # CREATE THE DERIVATION KERNEL ALGORITHM AND PASS THE ABOVE TOOLS 
 #====================================================================
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/share/MUON3.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/share/MUON3.py
index aa1583aed94..9ff2c08304c 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/share/MUON3.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/share/MUON3.py
@@ -9,6 +9,7 @@ from DerivationFrameworkCore.DerivationFrameworkMaster import *
 from DerivationFrameworkMuons.MuonsCommon import *
 # from DerivationFrameworkJetEtMiss.METCommon import *
 import AthenaCommon.SystemOfUnits as Units
+from MuonPerformanceAlgs.CommonMuonTPConfig import GetIDTrackCaloDepositsDecorator
 
 #====================================================================
 # AUGMENTATION TOOLS
@@ -34,6 +35,7 @@ andTriggers1_run2 = [] # No trigger in 8TeV data
 
 andTriggers1 = andTriggers1_run2
 MUON3AugmentTool1 = DerivationFramework__dimuonTaggingTool(name = "MUON3AugmentTool1",
+                                                           IDTrackCaloDepoDecoTool = GetIDTrackCaloDepositsDecorator(),
                                                            OrTrigs = orTriggers1,
                                                            AndTrigs = andTriggers1,
                                                            Mu1PtMin = 5.*Units.GeV,
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/src/components/DerivationFrameworkMuons_entries.cxx b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/src/components/DerivationFrameworkMuons_entries.cxx
index 72f944b2624..1c46788fd00 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/src/components/DerivationFrameworkMuons_entries.cxx
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/src/components/DerivationFrameworkMuons_entries.cxx
@@ -1,16 +1,15 @@
 #include "GaudiKernel/DeclareFactoryEntries.h"
 #include "DerivationFrameworkMuons/dimuonTaggingTool.h"
 #include "DerivationFrameworkMuons/isolationDecorator.h"
-//#include "DerivationFrameworkMuons/IsolationAugmentationToolMuons.h"
+#include "DerivationFrameworkMuons/mcpDecorator.h"
 using namespace DerivationFramework;
 
 DECLARE_TOOL_FACTORY( dimuonTaggingTool )
 DECLARE_TOOL_FACTORY( isolationDecorator )
-//DECLARE_TOOL_FACTORY( IsolationAugmentationToolMuons )
+DECLARE_TOOL_FACTORY( mcpDecorator )
 
 DECLARE_FACTORY_ENTRIES( DerivationFrameworkMuons ) {
    DECLARE_TOOL( dimuonTaggingTool )
    DECLARE_TOOL( isolationDecorator )
-   //DECLARE_TOOL( IsolationAugmentationToolMuons )
+   DECLARE_TOOL( mcpDecorator )
 }
-
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/src/dimuonTaggingTool.cxx b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/src/dimuonTaggingTool.cxx
index 6011127aeb4..102ffb02036 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/src/dimuonTaggingTool.cxx
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/src/dimuonTaggingTool.cxx
@@ -18,12 +18,16 @@
 #include "xAODTracking/TrackingPrimitives.h"
 #include "xAODTracking/TrackParticleContainer.h"
 #include "xAODTruth/TruthParticleContainer.h"
+#include "MuonTPTools/IMuonTPExtrapolationTool.h"
+#include "MuonTPTools/IIDTrackCaloDepositsDecoratorTool.h"
 
 // Constructor
 DerivationFramework::dimuonTaggingTool::dimuonTaggingTool(const std::string& t,
 							    const std::string& n,
 							    const IInterface* p):
   AthAlgTool(t, n, p),
+  m_tpExpTool("MuonTPExtrapolationTool/MuonTPExtrapolationTool"),
+  m_caloDepoTool("IDTrackCaloDepositsDecoratorTool/IDTrackCaloDepositsDecoratorTool"),
   m_matchTool( "Trig::TrigMuonMatching/TrigMuonMatching" ),
   m_trigDecisionTool("Trig::TrigDecisionTool/TrigDecisionTool")
 {
@@ -32,6 +36,8 @@ DerivationFramework::dimuonTaggingTool::dimuonTaggingTool(const std::string& t,
   declareProperty("OrTrigs", m_orTrigs=std::vector< std::string >());
   declareProperty("AndTrigs", m_andTrigs=std::vector< std::string >());
 
+  declareProperty("MuonTPExtrapoTool", m_tpExpTool, "Tool for MuonTPExtrapolation trigger matching");
+  declareProperty("IDTrackCaloDepoDecoTool", m_caloDepoTool, "Tool for ID track calo deposition decoration");
   declareProperty("TrigMatchTool", m_matchTool, "Tool for trigger matching");
   declareProperty("TriggerMatchDeltaR", m_triggerMatchDeltaR = 0.1);
 
@@ -58,6 +64,11 @@ DerivationFramework::dimuonTaggingTool::dimuonTaggingTool(const std::string& t,
 
   declareProperty("IDTrackThinningConeSize", m_thinningConeSize=0.4);
   declareProperty("BranchPrefix", m_br_prefix="");
+
+  /// for Coverity 109086 -- to be improved
+  m_invariantMassLow2 = m_invariantMassLow*fabs(m_invariantMassLow);
+  m_invariantMassHigh2 = m_invariantMassHigh*fabs(m_invariantMassHigh);
+  m_thinningConeSize2 = m_thinningConeSize*fabs(m_thinningConeSize);
 }
   
 // Destructor
@@ -88,6 +99,9 @@ StatusCode DerivationFramework::dimuonTaggingTool::initialize()
      return StatusCode::FAILURE;
   }
 
+  if( ! m_tpExpTool.empty() )  CHECK( m_tpExpTool.retrieve() );
+  if( ! m_caloDepoTool.empty() )  CHECK( m_caloDepoTool.retrieve() );
+
   m_invariantMassLow2 = m_invariantMassLow*fabs(m_invariantMassLow);
   m_invariantMassHigh2 = m_invariantMassHigh*fabs(m_invariantMassHigh);
   m_thinningConeSize2 = m_thinningConeSize*fabs(m_thinningConeSize);
@@ -156,6 +170,7 @@ StatusCode DerivationFramework::dimuonTaggingTool::fillInfo(int* keepEvent, std:
       if(mu_itr2==mu_itr1) continue;
       if(!passMuonCuts(mu_itr2, m_mu2PtMin, m_mu2AbsEtaMax, m_mu2Types, m_mu2Trigs, m_mu2IsoCuts)) continue;
       if(!muonPairCheck(mu_itr1, mu_itr2->charge(), mu_itr2->p4())) continue;
+      m_tpExpTool->dROnTriggerPivotPlane(*mu_itr1, mu_itr2);
       (*keepEvent)++;
     }
     if(m_useTrackProbe){
@@ -166,6 +181,8 @@ StatusCode DerivationFramework::dimuonTaggingTool::fillInfo(int* keepEvent, std:
         (*keepEvent)++;
         trackMask[mu_itr2->index()]+=100;
         maskNearbyIDtracks(mu_itr2, trackMask, tracks);
+        m_tpExpTool->dROnTriggerPivotPlane(*mu_itr1, mu_itr2);
+        ATH_CHECK(m_caloDepoTool->decorate(mu_itr2));
       }
     }
   }
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/src/isolationDecorator.cxx b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/src/isolationDecorator.cxx
index b6578e9086e..ea457e4e339 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/src/isolationDecorator.cxx
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/src/isolationDecorator.cxx
@@ -144,6 +144,11 @@ StatusCode DerivationFramework::isolationDecorator::addBranches() const
       if(dec_trkFlag(*particle)!=m_selFlagValue) continue;
      }
 
+    /// check if decorated already
+    static SG::AuxElement::Decorator< bool > dec_isoDecoDone(m_prefix+"IsoDecoDone");
+    if(dec_isoDecoDone.isAvailable(*particle) && dec_isoDecoDone(*particle)) continue;
+    dec_isoDecoDone(*particle) = true;
+
     /// track isolation
     xAOD::TrackIsolation resultTrack;
     if (m_trackIsolationTool->trackIsolation(resultTrack, *particle, m_ptconeTypes, m_trkCorrList)){
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/src/mcpDecorator.cxx b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/src/mcpDecorator.cxx
new file mode 100644
index 00000000000..5e242d7072f
--- /dev/null
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMuons/src/mcpDecorator.cxx
@@ -0,0 +1,204 @@
+/*
+  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"
+
+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() {}
+
+  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
+            proxyLoaders->push_back(new ExpressionParsing::SGxAODProxyLoader(evtStore())); // not deleted
+            m_parser = new ExpressionParsing::ExpressionParser(proxyLoaders);
+            m_parser->loadExpression(m_selectionString);
+    }
+
+    return StatusCode::SUCCESS;
+  }
+
+  StatusCode mcpDecorator::finalize() {
+    ATH_MSG_INFO ("Finalizing " << name() << "...");
+
+    /// clear parser
+    if (m_parser) {
+        delete m_parser;
+        m_parser = 0;
+    }
+
+
+    return StatusCode::SUCCESS;
+  }
+
+  StatusCode DerivationFramework::mcpDecorator::addBranches() const
+  {
+    // retrieve tag (muon) container
+    const xAOD::MuonContainer* toDecorate = 0;
+    if(evtStore()->retrieve(toDecorate, m_containerName).isFailure()) {
+      ATH_MSG_FATAL( "Unable to retrieve " << m_containerName );
+      return StatusCode::FAILURE;
+    }
+
+    // Execute the text parser and update the mask
+    std::vector<int> entries(toDecorate->size(), 1);
+    if (m_parser) {
+        entries =  m_parser->evaluateAsVector();
+        if (entries.size() != toDecorate->size()) {
+            ATH_MSG_ERROR("Sizes incompatible! Are you sure your selection string used ID TrackParticles?");
+            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