From 8937aa582ef0fb9d490c9f40bbe63f3799320a26 Mon Sep 17 00:00:00 2001
From: Andrii Usachov <andrii.usachov@cern.ch>
Date: Sun, 18 Sep 2022 20:00:11 +0200
Subject: [PATCH 01/15] define VeloBackward type instead of flag, remove Calo
 type

---
 Pr/PrConverters/src/PrConvertersInfo.h        |  13 +-
 Pr/PrConverters/src/fromPrTracksV1Track.cpp   |   9 +-
 Pr/PrConverters/src/fromV3TrackV1Track.cpp    |  14 +-
 Pr/PrMCTools/src/PrCheatedVP.cpp              |   5 +-
 Rec/LoKiTrack/include/LoKi/TrackCuts.h        |   7 +-
 Rec/LoKiTrack/python/LoKiTrack/functions.py   |   2 -
 Rec/LoKiTrack/src/Track.cpp                   |   2 -
 Rec/RecAlgs/src/RecSummaryAlg.cpp             |   2 +-
 Tf/FastPV/src/FastPVMonitor.cpp               |   4 +-
 Tr/PatPV/src/LSAdaptPV3DFitter.cpp            |   2 +-
 Tr/PatPV/src/LSAdaptPVFitter.cpp              |   2 +-
 Tr/PrKalmanFilter/include/PrKalmanFilter/KF.h |   8 +-
 Tr/PrKalmanFilter/src/KalmanFilterTool.cpp    |   6 +-
 .../src/TrackIPResolutionChecker.cpp          |   2 +-
 .../src/TrackIPResolutionCheckerNT.cpp        |   2 +-
 Tr/TrackCheckers/src/TrackPVChecker.cpp       |   2 +-
 Tr/TrackCheckers/src/TrackResChecker.cpp      |   2 +-
 Tr/TrackCheckers/src/VertexChecker.cpp        |   2 +-
 .../src/TrackStateProvider.cpp                |   2 +-
 Tr/TrackFitter/src/TrackMasterFitter.cpp      |  12 +-
 .../include/TrackKernel/TrackPredicates.h     |   2 +-
 Tr/TrackMCTools/src/MeasureIPResolution.cpp   |   2 +-
 Tr/TrackMonitors/src/TrackMonitor.cpp         |  16 +-
 Tr/TrackMonitors/src/TrackMonitorBase.cpp     |   1 -
 .../src/TrackMonitorTupleBase.cpp             |   1 -
 .../src/TrackVPOverlapMonitor.cpp             |   2 +-
 Tr/TrackMonitors/src/TrackVertexMonitor.cpp   |   8 +-
 Tr/TrackMonitors/src/VPTrackMonitor.cpp       |   2 +-
 .../src/LongTrackReferenceCreator.cpp         |   2 +-
 .../src/TrackMaterialParametrizer.cpp         | 391 ++++++++++++++++++
 Tr/TrackTools/src/TrackSelectorBase.h         |   2 +-
 Tr/TrackTools/src/UpgradeGhostId.cpp          |   5 +-
 Tr/TrackTools/src/VeloMuonBuilder.cpp         |   2 +-
 Tr/TrackUtils/src/TrackBestTrackCreator.cpp   |  65 +--
 Tr/TrackUtils/src/TracksVPConverter.cpp       |  10 +-
 Tr/TrackUtils/src/VertexListRefiner.cpp       |   2 +-
 36 files changed, 502 insertions(+), 111 deletions(-)
 create mode 100644 Tr/TrackTools/src/TrackMaterialParametrizer.cpp

diff --git a/Pr/PrConverters/src/PrConvertersInfo.h b/Pr/PrConverters/src/PrConvertersInfo.h
index 27da0a17e9c..8954f50bb29 100644
--- a/Pr/PrConverters/src/PrConvertersInfo.h
+++ b/Pr/PrConverters/src/PrConvertersInfo.h
@@ -84,30 +84,27 @@ namespace LHCb::Pr::ConversionInfo {
         std::make_pair( LHCb::State::Location::ClosestToBeam, 0 ), std::make_pair( LHCb::State::Location::EndVelo, 1 )};
     static constexpr bool                                           AddStatesFromAncestor = false;
     static constexpr std::array<const char*, 0>                     AncestorLocations     = {};
-    static constexpr std::pair<LHCb::Event::v1::Track::Flags, bool> Flag = {LHCb::Event::v1::Track::Flags::Backward,
-                                                                            false};
   };
 
   struct VeloBackward {
-    static constexpr LHCb::Event::v1::Track::Types   Type      = LHCb::Event::v1::Track::Types::Velo;
+    static constexpr LHCb::Event::v1::Track::Types   Type      = LHCb::Event::v1::Track::Types::VeloBackward;
     static constexpr LHCb::Event::v1::Track::History PrHistory = LHCb::Event::v1::Track::History::PrPixel;
     static constexpr std::array<std::pair<LHCb::State::Location, int>, 1> StateLocations = {
         std::make_pair( LHCb::State::Location::ClosestToBeam, 0 )};
     static constexpr bool                                           AddStatesFromAncestor = false;
     static constexpr std::array<const char*, 0>                     AncestorLocations     = {{}};
-    static constexpr std::pair<LHCb::Event::v1::Track::Flags, bool> Flag = {LHCb::Event::v1::Track::Flags::Backward,
-                                                                            true};
   };
 
   struct Velo {
-    static constexpr LHCb::Event::v1::Track::Types   Type      = LHCb::Event::v1::Track::Types::Velo;
+    static LHCb::Event::v1::Track::Types Type( bool backward=false ){
+      if ( backward ) return LHCb::Event::v1::Track::Types::VeloBackward;
+      else return LHCb::Event::v1::Track::Types::Velo;  
+    }
     static constexpr LHCb::Event::v1::Track::History PrHistory = LHCb::Event::v1::Track::History::PrPixel;
     static constexpr std::array<std::pair<LHCb::State::Location, int>, 2> StateLocations = {
         std::make_pair( LHCb::State::Location::ClosestToBeam, 0 ), std::make_pair( LHCb::State::Location::EndVelo, 1 )};
     static constexpr bool                                           AddStatesFromAncestor = false;
     static constexpr std::array<const char*, 0>                     AncestorLocations     = {};
-    static constexpr std::pair<LHCb::Event::v1::Track::Flags, bool> Flag = {LHCb::Event::v1::Track::Flags::Backward,
-                                                                            false};
   };
 
   struct Seeding {
diff --git a/Pr/PrConverters/src/fromPrTracksV1Track.cpp b/Pr/PrConverters/src/fromPrTracksV1Track.cpp
index 0e6da642d70..5f2355c7764 100644
--- a/Pr/PrConverters/src/fromPrTracksV1Track.cpp
+++ b/Pr/PrConverters/src/fromPrTracksV1Track.cpp
@@ -303,10 +303,11 @@ namespace LHCb {
               auto outTrack   = createFromAncestor<TrackType, ConversionInfo>( inTrack, ancestorTracks... );
               //  ---
               ConvertTrack<TrackType, PrTracksType, ConversionInfo>( outTrack, inTrack, errors, m_veloPT );
-              outTrack->setType( ConversionInfo::Type );
+              if constexpr ( std::is_same_v<ConversionInfo, LHCb::Pr::ConversionInfo::Velo> )
+                outTrack->setType( ConversionInfo::Type( inTrack.backward() ) );
+              else
+                outTrack->setType( ConversionInfo::Type );
               outTrack->setHistory( ConversionInfo::PrHistory );
-              if constexpr ( std::is_same_v<PrTracksType, LHCb::Pr::Velo::Tracks> )
-                outTrack->setFlag( ConversionInfo::Flag.first, ConversionInfo::Flag.second );
               outTracks.insert( outTrack );
             }
             return outTracks;
@@ -397,7 +398,6 @@ namespace LHCb {
               ConvertTrack<TrackType, PrTracksType, ConversionInfo1>( outTrack, inTrack, errors, m_veloPT );
               outTrack->setType( ConversionInfo1::Type );
               outTrack->setHistory( ConversionInfo1::PrHistory );
-              outTrack->setFlag( ConversionInfo1::Flag.first, ConversionInfo1::Flag.second );
               outTracks.insert( outTrack );
             }
 
@@ -409,7 +409,6 @@ namespace LHCb {
               ConvertTrack<TrackType, PrTracksType, ConversionInfo2>( outTrack, inTrack, errors, m_veloPT );
               outTrack->setType( ConversionInfo2::Type );
               outTrack->setHistory( ConversionInfo2::PrHistory );
-              outTrack->setFlag( ConversionInfo2::Flag.first, ConversionInfo2::Flag.second );
               outTracks.insert( outTrack );
             }
 
diff --git a/Pr/PrConverters/src/fromV3TrackV1Track.cpp b/Pr/PrConverters/src/fromV3TrackV1Track.cpp
index 1993a7af899..5a0177d7db7 100644
--- a/Pr/PrConverters/src/fromV3TrackV1Track.cpp
+++ b/Pr/PrConverters/src/fromV3TrackV1Track.cpp
@@ -95,6 +95,10 @@ namespace {
       new_track.addInfo( out_track::AdditionalInfo::FitVeloChi2, in_partial_chi2.FitVeloChi2().cast() );
       new_track.addInfo( out_track::AdditionalInfo::FitVeloNDoF, in_partial_chi2.FitVeloNDoF().cast() );
       break;
+    case out_track::Types::VeloBackward:
+      new_track.addInfo( out_track::AdditionalInfo::FitVeloChi2, in_partial_chi2.FitVeloChi2().cast() );
+      new_track.addInfo( out_track::AdditionalInfo::FitVeloNDoF, in_partial_chi2.FitVeloNDoF().cast() );
+      break;
     case out_track::Types::Ttrack:
       new_track.addInfo( out_track::AdditionalInfo::FitTChi2, in_partial_chi2.FitTChi2().cast() );
       new_track.addInfo( out_track::AdditionalInfo::FitTNDoF, in_partial_chi2.FitTNDoF().cast() );
@@ -135,8 +139,6 @@ namespace {
       return update_states_impl( new_track, inTrack, LHCb::Event::v3::available_states_t<trtype_t::Upstream>{} );
     case LHCb::Event::v3::TrackType::Muon:
       return update_states_impl( new_track, inTrack, LHCb::Event::v3::available_states_t<trtype_t::Muon>{} );
-    case LHCb::Event::v3::TrackType::Calo:
-      return update_states_impl( new_track, inTrack, LHCb::Event::v3::available_states_t<trtype_t::Calo>{} );
     case LHCb::Event::v3::TrackType::UT:
       return update_states_impl( new_track, inTrack, LHCb::Event::v3::available_states_t<trtype_t::UT>{} );
     case LHCb::Event::v3::TrackType::Unknown:
@@ -150,9 +152,6 @@ namespace {
   template <typename TrackProxy>
   void convert_track( LHCb::Event::v1::Track& new_track, TrackProxy const& inTrack ) {
 
-    auto v1_track_type = conversion::to_v1_track_type( inTrack.type() );
-
-    new_track.setType( v1_track_type );
     new_track.setHistory( inTrack.history().cast() );
 
     new_track.setPatRecStatus( LHCb::Event::v1::Track::PatRecStatus::PatRecIDs );
@@ -209,7 +208,10 @@ namespace LHCb::Converters::Track::v1 {
       int counter = 0;
       for ( auto const track_with_extra_info : tracks_with_extra_infos ) {
         auto new_track = new LHCb::Event::v1::Track{};
-        if ( in_tracks.backward() ) new_track->setFlag( LHCb::Track::Flags::Backward, true );
+        if ( in_tracks.backward() ) 
+          new_track->setType( LHCb::Track::Types::VeloBackward );
+        else
+          new_track->setType( conversion::to_v1_track_type( track_with_extra_info.type() ) );
         convert_track( *new_track, track_with_extra_info );
 
         if constexpr ( has_partial_chisquareds ) { add_partial_chi2s( *new_track, track_with_extra_info ); }
diff --git a/Pr/PrMCTools/src/PrCheatedVP.cpp b/Pr/PrMCTools/src/PrCheatedVP.cpp
index 06d4ba75933..fb46cc56919 100644
--- a/Pr/PrMCTools/src/PrCheatedVP.cpp
+++ b/Pr/PrMCTools/src/PrCheatedVP.cpp
@@ -96,12 +96,13 @@ namespace {
       state.setState( x0, y0, zVelo, x1, y1, 0. );
       track->addToStates( state );
       if ( 0 > particle->momentum().z() ) {
-        track->setFlag( LHCb::Track::Flags::Backward, true );
+        track->setType( LHCb::Track::Types::VeloBackward );
         // Cut out backwards tracks.
         // delete track;
         // continue;
+      } else {
+        track->setType( LHCb::Track::Types::Velo );
       }
-      track->setType( LHCb::Track::Types::Velo );
       tracks.insert( track );
     }
 
diff --git a/Rec/LoKiTrack/include/LoKi/TrackCuts.h b/Rec/LoKiTrack/include/LoKi/TrackCuts.h
index cb261326992..2d7a78e8e8b 100644
--- a/Rec/LoKiTrack/include/LoKi/TrackCuts.h
+++ b/Rec/LoKiTrack/include/LoKi/TrackCuts.h
@@ -66,12 +66,13 @@ namespace LoKi {
      *    const bool backward = TrBACKWARD ( track ) ;
      *
      *  @endcode
-     *  @see LoKi::Cuts::TrISFLAG
-     *  @see LoKi::Track::CheckFlag
+     *  @see LoKi::Track::TrTYPE
      *  @author Vanya BELYAEV ibelyaev@physics.syr.edu
      *  @date   2007-06-08
      */
-    inline const auto TrBACKWARD = LoKi::Track::CheckFlag{LHCb::Track::Flags::Backward};
+    inline const auto TrBACKWARD =
+        LoKi::EqualToValue<const LHCb::Track*, double>{TrTYPE, static_cast<int>( LHCb::Track::Types::VeloBackward )};
+    
     // ========================================================================
     /** @var TrCHI2
      *  the simple function which returns LHCb::Track::Chi2
diff --git a/Rec/LoKiTrack/python/LoKiTrack/functions.py b/Rec/LoKiTrack/python/LoKiTrack/functions.py
index ba2b894d329..8f28563a4ed 100644
--- a/Rec/LoKiTrack/python/LoKiTrack/functions.py
+++ b/Rec/LoKiTrack/python/LoKiTrack/functions.py
@@ -70,8 +70,6 @@ TrTYPE = LoKi.Track.Type()
 
 ## @see @see LoKi::Cuts::TrALL
 TrALL = LoKi.Constant(_T, bool)(True)
-## @see LoKi::Cuts::TrBACKWARD
-TrBACKWARD = LoKi.Track.CheckFlag(TrackEnums.Flag.Backward)
 ## @see LoKi::Cuts::TrCHI2
 TrCHI2 = LoKi.Track.Chi2()
 ## @see LoKi::Cuts::TrCHI2PDOF
diff --git a/Rec/LoKiTrack/src/Track.cpp b/Rec/LoKiTrack/src/Track.cpp
index 96daf9df9d5..ece6c6dfefa 100644
--- a/Rec/LoKiTrack/src/Track.cpp
+++ b/Rec/LoKiTrack/src/Track.cpp
@@ -57,8 +57,6 @@ LoKi::Track::CheckFlag::CheckFlag( LHCb::Track::Flags flag )
 // ============================================================================
 std::ostream& LoKi::Track::CheckFlag::fillStream( std::ostream& s ) const {
   switch ( m_flag ) {
-  case LHCb::Track::Flags::Backward:
-    return s << "TrBACKWARD"; // RETURN
   case LHCb::Track::Flags::Invalid:
     return s << "TrINVALID"; // RETURN
   case LHCb::Track::Flags::Clone:
diff --git a/Rec/RecAlgs/src/RecSummaryAlg.cpp b/Rec/RecAlgs/src/RecSummaryAlg.cpp
index 71a748c9be9..14e92c40282 100644
--- a/Rec/RecAlgs/src/RecSummaryAlg.cpp
+++ b/Rec/RecAlgs/src/RecSummaryAlg.cpp
@@ -179,7 +179,7 @@ StatusCode RecSummaryAlg::execute() {
         ++nT;
         break;
       case LHCb::Track::Types::Velo:
-        if ( tk->checkFlag( LHCb::Track::Flags::Backward ) ) ++nBack;
+        if ( tk->checkType( LHCb::Track::Types::VeloBackward ) ) ++nBack;
         break;
       default:;
       }
diff --git a/Tf/FastPV/src/FastPVMonitor.cpp b/Tf/FastPV/src/FastPVMonitor.cpp
index 4d972572490..484443a6ee5 100644
--- a/Tf/FastPV/src/FastPVMonitor.cpp
+++ b/Tf/FastPV/src/FastPVMonitor.cpp
@@ -196,7 +196,7 @@ StatusCode FastPVMonitor::execute() {
 
   // Number of tracks with IP between min and max values
   for ( LHCb::Tracks::iterator itT = tracks->begin(); tracks->end() != itT; ++itT ) { // loop over tracks
-    if ( ( *itT )->checkFlag( LHCb::Track::Flags::Backward ) ) continue;              // avoid backward tracks
+    if ( ( *itT )->checkType( LHCb::Track::Types::VeloBackward ) ) continue;              // avoid backward tracks
     Gaudi::XYZPoint  point = ( *itT )->position();                                    // track position (first hit ?)
     Gaudi::XYZVector dir   = ( *itT )->slopes();                                      // track direction
 
@@ -260,7 +260,7 @@ StatusCode FastPVMonitor::execute() {
 #ifdef DEBUG_HISTO
   if ( MCvs ) {
     for ( LHCb::Tracks::iterator itT = tracks->begin(); tracks->end() != itT; ++itT ) // loop over tracks
-    { // if ( (*itT)->checkFlag( LHCb::Track::Flags::Backward ) ) continue;                       // avoid backward
+    { // if ( (*itT)->checkType( LHCb::Track::Types::VeloBackward ) ) continue;                       // avoid backward
       // tracks
       Gaudi::XYZPoint  point = ( *itT )->position(); // track position (first hit ?)
       Gaudi::XYZVector dir   = ( *itT )->slopes();   // track direction
diff --git a/Tr/PatPV/src/LSAdaptPV3DFitter.cpp b/Tr/PatPV/src/LSAdaptPV3DFitter.cpp
index 732d205a18f..298291ea143 100644
--- a/Tr/PatPV/src/LSAdaptPV3DFitter.cpp
+++ b/Tr/PatPV/src/LSAdaptPV3DFitter.cpp
@@ -311,7 +311,7 @@ double LSAdaptPV3DFitter::err2d0( const LHCb::Track* track, const Gaudi::XYZPoin
   double fsin2 = tr2 / ( 1. + tr2 );
   double err2  = ( ex2 + ey2 ) * fcos2;
 
-  bool backward = track->checkFlag( LHCb::Track::Flags::Backward );
+  bool backward = track->checkType( LHCb::Track::Types::VeloBackward );
 
   double z_seed = seed.z();
   double dz_pv  = z - z_seed;
diff --git a/Tr/PatPV/src/LSAdaptPVFitter.cpp b/Tr/PatPV/src/LSAdaptPVFitter.cpp
index 9060af8c258..33a3189b10b 100644
--- a/Tr/PatPV/src/LSAdaptPVFitter.cpp
+++ b/Tr/PatPV/src/LSAdaptPVFitter.cpp
@@ -234,7 +234,7 @@ StatusCode LSAdaptPVFitter::fit( LHCb::RecVertex& vtx, std::vector<PVTrack*>& pv
 
       if ( ( *itrack )->chi2 < 100. ) {
         const LHCb::Track* lbtrack = ( *itrack )->refTrack;
-        int                back    = lbtrack->checkFlag( LHCb::Track::Flags::Backward );
+        int                back    = lbtrack->checkType( LHCb::Track::Types::VeloBackward );
         int                velo =
             ( lbtrack->checkType( LHCb::Track::Types::Velo ) || lbtrack->checkType( LHCb::Track::Types::Upstream ) );
         int longtr = lbtrack->checkType( LHCb::Track::Types::Long );
diff --git a/Tr/PrKalmanFilter/include/PrKalmanFilter/KF.h b/Tr/PrKalmanFilter/include/PrKalmanFilter/KF.h
index 073f3481e4c..3d42795cf65 100644
--- a/Tr/PrKalmanFilter/include/PrKalmanFilter/KF.h
+++ b/Tr/PrKalmanFilter/include/PrKalmanFilter/KF.h
@@ -1022,7 +1022,7 @@ namespace LHCb::Pr::Tracks::Fit {
         is_ctb_first = ctb_z < first_hit.z();
         if constexpr ( std::is_same_v<TrackProxy, LHCb::Event::v1::Track> ) {
           // no effect for v3::Tracks
-          if ( newtrack.checkFlag( LHCb::Track::Flags::Backward ) ) is_ctb_first = !is_ctb_first;
+          if ( newtrack.checkType( LHCb::Track::Types::VeloBackward ) ) is_ctb_first = !is_ctb_first;
         }
       }
 
@@ -1183,7 +1183,10 @@ namespace LHCb::Pr::Tracks::Fit {
 
       } else if constexpr ( isVelo<InputTrackType> ) {
 
-        return std::make_unique<out_track>( History::PrPixel, Type::Velo, PatRecStatus::PatRecIDs );
+        if ( track.backward() )
+          return std::make_unique<out_track>( History::PrPixel, Type::VeloBackward, PatRecStatus::PatRecIDs );
+        else
+          return std::make_unique<out_track>( History::PrPixel, Type::Velo, PatRecStatus::PatRecIDs );
 
       } else if constexpr ( isSeed<InputTrackType> ) {
 
@@ -1220,7 +1223,6 @@ namespace LHCb::Pr::Tracks::Fit {
 
       new_track->addInfo( AdditionalInfo::FitVeloChi2, velo_chi2.chi2() );
       new_track->addInfo( AdditionalInfo::FitVeloNDoF, velo_chi2.nDoF() );
-      if ( track.backward() ) new_track->setFlag( LHCb::Track::Flags::Backward, true );
 
     } else if constexpr ( isDownstream<InputTrackType> || isSeed<InputTrackType> ) {
 
diff --git a/Tr/PrKalmanFilter/src/KalmanFilterTool.cpp b/Tr/PrKalmanFilter/src/KalmanFilterTool.cpp
index b9249cc3673..d523b7e7129 100644
--- a/Tr/PrKalmanFilter/src/KalmanFilterTool.cpp
+++ b/Tr/PrKalmanFilter/src/KalmanFilterTool.cpp
@@ -59,7 +59,7 @@ namespace LHCb::Pr {
 
       if constexpr ( has_hit_type<HitType::VP, Types...> && !has_hit_type<HitType::FT, Types...> &&
                      !has_hit_type<HitType::UT, Types...> ) {
-        assert( track.checkType( TrackV1::Types::Velo ) );
+        assert( track.checkType( TrackV1::Types::Velo ) || track.checkType( TrackV1::Types::Backward ) );
       } else if constexpr ( !has_hit_type<HitType::VP, Types...> && has_hit_type<HitType::FT, Types...> &&
                             has_hit_type<HitType::UT, Types...> ) {
         assert( track.checkType( TrackV1::Types::Downstream ) );
@@ -71,8 +71,7 @@ namespace LHCb::Pr {
         assert( track.checkType( TrackV1::Types::Ttrack ) );
       } else if constexpr ( has_hit_type<HitType::VP, Types...> && has_hit_type<HitType::FT, Types...> &&
                             has_hit_type<HitType::UT, Types...> ) {
-        assert( track.checkType( TrackV1::Types::Long ) || track.checkType( TrackV1::Types::Velo ) ||
-                track.checkType( TrackV1::Types::Downstream ) || track.checkType( TrackV1::Types::Upstream ) );
+        assert( track.checkType( TrackV1::Types::Long ) || track.checkType( TrackV1::Types::Velo ) || track.checkType( TrackV1::Types::VeloBackward ) || track.checkType( TrackV1::Types::Downstream ) || track.checkType( TrackV1::Types::Upstream ) );
       } else {
         static_assert( always_false<std::integral_constant<HitType, Types>...>::value,
                        "Hit Containers do not match any supported track type" );
@@ -209,6 +208,7 @@ namespace LHCb::Pr {
         }
         break;
       case TrackV1::Types::Velo:
+      case TrackV1::Types::VeloBackward:
         new_track.addInfo( TrackV1::AdditionalInfo::FitVeloChi2, velo_chi2.chi2() );
         new_track.addInfo( TrackV1::AdditionalInfo::FitVeloNDoF, velo_chi2.nDoF() );
         if ( add_fitted_states<Velo::Tracks>( new_track, fitnodes, scatteringMomentum, geo, extrap ).isFailure() ) {
diff --git a/Tr/TrackCheckers/src/TrackIPResolutionChecker.cpp b/Tr/TrackCheckers/src/TrackIPResolutionChecker.cpp
index 346b4909cde..4f5a284065f 100644
--- a/Tr/TrackCheckers/src/TrackIPResolutionChecker.cpp
+++ b/Tr/TrackCheckers/src/TrackIPResolutionChecker.cpp
@@ -431,7 +431,7 @@ StatusCode TrackIPResolutionChecker::execute() {
   // Finally, we also want to monitor the reconstructed IP, so the IP with respect to the reconstructed PVs.
   if ( !pvs.empty() ) {
     for ( const LHCb::Track* track : tracks )
-      if ( !track->checkFlag( LHCb::Track::Flags::Backward ) ) {
+      if ( !track->checkType( LHCb::Track::Types::VeloBackward ) ) {
         const LHCb::MCParticle* mcparticle = linker.first( track );
         // distinghuish secondaries, from primaries, from ghosts
         bool        hasMCMatch = mcparticle && mcparticle->originVertex();
diff --git a/Tr/TrackCheckers/src/TrackIPResolutionCheckerNT.cpp b/Tr/TrackCheckers/src/TrackIPResolutionCheckerNT.cpp
index 7860591b99e..601c75651ea 100644
--- a/Tr/TrackCheckers/src/TrackIPResolutionCheckerNT.cpp
+++ b/Tr/TrackCheckers/src/TrackIPResolutionCheckerNT.cpp
@@ -146,7 +146,7 @@ namespace {
           .ignore( /* AUTOMATICALLY ADDED FOR gaudi/Gaudi!763 */ );
       theTuple->column( "TNdof", track->info( LHCb::Track::AdditionalInfo::FitTNDoF, 0 ) )
           .ignore( /* AUTOMATICALLY ADDED FOR gaudi/Gaudi!763 */ );
-      theTuple->column( "backward", track->checkFlag( LHCb::Track::Flags::Backward ) )
+      theTuple->column( "backward", track->checkType( LHCb::Track::Types::VeloBackward ) )
           .ignore( /* AUTOMATICALLY ADDED FOR gaudi/Gaudi!763 */ );
 
       const LHCb::State* stateAtFirstHit = track->stateAt( LHCb::State::Location::FirstMeasurement );
diff --git a/Tr/TrackCheckers/src/TrackPVChecker.cpp b/Tr/TrackCheckers/src/TrackPVChecker.cpp
index ffac07b2881..9bae21173cf 100644
--- a/Tr/TrackCheckers/src/TrackPVChecker.cpp
+++ b/Tr/TrackCheckers/src/TrackPVChecker.cpp
@@ -610,7 +610,7 @@ void TrackPVChecker::operator()( PrimaryVertexContainer const& vertices, ///< Al
       plot1D( wtrk.weight, "pvtrkweight", "Track weight", 0, 1 );
       if ( wtrk.track ) plot1D( int( wtrk.track->type() ), "pvtrktype", "Track type", -0.5, 20.5, 21 );
       usedtracks.insert( wtrk.track );
-      if ( !wtrk.track || wtrk.track->checkFlag( Track::Flag::Backward ) ) ++numbackward;
+      if ( !wtrk.track || wtrk.track->checkType( Track::Type::VeloBackward ) ) ++numbackward;
     }
     plot1D( numbackward, "pvnumbackwardtracks", "Number of backward tracks", -0.5, 50.5, 51 );
   }
diff --git a/Tr/TrackCheckers/src/TrackResChecker.cpp b/Tr/TrackCheckers/src/TrackResChecker.cpp
index a86daaa58c7..84d0bfd9c52 100644
--- a/Tr/TrackCheckers/src/TrackResChecker.cpp
+++ b/Tr/TrackCheckers/src/TrackResChecker.cpp
@@ -96,7 +96,7 @@ StatusCode TrackResChecker::initialize() {
     if ( splitByType() ) {
       using Type = LHCb::Track::Types;
       constexpr auto types =
-          std::array{Type::Velo, Type::Long, Type::Upstream, Type::Downstream, Type::Ttrack, Type::Muon};
+          std::array{Type::Velo, Type::VeloBackward, Type::Long, Type::Upstream, Type::Downstream, Type::Ttrack, Type::Muon};
       for ( auto type : types ) { m_histoTools[static_cast<int>( type )] = createHistoTool( toString( type ) ); }
     }
   } );
diff --git a/Tr/TrackCheckers/src/VertexChecker.cpp b/Tr/TrackCheckers/src/VertexChecker.cpp
index 51708e23e1b..d5fa1f0ee29 100644
--- a/Tr/TrackCheckers/src/VertexChecker.cpp
+++ b/Tr/TrackCheckers/src/VertexChecker.cpp
@@ -211,7 +211,7 @@ void VertexChecker::operator()( LHCb::MCVertices const& mcVertices, LHCb::RecVer
 
   // Number of tracks with IP between min and max values
   for ( const auto& itT : veloTracks ) {
-    if ( itT->checkFlag( LHCb::Track::Flags::Backward ) ) continue;
+    if ( itT->checkType( LHCb::Track::Types::VeloBackward ) ) continue;
     Gaudi::XYZPoint  point = itT->position();
     Gaudi::XYZVector dir   = itT->slopes();
     auto [lowestIP, best]  = std::accumulate(
diff --git a/Tr/TrackExtrapolators/src/TrackStateProvider.cpp b/Tr/TrackExtrapolators/src/TrackStateProvider.cpp
index 2a90e8836a3..7bc57a81012 100644
--- a/Tr/TrackExtrapolators/src/TrackStateProvider.cpp
+++ b/Tr/TrackExtrapolators/src/TrackStateProvider.cpp
@@ -406,7 +406,7 @@ TrackCache TrackStateProvider::createCacheEntry( TkCacheKey key, const LHCb::Tra
   // at the beamline and at rich2. For the trajectory approximation
   // used in DTF for Long-Long Ks, this is not enough. Add a state at
   // the end of the Velo.
-  if ( !track.checkFlag( LHCb::Track::Flags::Backward ) && track.hasVelo() &&
+  if ( !track.checkType( LHCb::Track::Types::VeloBackward ) && track.hasVelo() &&
        !track.stateAt( LHCb::State::Location::FirstMeasurement ) ) {
     addState( tc, StateParameters::ZEndVelo, geometry, LHCb::State::Location::EndVelo );
   }
diff --git a/Tr/TrackFitter/src/TrackMasterFitter.cpp b/Tr/TrackFitter/src/TrackMasterFitter.cpp
index 0a15ca1ab9b..4e88d9a75fa 100644
--- a/Tr/TrackFitter/src/TrackMasterFitter.cpp
+++ b/Tr/TrackFitter/src/TrackMasterFitter.cpp
@@ -355,8 +355,8 @@ StatusCode TrackMasterFitter::determineStates( Track& track ) const {
   auto* lastMeasurementNode  = ( jnode != nodes_.crend() ? *jnode : nullptr );
 
   bool upstream = nodes_.front()->z() > nodes_.back()->z();
-  bool reversed = ( upstream && !track.checkFlag( Track::Flags::Backward ) ) ||
-                  ( !upstream && track.checkFlag( Track::Flags::Backward ) );
+  bool reversed = ( upstream && !track.checkType( Track::Types::VeloBackward ) ) ||
+                  ( !upstream && track.checkType( Track::Types::VeloBackward ) );
 
   // This state is not filtered for a forward only fit.
   if ( m_addDefaultRefNodes.value() ) {
@@ -617,7 +617,7 @@ StatusCode TrackMasterFitter::makeNodes( Track& track, const LHCb::Tr::PID pid,
 
   // Add reference nodes depending on track type
   if ( m_addDefaultRefNodes.value() ) {
-    if ( track.hasVelo() && !track.checkFlag( Track::Flags::Backward ) )
+    if ( track.hasVelo() && !track.checkType( Track::Types::VeloBackward ) )
       nodes.push_back( new FitNode( StateParameters::ZEndVelo, State::Location::EndVelo ) );
     if ( track.hasUT() ) {
       nodes.push_back( new FitNode( StateParameters::ZBegRich1, State::Location::BegRich1 ) );
@@ -633,12 +633,12 @@ StatusCode TrackMasterFitter::makeNodes( Track& track, const LHCb::Tr::PID pid,
   // At a node for the position at the beamline
   if ( m_stateAtBeamLine.value() && track.hasVelo() ) {
     const LHCb::State& refstate =
-        *( track.checkFlag( Track::Flags::Backward ) ? track.states().back() : track.states().front() );
+        *( track.checkType( Track::Types::VeloBackward ) ? track.states().back() : track.states().front() );
     nodes.push_back( new FitNode( closestToBeamLine( refstate ), State::Location::ClosestToBeam ) );
   }
 
   // Sort the nodes in z
-  bool backward = track.checkFlag( LHCb::Track::Flags::Backward );
+  bool backward = track.checkType( LHCb::Track::Types::VeloBackward );
   bool upstream = ( m_upstream.value() && !backward ) || ( !m_upstream.value() && backward );
   if ( upstream ) {
     std::stable_sort( nodes.begin(), nodes.end(), TrackFunctor::decreasingByZ() );
@@ -852,7 +852,7 @@ StatusCode TrackMasterFitter::initializeRefStates( LHCb::Track& track, IGeometry
   const LHCb::State* stateAtT = track.stateAt( LHCb::State::Location::AtT );
   const LHCb::State& refstate =
       stateAtT ? *stateAtT
-               : *( track.checkFlag( Track::Flags::Backward ) ? track.states().front() : track.states().back() );
+               : *( track.checkType( Track::Types::VeloBackward ) ? track.states().front() : track.states().back() );
   for ( auto* state : track.states() ) const_cast<LHCb::State*>( state )->setQOverP( refstate.qOverP() );
 
   // collect the z-positions where we want the states
diff --git a/Tr/TrackKernel/include/TrackKernel/TrackPredicates.h b/Tr/TrackKernel/include/TrackKernel/TrackPredicates.h
index 8e65174285a..1491d760174 100644
--- a/Tr/TrackKernel/include/TrackKernel/TrackPredicates.h
+++ b/Tr/TrackKernel/include/TrackKernel/TrackPredicates.h
@@ -30,7 +30,7 @@ namespace TrackPredicates {
     int m_sign;
     VeloSide( int asign ) : m_sign( asign ) {}
     bool operator()( const LHCb::Track* track ) const {
-      return track->firstState().tx() * m_sign * ( track->checkFlag( LHCb::Track::Flags::Backward ) ? -1 : 1 ) > 0;
+      return track->firstState().tx() * m_sign * ( track->checkType( LHCb::Track::Types::VeloBackward ) ? -1 : 1 ) > 0;
     }
   };
 
diff --git a/Tr/TrackMCTools/src/MeasureIPResolution.cpp b/Tr/TrackMCTools/src/MeasureIPResolution.cpp
index 8ac0cc047de..5fb11069bc0 100644
--- a/Tr/TrackMCTools/src/MeasureIPResolution.cpp
+++ b/Tr/TrackMCTools/src/MeasureIPResolution.cpp
@@ -87,7 +87,7 @@ StatusCode MeasureIPResolution::execute() {
   LinkedTo<LHCb::MCParticle> trackLinker( evtSvc(), msgSvc(), m_containerName );
 
   for ( LHCb::Tracks::const_iterator itT = tracks->begin(); tracks->end() != itT; ++itT ) {
-    if ( ( *itT )->checkFlag( LHCb::Track::Flags::Backward ) ) continue;
+    if ( ( *itT )->checkType( LHCb::Track::Types::VeloBackward ) ) continue;
     LHCb::MCParticle* part = trackLinker.first( *itT );
     /*
     if ( 0 == part ) continue;
diff --git a/Tr/TrackMonitors/src/TrackMonitor.cpp b/Tr/TrackMonitors/src/TrackMonitor.cpp
index dc7ce5bc799..22c347a9a3f 100644
--- a/Tr/TrackMonitors/src/TrackMonitor.cpp
+++ b/Tr/TrackMonitors/src/TrackMonitor.cpp
@@ -281,8 +281,8 @@ private:
   using Type = LHCb::Event::Enum::Track::Type;
   Gaudi::Property<std::vector<Type>> m_typesToMonitor{this,
                                                       "typesToMonitor",
-                                                      {Type::Unknown, Type::Velo, Type::Long, Type::Upstream,
-                                                       Type::Downstream, Type::Ttrack, Type::Muon, Type::Calo,
+                                                      {Type::Unknown, Type::Velo, Type::VeloBackward, Type::Long, Type::Upstream,
+                                                       Type::Downstream, Type::Ttrack, Type::Muon,
                                                        Type::UT}};
 
   // HISTOGRAM DEFINITION
@@ -389,24 +389,16 @@ void TrackMonitor<TFitResult, TNode>::initializeHistogramMap() {
 
   if ( splitByType() ) {
     for ( auto const& type : m_typesToMonitor.value() ) {
-      std::string typo               = toString( type );
-      m_histograms[toString( type )] = std::make_unique<TypeTrackHistogram>( this, typo );
-
-      std::string btypo                           = toString( type ) + "Backward";
-      m_histograms[toString( type ) + "Backward"] = std::make_unique<TypeTrackHistogram>( this, btypo );
-
+      std::string typo                            = toString( type );
+      m_histograms[toString( type )]              = std::make_unique<TypeTrackHistogram>( this, typo );
       for ( auto hittype = 0; hittype < HitType::HitTypeUnknown; ++hittype ) {
         const auto name = HitTypeName[hittype];
         m_named_histograms[toString( type )][name] =
             std::make_unique<TypeNameTrackHistogram>( this, toString( type ), name, HitTypeMaxRes[hittype] );
-        m_named_histograms[toString( type ) + "Backward"][name] =
-            std::make_unique<TypeNameTrackHistogram>( this, btypo, name, HitTypeMaxRes[hittype] );
       }
       for ( auto& [fid, min, max] : range ) {
         m_ranged_histograms[toString( type )][fid] =
             std::make_unique<TypeRangeTrackHistogram>( this, toString( type ), fid, min, max );
-        m_ranged_histograms[toString( type ) + "Backward"][fid] =
-            std::make_unique<TypeRangeTrackHistogram>( this, btypo, fid, min, max );
       }
     }
   }
diff --git a/Tr/TrackMonitors/src/TrackMonitorBase.cpp b/Tr/TrackMonitors/src/TrackMonitorBase.cpp
index e400253d530..03b7f41f4ce 100644
--- a/Tr/TrackMonitors/src/TrackMonitorBase.cpp
+++ b/Tr/TrackMonitors/src/TrackMonitorBase.cpp
@@ -26,7 +26,6 @@ std::string TrackMonitorBase::histoDirName( const LHCb::Track& track ) const {
   std::string type;
   if ( splitByType() ) {
     type = toString( track.type() );
-    if ( track.checkFlag( LHCb::Track::Flags::Backward ) ) type += "Backward";
   } else if ( splitByAlgorithm() ) {
     type = toString( track.history() );
   }
diff --git a/Tr/TrackMonitors/src/TrackMonitorTupleBase.cpp b/Tr/TrackMonitors/src/TrackMonitorTupleBase.cpp
index 27c80fe8e4b..166fcfc2fdc 100644
--- a/Tr/TrackMonitors/src/TrackMonitorTupleBase.cpp
+++ b/Tr/TrackMonitors/src/TrackMonitorTupleBase.cpp
@@ -26,7 +26,6 @@ std::string TrackMonitorTupleBase::histoDirName( const LHCb::Track& track ) cons
   std::string type;
   if ( splitByType() ) {
     type = Gaudi::Utils::toString( track.type() );
-    if ( track.checkFlag( LHCb::Track::Flags::Backward ) ) type += "Backward";
   } else if ( splitByAlgorithm() ) {
     type = Gaudi::Utils::toString( track.history() );
   }
diff --git a/Tr/TrackMonitors/src/TrackVPOverlapMonitor.cpp b/Tr/TrackMonitors/src/TrackVPOverlapMonitor.cpp
index 2484220865a..28614806777 100644
--- a/Tr/TrackMonitors/src/TrackVPOverlapMonitor.cpp
+++ b/Tr/TrackMonitors/src/TrackVPOverlapMonitor.cpp
@@ -62,7 +62,7 @@ namespace LHCb::Tr::Monitor {
       };
 
       for ( const Track* track : tracks ) { // start of track-loop
-        const bool bwd  = track->checkFlag( Track::Flags::Backward );
+        const bool bwd  = track->checkType( Track::Types::VeloBackward );
         const auto type = track->type();
         if ( type != Track::Types::Velo && type != Track::Types::Long && !bwd ) { continue; }
         const bool fitted = track->checkFitStatus( Track::FitStatus::Fitted );
diff --git a/Tr/TrackMonitors/src/TrackVertexMonitor.cpp b/Tr/TrackMonitors/src/TrackVertexMonitor.cpp
index f626e4747db..b1eed888f43 100644
--- a/Tr/TrackMonitors/src/TrackVertexMonitor.cpp
+++ b/Tr/TrackMonitors/src/TrackVertexMonitor.cpp
@@ -237,6 +237,10 @@ namespace {
     return [=]( const LHCb::Track* track ) { return track->type() == atype; };
   };
 
+  auto TrackTypeAntiPredicate = []( LHCb::Track::Types atype ) {
+    return [=]( const LHCb::Track* track ) { return track->type() != atype; };
+  };
+
   auto TrackFlagPredicate = []( LHCb::Track::Flags flag, bool positive ) {
     return [=]( const LHCb::Track* track ) {
       auto f = track->checkFlag( flag );
@@ -274,8 +278,8 @@ namespace {
 void TrackVertexMonitor::operator()( LHCb::RecVertex::Range const& pvcontainer, LHCb::Track::Range const& alltracks,
                                      DetectorElement const& lhcb ) const {
   const auto isLong     = TrackTypePredicate( LHCb::Track::Types::Long );
-  const auto isBackward = TrackFlagPredicate( LHCb::Track::Flags::Backward, true );
-  const auto isForward  = TrackFlagPredicate( LHCb::Track::Flags::Backward, false );
+  const auto isBackward = TrackTypePredicate( LHCb::Track::Types::VeloBackward );
+  const auto isForward  = TrackTypeAntiPredicate( LHCb::Track::Types::VeloBackward );;
 
   // lists needed
   // - primary vertices
diff --git a/Tr/TrackMonitors/src/VPTrackMonitor.cpp b/Tr/TrackMonitors/src/VPTrackMonitor.cpp
index 0dcb8c4e6c7..c3c86141f7a 100644
--- a/Tr/TrackMonitors/src/VPTrackMonitor.cpp
+++ b/Tr/TrackMonitors/src/VPTrackMonitor.cpp
@@ -261,7 +261,7 @@ namespace LHCb::Tr::Monitor {
 
       // start of track-loop
       for ( const LHCb::Track* track : tracks ) {
-        const bool bwd  = track->checkFlag( LHCb::Track::Flags::Backward );
+        const bool bwd  = track->checkType( LHCb::Track::Types::VeloBackward );
         const auto type = track->type();
 
         if constexpr ( outmode == OutputMode::Histograms ) {
diff --git a/Tr/TrackTools/src/LongTrackReferenceCreator.cpp b/Tr/TrackTools/src/LongTrackReferenceCreator.cpp
index 54700503a97..13eb8526615 100644
--- a/Tr/TrackTools/src/LongTrackReferenceCreator.cpp
+++ b/Tr/TrackTools/src/LongTrackReferenceCreator.cpp
@@ -83,7 +83,7 @@ StatusCode LongTrackReferenceCreator::execute( LHCb::Track& track ) const {
     const LHCb::State* stateAtT = track.stateAt( LHCb::State::Location::AtT );
     const LHCb::State& refstate =
         stateAtT ? *stateAtT
-                 : *( track.checkFlag( Track::Flags::Backward ) ? track.states().front() : track.states().back() );
+                 : *( track.checkType( Track::Types::VeloBackward ) ? track.states().front() : track.states().back() );
     for ( auto& s : track.states() ) s->setQOverP( refstate.qOverP() );
 
     // collect the z-positions where we want the states
diff --git a/Tr/TrackTools/src/TrackMaterialParametrizer.cpp b/Tr/TrackTools/src/TrackMaterialParametrizer.cpp
new file mode 100644
index 00000000000..e67e1c1f632
--- /dev/null
+++ b/Tr/TrackTools/src/TrackMaterialParametrizer.cpp
@@ -0,0 +1,391 @@
+/*****************************************************************************\
+* (c) Copyright 2000-2019 CERN for the benefit of the LHCb Collaboration      *
+*                                                                             *
+* This software is distributed under the terms of the GNU General Public      *
+* Licence version 3 (GPL Version 3), copied verbatim in the file "COPYING".   *
+*                                                                             *
+* In applying this licence, CERN does not waive the privileges and immunities *
+* granted to it by virtue of its status as an Intergovernmental Organization  *
+* or submit itself to any jurisdiction.                                       *
+\*****************************************************************************/
+// Include files
+
+// from Gaudi
+#include "GaudiAlg/GaudiTupleAlg.h"
+#include "GaudiKernel/ToolHandle.h"
+
+#include "Event/FitNode.h"
+#include "Event/KalmanFitResult.h"
+#include "Event/Measurement.h"
+#include "Event/StateParameters.h"
+#include "TrackInterfaces/IMaterialLocator.h"
+#include "TrackInterfaces/ITrackExtrapolator.h"
+#include "TrackKernel/CubicStateInterpolationTraj.h"
+#include "TrackKernel/TrackTraj.h"
+
+#include "DetDesc/Material.h"
+
+// from Event/LinkerEvent
+#include "Linker/LinkedFrom.h"
+
+// from Event/TrackEvent
+#include "Event/Track.h"
+
+// from Event/MCEvent
+#include "Event/MCHit.h"
+#include "Event/MCParticle.h"
+
+using namespace LHCb::Event::v1;
+
+class TrackMaterialParametrizer : public GaudiTupleAlg {
+
+public:
+  /** Standard construtor */
+  using GaudiTupleAlg::GaudiTupleAlg;
+
+  /** Algorithm execute */
+  StatusCode execute() override;
+
+  /** Algorithm initialize */
+  StatusCode initialize() override;
+
+  /** Algorithm initialize */
+  StatusCode finalize() override;
+
+private:
+  Gaudi::Property<std::string>   m_tracksInContainer{this, "TracksInContainer",
+                                                   LHCb::TrackLocation::Default}; ///< Input Tracks container location
+  Gaudi::Property<bool>          m_printIntersect{this, "PrintIntersections", false };
+  ToolHandle<ITrackExtrapolator> m_extrapolator    = {"TrackMasterExtrapolator"};
+  ToolHandle<IMaterialLocator>   m_materiallocator = {"DetailedMaterialLocator"};
+};
+
+DECLARE_COMPONENT( TrackMaterialParametrizer )
+
+StatusCode TrackMaterialParametrizer::initialize() {
+  StatusCode sc = GaudiTupleAlg::initialize();
+  if ( sc.isSuccess() ) sc = m_extrapolator.retrieve();
+  if ( sc.isSuccess() ) sc = m_materiallocator.retrieve();
+  setHistoTopDir( "Track/" );
+  return sc;
+}
+
+StatusCode TrackMaterialParametrizer::finalize() {
+  m_extrapolator.release().ignore();
+  m_materiallocator.release().ignore();
+  return GaudiTupleAlg::finalize();
+}
+
+//=============================================================================
+// Main execution
+//=============================================================================
+namespace {
+  enum NodeType {
+    VPHit,
+    UTHit,
+    FTHit,
+    ClosestToBeam,
+    EndVelo,
+    BegRich1,
+    EndRich1,
+    AtT,
+    BegRich2,
+    EndRich2,
+    MuonHit,
+    RefNode,
+    HitNode,
+    NTypes
+  };
+
+  std::string nodeTypeToString( NodeType node ) {
+    switch ( node ) {
+    case VPHit:
+      return "VPHit";
+      break;
+    case UTHit:
+      return "UTHit";
+      break;
+    case FTHit:
+      return "FTHit";
+      break;
+    case MuonHit:
+      return "MuonHit";
+      break;
+    case ClosestToBeam:
+      return "ClosestToBeam";
+      break;
+    case EndVelo:
+      return "EndVelo";
+      break;
+    case BegRich1:
+      return "BegRich1";
+      break;
+    case EndRich1:
+      return "EndRich1";
+      break;
+    case BegRich2:
+      return "BegRich2";
+      break;
+    case EndRich2:
+      return "EndRich2";
+      break;
+    case AtT:
+      return "AtT";
+      break;
+    case RefNode:
+      return "RefNode";
+    case HitNode:
+      return "HitNode";
+    case NTypes:
+      return "Unknown";
+    }
+    return "Unknown";
+  }
+
+  NodeType nodetype( const LHCb::FitNode& node ) {
+    NodeType rc = NTypes;
+    if ( node.hasMeasurement() ) {
+      // Check measurement type compatible with 2D measurements
+      rc = node.measurement().visit(
+          []( LHCb::Measurement::FT const& ) { return FTHit; }, []( LHCb::Measurement::VP const& ) { return VPHit; },
+          []( LHCb::Measurement::VP2D const& ) { return VPHit; },
+          []( LHCb::Measurement::UT const& ) { return UTHit; },
+          []( LHCb::Measurement::Muon const& ) { return MuonHit; },
+          [&]( ... ) {
+            std::cout << "Unknown node type for measurement: " << node.measurement().type() << std::endl;
+            return HitNode;
+          } );
+    } else {
+      switch ( node.state().location() ) {
+      case LHCb::State::ClosestToBeam:
+        rc = ClosestToBeam;
+        break;
+      case LHCb::State::EndVelo:
+        rc = EndVelo;
+        break;
+      case LHCb::State::BegRich1:
+        rc = BegRich1;
+        break;
+      case LHCb::State::EndRich1:
+        rc = EndRich1;
+        break;
+      case LHCb::State::BegRich2:
+        rc = BegRich2;
+        break;
+      case LHCb::State::EndRich2:
+        rc = EndRich2;
+        break;
+      case LHCb::State::AtT:
+        rc = AtT;
+        break;
+      default:
+        rc = RefNode;
+        std::cout << "Unknown reference node type: " << node.state().location() << std::endl;
+      }
+    }
+    return rc;
+  }
+} // namespace
+
+StatusCode TrackMaterialParametrizer::execute() {
+  // Get the Tracks
+  Track::Range tracks = get<Track::Range>( m_tracksInContainer );
+
+  // Loop over the nodes and fill some histograms
+  for ( const auto& trk : tracks ) {
+    auto fitresult = dynamic_cast<const LHCb::KalmanFitResult*>( trk->fitResult() );
+    if ( !fitresult || fitresult->nodes().empty() ) continue;
+    LHCb::TrackTraj tracktraj( {fitresult->nodes().data(), fitresult->nodes().size()} );
+    for ( const auto& is : fitresult->intersections() ) {
+      const auto radthickness = std::abs( is.z2 - is.z1 ) / is.material->radiationLength();
+      // Print intersections
+      if ( m_printIntersect.value() &&
+          std::min( is.z1, is.z2 ) < StateParameters::ZBegRich1 && radthickness > 0.01
+          // && is.material->name() != std::string("Air")
+          // && std::max( is.z1,is.z2 ) > StateParameters::ZEndVelo
+          ) {
+        auto state = tracktraj.stateVector( 0.5 * ( is.z1 + is.z2 ) );
+        std::cout << "intersect: "
+                  << "z1= " << std::setprecision( 1 ) << std::fixed << is.z1 << "; z2= " << is.z2
+                  << "; dz= " << std::abs( is.z2 - is.z1 ) << "; (x,y)_mid=(" << state.x() << "," << state.y() << ")"
+                  << "; Z= " << std::setw( 4 ) << is.material->Z() << "; name= " << std::setw( 10 )
+                  << is.material->name() << "; radthickness= " << std::scientific << radthickness << std::endl;
+      }
+      // Map intersections with aluminium (RF foil)
+      if ( is.material->Z() == 13 ) {
+        // find out at which x,y position this is?
+        auto state = tracktraj.stateVector( 0.5 * ( is.z1 + is.z2 ) );
+        profile2D( state.x(), state.y(), std::abs( is.z2 - is.z1 ), "aluthicknessvsxy", -50, 50, -50, 50, 100, 100 );
+        profile2D( state.y() + state.x(), state.y() - state.x(), std::abs( is.z2 - is.z1 ), "aluthicknessvsxyrotated",
+                  -50, 50, -50, 50, 100, 100 );
+      }
+    }
+    // let's loop over the nodes
+    for ( const auto& node : fitresult->nodes() ) {
+      // Get the noise matrix. This is the noise between this node and the previous node. it is added to prediction
+      // after propagation:
+      //  C_{k,k-1} = F_k C_{k-1} F_k + Qk
+      const auto& Q = node->noiseMatrix();
+
+      // Get the reference state.
+      const auto& state = node->refVector();
+
+      // Get the scattering momentum.
+      const auto pscatter = fitresult->pScatter();
+
+      // let's complete the correction for a thin scatterer, then use
+      // that to take the known effects out of the noise.
+      const auto   tx      = state.tx();
+      const auto   ty      = state.ty();
+      const auto   tx2     = tx * tx;
+      const auto   ty2     = ty * ty;
+      const auto   n2      = 1 + tx2 + ty2;
+      const auto   n       = std::sqrt( n2 );
+      const auto   invp    = 1 / pscatter;
+      const auto   normCms = n * n2 * invp * invp;
+      const double covtxtx = ( 1 + tx2 ) * normCms;
+      const double covtyty = ( 1 + ty2 ) * normCms;
+      const double covtxty = tx * ty * normCms;
+
+      const auto prevnode = node->prevNode( LHCb::FitNode::Forward );
+      // std::cout << "Node: " << node->z() << " " << nodetype( *node ) << " " << node->state().location() << std::endl;
+      // std::cout << "Prev node: " << " " << node->z() << " " << nodetype( *node ) << std::endl ;
+
+      const double xmax  = 4;
+      const int    nbins = 200;
+      // Special histograms for all VPHit to VPHit transitions
+      // Later we divide VPHit-VPHit transitions based on whether they pass through RF foil
+      if ( prevnode && nodetype( *node ) == VPHit && nodetype( *prevnode ) == VPHit &&
+           std::abs( prevnode->z() - node->z() ) > 1 ) {
+        plot1D( std::sqrt( Q( 2, 2 ) / covtxtx ), "velostxnorm", 0, xmax, nbins );
+        plot1D( Q( 3, 2 ) / covtxty, "velostxynorm", 0, xmax, nbins );
+        plot1D( std::sqrt( Q( 3, 3 ) / covtyty ), "velostynorm", 0, xmax, nbins );
+        profile2D( state.x(), state.y(), std::sqrt( Q( 2, 2 ) / covtxtx ), "velostxnormvsxy", -50, 50, -50, 50, 100,
+                   100 );
+      // Special histograms for VPHit to ClosestToBeam transitions
+      } else if ( prevnode && nodetype( *prevnode ) == VPHit && nodetype( *node ) == ClosestToBeam ) {
+        plot1D( std::sqrt( Q( 2, 2 ) / covtxtx ), "velostxnormBL", 0, xmax, nbins );
+        plot1D( Q( 3, 2 ) / covtxty, "velostxynormBL", 0, xmax, nbins );
+        plot1D( std::sqrt( Q( 3, 3 ) / covtyty ), "velostynormBL", 0, xmax, nbins );
+        profile2D( state.x(), state.y(), std::sqrt( Q( 2, 2 ) / covtxtx ), "velostxnormvsxyBL", -50, 50, -50, 50, 100,
+                   100 );
+        // we also make an alternative norm: assume that this is a
+        // thick scatterer and divide by z. perhaps we better treat
+        // the RF foil as a thick one, but we may also have to treat
+        // it as a fixed diameter cylinder. (some profile plots
+        // would help)
+        const double dz = prevnode->z() - node->z();
+        plot1D( std::sqrt( Q( 2, 2 ) / covtxtx / dz ), "velostxLnormBL", 0, 1, nbins );
+        plot1D( Q( 3, 2 ) / covtxty / dz, "velostxyLnormBL", 0, 1, nbins );
+        plot1D( std::sqrt( Q( 3, 3 ) / covtyty / dz ), "velostyLnormBL", 0, 1, nbins );
+      }
+
+      // Skip node pairs with small z position difference.
+      // Note that with 1D Velo measurements, we have two separate nodes at the same z and there's no material noise between those.
+      if ( prevnode && std::abs( node->z() - prevnode->z() ) > 0.5 && covtxtx > 0 ) {
+        bool infoil = false;
+        if ( nodetype( *node ) == VPHit && nodetype( *prevnode ) == VPHit ) {
+          // Check whether the Velo node is already inside rf foil.
+          // Remember that the previous node is more downstream
+          // as we are now parametrizing for fit in upstream direction.
+          const auto x      = state.x();
+          const auto y      = state.y();
+          const auto xprime = y + x;
+          const auto yprime = y - x;
+          infoil = ( yprime > -15 && xprime >= 0 && xprime < 15 ) || ( yprime < 15 && xprime > -15 && xprime <= 0 );
+        }
+        // Prepare folder names for all transitions. For VPHit-VPHit transition we add Foil suffix if the node is within RF foil.
+        // This way we divide VPHit to VPHit transitions in two categories.
+        const std::string foilfix = infoil ? "Foil" : "";
+        const std::string prefix =
+            nodeTypeToString( nodetype( *prevnode ) ) + nodeTypeToString( nodetype( *node ) ) + foilfix + "/";
+
+        // std::cout << node->state().location() << " "
+        // 	  << node->z() << " " << nodetype(*prevnode) << " " << nodetype(*node) << " " << prefix << std::endl ;
+        const auto dz   = node->z() - prevnode->z();
+        const auto xmax = 20.;
+        // std::cout << "delta-z: "
+        // 	  << dz << " "
+        // 	  << node->transportMatrix()(2,0) << " "
+        // 	  << node->transportMatrix()(0,2) << std::endl ;
+
+        // Make histograms for scattering parameters
+        const double reldzxx  = std::sqrt( Q( 0, 0 ) / Q( 2, 2 ) ) / std::abs( dz );
+        const double reldzxtx = Q( 2, 0 ) / Q( 2, 2 ) / dz;
+        plot1D( reldzxx, prefix + "reldzxx", "reldzxx", 0, 1, nbins );
+        plot1D( reldzxtx, prefix + "reldzxtx", "reldzxtx", 0, 1, nbins );
+        plot1D( std::sqrt( Q( 2, 2 ) / covtxtx ), prefix + "stxnorm", "stxnorm", 0., xmax, nbins );
+
+        // Make histograms for other interesting quantities that tell something
+        // about material and scattering
+        plot1D( Q( 3, 2 ) / covtxty, prefix + "stxynorm", "stxynorm", 0., xmax, nbins );
+        plot1D( std::sqrt( Q( 3, 3 ) / covtyty ), prefix + "stynorm", "stynorm", 0., xmax, nbins );
+        plot1D( std::sqrt( Q( 0, 0 ) / Q( 2, 2 ) ), prefix + "effectivedz", "effectivedz", 0, 400, nbins );
+        plot1D( Q( 2, 0 ) * Q( 2, 0 ) / ( Q( 2, 2 ) * Q( 0, 0 ) ), prefix + "thicknessy", "thicknessy", 0, 1, nbins );
+
+        const float zav     = 0.5 * ( node->z() + prevnode->z() );
+        const float thexmax = std::max( 0.3 * zav, 50. );
+
+        profile2D( state.x(), state.y(), std::sqrt( Q( 2, 2 ) / covtxtx ), prefix + "stxnormvsxy", "stxnormvsxy",
+                   -thexmax, thexmax, -thexmax, thexmax, 100, 100 );
+        profile2D( tx, ty, std::sqrt( Q( 2, 2 ) / covtxtx ), prefix + "stxnormvstxtynarrow", "stxnormvstxty", -0.05,
+                   0.05, -0.05, 0.05, 100, 100 );
+        profile2D( tx, ty, std::sqrt( Q( 2, 2 ) / covtxtx ), prefix + "stxnormvstxty", "stxnormvstxty", -0.4, 0.4, -0.4,
+                   0.4, 100, 100 );
+
+        const double eta = -std::log( std::tan( 0.5 * std::atan( std::sqrt( tx2 + ty2 ) ) ) );
+        // const double eta = state.momentum().PseudoRapidity() ;
+        const double relnoise2 = Q( 2, 2 ) / covtxtx;
+        const double relnoise  = std::sqrt( relnoise2 );
+        const double dE        = std::abs( 1 / node->state().qOverP() ) - std::abs( 1 / prevnode->state().qOverP() );
+
+        // Make some more profile plots
+        if ( relnoise < 50.0 ) {
+          const double t = std::sqrt( tx2 + ty2 );
+          profile1D( eta, relnoise, prefix + "stxnormvseta", "stxnormvseta", 1., 7., 100 );
+          profile1D( t, relnoise, prefix + "stxnormvst", "stxnormvst", 0, 0.4 );
+
+          profile1D( t, relnoise2, prefix + "stxnorm2vst", "stxnorm2vst", 0, 0.4, 40 );
+          profile1D( t, reldzxx, prefix + "reldzxxvst", "reldzxxvst", 0, 0.4, 40 );
+          profile1D( t, reldzxtx, prefix + "reldzxtxvst", "reldzxtxvst", 0, 0.4, 40 );
+          profile1D( t, dE / n, prefix + "dEvst", "dEvst", 0, 0.4, 40 );
+
+          const double R1 = std::sqrt( state.x() * state.x() + state.y() * state.y() );
+          profile1D( R1, relnoise, prefix + "stxnormvsR1", "stxnormvsR1", 0., 100., 100 );
+          const auto   prevstate = prevnode->state();
+          const double R2        = std::sqrt( prevstate.x() * prevstate.x() + prevstate.y() * prevstate.y() );
+          profile1D( log( R2 ) / log( 10 ), relnoise, prefix + "stxnormvsR2", "stxnormvsR2", 0., 4., 100 );
+        }
+
+        // also add energy loss (divided by wall thickness)
+        plot1D( dE / n, prefix + "normdE", "normdE", 0., 100., 10 * nbins );
+
+        // Wouter's notes:
+
+        // we still miss:
+        // - module support/cooling block: very visible between last velo-hit and end-velo
+        // - heavy material close to beam pipe, especially between endvelo and end rich
+        // - there is a very big object in the middle of UT.
+        //   the AtT-EndRich1 step now accounts for this because most tracks that go through UT actually have UT hits.
+        //   We need to find a different solution here.
+
+        // to be added volumes:
+        // * VP->EndVelo: between 30 and 50 mm in R is very much
+        // heavier. should be easy to add. there are basically no tracks
+        // above 50, which really surprises me ... WARNING: we see the R of the most upstream part. that explains.
+        // indeed the material is at LOW angles: we go through the support material of other modules.
+        // * EndVelo->BegRich1: 20<R<45 (but there is basically nothing below 20)
+        // * EndRich1-BegRich1: narrow thing between 25<R<30; probably narrower in angle (4.2<eta<4.5)
+        // AtT-UTHit: heavy for R<50 (eta>5)
+        // surprising: nothing between UT-EndRich1: probably because UT hits are outside beampipe
+        // but: you do see it in AtT->EndRich1 (no UT hits): something
+        // heavy for R<50 (5<eta) note that this is at larger angle
+        // than in Rich1 itself.
+      }
+    }
+  }
+
+  //Tuple theTuple = nTuple( "scattertuple", "", CLID_ColumnWiseTuple );
+  //theTuple->write().ignore();
+  return StatusCode::SUCCESS;
+}
diff --git a/Tr/TrackTools/src/TrackSelectorBase.h b/Tr/TrackTools/src/TrackSelectorBase.h
index 57a82a80e39..35367541994 100644
--- a/Tr/TrackTools/src/TrackSelectorBase.h
+++ b/Tr/TrackTools/src/TrackSelectorBase.h
@@ -74,7 +74,7 @@ protected:
   // Check track type
   bool checkTrackType( const LHCb::Track& aTrack ) const {
     if ( m_selTypes.value()( aTrack.type() ) ) {
-      return m_onlyBackwardTracks ? aTrack.checkFlag( LHCb::Track::Flags::Backward ) : true;
+      return m_onlyBackwardTracks ? aTrack.checkType( LHCb::Track::Types::VeloBackward ) : true;
     }
     if ( msgLevel( MSG::VERBOSE ) ) verbose() << " -> Track type " << aTrack.type() << " is rejected" << endmsg;
     return false;
diff --git a/Tr/TrackTools/src/UpgradeGhostId.cpp b/Tr/TrackTools/src/UpgradeGhostId.cpp
index 4e75a6fed6d..e49a9c49cc4 100644
--- a/Tr/TrackTools/src/UpgradeGhostId.cpp
+++ b/Tr/TrackTools/src/UpgradeGhostId.cpp
@@ -160,6 +160,7 @@ StatusCode UpgradeGhostId::initialize() {
     m_flatters.clear();
     m_flatters.resize( static_cast<int>( LHCb::Track::Types::Last ) );
     m_flatters[static_cast<int>( LHCb::Track::Types::Velo )]       = Update_VeloTable();
+    m_flatters[static_cast<int>( LHCb::Track::Types::VeloBackward )]       = Update_VeloTable();
     m_flatters[static_cast<int>( LHCb::Track::Types::Upstream )]   = Update_UpstreamTable();
     m_flatters[static_cast<int>( LHCb::Track::Types::Downstream )] = Update_DownstreamTable();
     m_flatters[static_cast<int>( LHCb::Track::Types::Long )]       = Update_LongTable();
@@ -232,7 +233,7 @@ StatusCode UpgradeGhostId::execute( LHCb::Track& aTrack ) const {
   if ( LHCb::Track::Types::Long != aTrack.type() && LHCb::Track::Types::Downstream != aTrack.type() ) {
     variables.push_back( aTrack.nDoF() );
   }
-  if ( LHCb::Track::Types::Velo != aTrack.type() ) { variables.push_back( aTrack.pt() ); }
+  if ( (LHCb::Track::Types::Velo != aTrack.type()) && (LHCb::Track::Types::VeloBackward != aTrack.type())) { variables.push_back( aTrack.pt() ); }
   variables.push_back( aTrack.pseudoRapidity() );
 
   float netresponse = std::numeric_limits<float>::max();
@@ -245,6 +246,7 @@ StatusCode UpgradeGhostId::execute( LHCb::Track& aTrack ) const {
     netresponse = m_downstreamClassifier.GetMvaValue( LHCb::span{variables}.first<downstreamVars.size()>() );
     break;
   case LHCb::Track::Types::Velo:
+  case LHCb::Track::Types::VeloBackward:
     netresponse = m_veloClassifier.GetMvaValue( LHCb::span{variables}.first<veloVars.size()>() );
     break;
   case LHCb::Track::Types::Upstream:
@@ -271,6 +273,7 @@ StatusCode UpgradeGhostId::execute( LHCb::Track& aTrack ) const {
 std::vector<std::string_view> UpgradeGhostId::variableNames( LHCb::Track::Types type ) const {
   switch ( type ) {
   case LHCb::Track::Types::Velo:
+  case LHCb::Track::Types::VeloBackward:
     return std::vector<std::string_view>( veloVars.begin(), veloVars.end() );
   case LHCb::Track::Types::Long:
     return std::vector<std::string_view>( longVars.begin(), longVars.end() );
diff --git a/Tr/TrackTools/src/VeloMuonBuilder.cpp b/Tr/TrackTools/src/VeloMuonBuilder.cpp
index d47515d016b..04f16fa0702 100644
--- a/Tr/TrackTools/src/VeloMuonBuilder.cpp
+++ b/Tr/TrackTools/src/VeloMuonBuilder.cpp
@@ -89,7 +89,7 @@ LHCb::Tracks VeloMuonBuilder::operator()( const LHCb::Tracks& muontracks, const
     // loop over velos - chose the one with the closest distance at the extrapolated position in the magnet
     for ( auto& velotrack : velotracks ) {
 
-      if ( velotrack->checkFlag( LHCb::Track::Flags::Backward ) ) continue;
+      if ( velotrack->checkType( LHCb::Track::Types::VeloBackward ) ) continue;
 
       // extrapolate the velo track to the position in the magnet
       Gaudi::XYZPoint velopunktx, velopunkty;
diff --git a/Tr/TrackUtils/src/TrackBestTrackCreator.cpp b/Tr/TrackUtils/src/TrackBestTrackCreator.cpp
index 6725c325390..4c22328e024 100644
--- a/Tr/TrackUtils/src/TrackBestTrackCreator.cpp
+++ b/Tr/TrackUtils/src/TrackBestTrackCreator.cpp
@@ -115,14 +115,13 @@ namespace LHCb {
           m_counters.emplace_back( owner, toString( static_cast<Type>( itype ) ) + "Backward." + tag );
         }
       }
-      CounterType& operator()( bool isBackward, Track::Types type ) {
-        return m_counters[static_cast<int>( type ) + ( isBackward ? static_cast<int>( Track::Types::Last ) : 0 )];
-      }
-
-    private:
-      // the actual counters
-      std::deque<CounterType> m_counters;
-    };
+      // for ( auto itype{0}; itype < ilast; ++itype ) {
+      //   m_counters.emplace_back( owner, toString( static_cast<Type>( itype ) ) + "Backward." + tag );
+      // }
+    }
+    CounterType& operator()( LHCb::Track::Types type ) {
+      return m_counters[static_cast<int>( type )];
+    }
 
   private:
     ToolHandle<ITrackFitter>      m_fitter{this, "Fitter", "TrackMasterFitter"};
@@ -375,7 +374,6 @@ void LHCb::TrackBestTrackCreator::fitAndUpdateCounters( TrackData& td, IGeometry
 
   bool badinput   = false;
   bool fitfailed  = false;
-  bool isBackward = track.checkFlag( Track::Flags::Backward );
 
   if ( m_doNotRefit &&
        ( td.previousStatus() == Track::FitStatus::Fitted || td.previousStatus() == Track::FitStatus::FitFailed ) ) {
@@ -399,16 +397,16 @@ void LHCb::TrackBestTrackCreator::fitAndUpdateCounters( TrackData& td, IGeometry
         // Update counters
         if ( track.nDoF() > 0 ) {
           double chisqProb = track.probChi2();
-          m_chisqProbSumCounters( isBackward, track.type() ) += chisqProb;
-          m_badChisqCounters( isBackward, track.type() ) += bool( chisqProb < 0.01 );
+          m_chisqProbSumCounters( track.type() ) += chisqProb;
+          m_badChisqCounters( track.type() ) += bool( chisqProb < 0.01 );
         }
-        m_flipChargeCounters( isBackward, track.type() ) += bool( td.qOverP() * track.firstState().qOverP() < 0 );
-        m_numOutliersCounters( isBackward, track.type() ) += nMeasurementsRemoved( track );
-        m_ghostProbCounters( isBackward, track.type() ) += track.ghostProbability();
+        m_flipChargeCounters( track.type() ) += bool( td.qOverP() * track.firstState().qOverP() < 0 );
+        m_numOutliersCounters( track.type() ) += nMeasurementsRemoved( track );
+        m_ghostProbCounters( track.type() ) += track.ghostProbability();
       } else {
         track.setFlag( Track::Flags::Invalid, true );
         fitfailed = true;
-        m_fitFailedCounters( isBackward, track.type() ) += int( fitfailed );
+        m_fitFailedCounters( track.type() ) += int( fitfailed );
       }
     }
   }
@@ -478,11 +476,18 @@ bool LHCb::TrackBestTrackCreator::areClones( const TrackData& it, const TrackDat
   case to_index( Track::Types::Upstream, Track::Types::Long ):
   case to_index( Track::Types::Upstream, Track::Types::Upstream ):
     return veloOrClones( it, jt ) && UTClones( it, jt );
-  case to_index( Track::Types::Long, Track::Types::Velo ):
-  case to_index( Track::Types::Velo, Track::Types::Long ):
-  case to_index( Track::Types::Upstream, Track::Types::Velo ):
-  case to_index( Track::Types::Velo, Track::Types::Upstream ):
-  case to_index( Track::Types::Velo, Track::Types::Velo ):
+  case to_index( LHCb::Track::Types::Long, LHCb::Track::Types::Velo ):
+  case to_index( LHCb::Track::Types::Velo, LHCb::Track::Types::Long ):
+  case to_index( LHCb::Track::Types::Upstream, LHCb::Track::Types::Velo ):
+  case to_index( LHCb::Track::Types::Velo, LHCb::Track::Types::Upstream ):
+  case to_index( LHCb::Track::Types::Velo, LHCb::Track::Types::Velo ):
+  case to_index( LHCb::Track::Types::Velo, LHCb::Track::Types::VeloBackward ):
+  case to_index( LHCb::Track::Types::VeloBackward, LHCb::Track::Types::Velo ):
+  case to_index( LHCb::Track::Types::Long, LHCb::Track::Types::VeloBackward ):
+  case to_index( LHCb::Track::Types::VeloBackward, LHCb::Track::Types::Long ):
+  case to_index( LHCb::Track::Types::Upstream, LHCb::Track::Types::VeloBackward ):
+  case to_index( LHCb::Track::Types::VeloBackward, LHCb::Track::Types::Upstream ):
+  case to_index( LHCb::Track::Types::VeloBackward, LHCb::Track::Types::VeloBackward ):
     return veloOrClones( it, jt );
   case to_index( Track::Types::Long, Track::Types::Ttrack ):
   case to_index( Track::Types::Ttrack, Track::Types::Long ):
@@ -490,14 +495,18 @@ bool LHCb::TrackBestTrackCreator::areClones( const TrackData& it, const TrackDat
   case to_index( Track::Types::Ttrack, Track::Types::Downstream ):
   case to_index( Track::Types::Ttrack, Track::Types::Ttrack ):
     return TClones( it, jt );
-  case to_index( Track::Types::Ttrack, Track::Types::Upstream ):
-  case to_index( Track::Types::Upstream, Track::Types::Ttrack ):
-  case to_index( Track::Types::Ttrack, Track::Types::Velo ):
-  case to_index( Track::Types::Velo, Track::Types::Ttrack ):
-  case to_index( Track::Types::Downstream, Track::Types::Velo ):
-  case to_index( Track::Types::Velo, Track::Types::Downstream ):
-  case to_index( Track::Types::Downstream, Track::Types::Upstream ):
-  case to_index( Track::Types::Upstream, Track::Types::Downstream ):
+  case to_index( LHCb::Track::Types::Ttrack, LHCb::Track::Types::Upstream ):
+  case to_index( LHCb::Track::Types::Upstream, LHCb::Track::Types::Ttrack ):
+  case to_index( LHCb::Track::Types::Ttrack, LHCb::Track::Types::Velo ):
+  case to_index( LHCb::Track::Types::Velo, LHCb::Track::Types::Ttrack ):
+  case to_index( LHCb::Track::Types::Downstream, LHCb::Track::Types::Velo ):
+  case to_index( LHCb::Track::Types::Velo, LHCb::Track::Types::Downstream ):
+  case to_index( LHCb::Track::Types::Ttrack, LHCb::Track::Types::VeloBackward ):
+  case to_index( LHCb::Track::Types::VeloBackward, LHCb::Track::Types::Ttrack ):
+  case to_index( LHCb::Track::Types::Downstream, LHCb::Track::Types::VeloBackward ):
+  case to_index( LHCb::Track::Types::VeloBackward, LHCb::Track::Types::Downstream ):
+  case to_index( LHCb::Track::Types::Downstream, LHCb::Track::Types::Upstream ):
+  case to_index( LHCb::Track::Types::Upstream, LHCb::Track::Types::Downstream ):
     break;
   default:
     error() << "Don't know how to handle combi: " << itrack.type() << " " << jtrack.type() << endmsg;
diff --git a/Tr/TrackUtils/src/TracksVPConverter.cpp b/Tr/TrackUtils/src/TracksVPConverter.cpp
index e1fe97fb830..fde57672a62 100644
--- a/Tr/TrackUtils/src/TracksVPConverter.cpp
+++ b/Tr/TrackUtils/src/TracksVPConverter.cpp
@@ -32,7 +32,6 @@ namespace {
   using F     = dType::float_v;
 
   void SetFlagsAndPt( LHCb::Event::v2::Track& outtrack, float ptVelo ) {
-    outtrack.setType( LHCb::Event::v2::Track::Type::Velo ); // CHECKME!!!
     outtrack.setHistory( LHCb::Event::v2::Track::History::PrPixel );
     outtrack.setPatRecStatus( LHCb::Event::v2::Track::PatRecStatus::PatRecIDs );
     const int firstRow = outtrack.lhcbIDs()[0].channelID();
@@ -102,8 +101,7 @@ public:
       auto state_endvelo = getState( track, 1 );
       state_endvelo.setLocation( LHCb::State::Location::EndVelo );
       newTrack.addToStates( state_endvelo );
-
-      newTrack.setFlag( Track::Flag::Backward, false ); // always
+      newTrack.setType( LHCb::Event::v2::Track::Type::Velo ); 
       SetFlagsAndPt( newTrack, m_ptVelo );
     }
 
@@ -142,8 +140,7 @@ public:
       auto state_endvelo = getState( fwdtrack, 1 );
       state_endvelo.setLocation( LHCb::State::Location::EndVelo );
       newTrack.addToStates( state_endvelo );
-
-      newTrack.setFlag( Track::Flag::Backward, false );
+      newTrack.setType( LHCb::Event::v2::Track::Type::Velo ); 
       SetFlagsAndPt( newTrack, m_ptVelo );
     }
 
@@ -154,8 +151,7 @@ public:
       auto state_beam = getState( bwdtrack, 0 );
       state_beam.setLocation( LHCb::State::Location::ClosestToBeam );
       newTrack.addToStates( state_beam );
-
-      newTrack.setFlag( Track::Flag::Backward, true );
+      newTrack.setType( LHCb::Event::v2::Track::Type::VeloBackward ); 
       SetFlagsAndPt( newTrack, m_ptVelo );
     }
 
diff --git a/Tr/TrackUtils/src/VertexListRefiner.cpp b/Tr/TrackUtils/src/VertexListRefiner.cpp
index 382dcbc2d46..b8b849f1599 100644
--- a/Tr/TrackUtils/src/VertexListRefiner.cpp
+++ b/Tr/TrackUtils/src/VertexListRefiner.cpp
@@ -60,7 +60,7 @@ public:
 
                     if ( accept && ( m_minNumBackwardTracks > 0 || m_minNumForwardTracks > 0 ) ) {
                       int numback    = std::count_if( tracks.begin(), tracks.end(),
-                                                   TrackPredicates::Flag( LHCb::Track::Flags::Backward ) );
+                                                   TrackPredicates::Type( LHCb::Track::Types::VeloBackward ) );
                       int numforward = tracks.size() - numback;
                       accept         = numback >= m_minNumBackwardTracks && numforward >= m_minNumForwardTracks;
                     }
-- 
GitLab


From de9c75bb99e930bb94c1c91c771482643f039841 Mon Sep 17 00:00:00 2001
From: Andrii Usachov <andrii.usachov@cern.ch>
Date: Sun, 18 Sep 2022 20:08:06 +0200
Subject: [PATCH 02/15] add TrBackward functor

---
 Rec/LoKiTrack/python/LoKiTrack/decorators.py | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/Rec/LoKiTrack/python/LoKiTrack/decorators.py b/Rec/LoKiTrack/python/LoKiTrack/decorators.py
index 10e8b05fd54..62612158fba 100644
--- a/Rec/LoKiTrack/python/LoKiTrack/decorators.py
+++ b/Rec/LoKiTrack/python/LoKiTrack/decorators.py
@@ -130,6 +130,8 @@ _decorated = _decorate()  ## ATTENTION
 
 ## @see LoKi::Cuts::TrDOWNSTREAM
 TrDOWNSTREAM = equal_to(TrTYPE, TrackEnums.Type.Downstream)
+## @see LoKi::Cuts::TrBACKWARD
+TrBACKWARD = equal_to(TrTYPE, TrackEnums.Type.VeloBackward)
 ## @see LoKi::Cuts::TrLONG
 TrLONG = equal_to(TrTYPE, TrackEnums.Type.Long)
 ## @see LoKi::Cuts::TrMUON
-- 
GitLab


From f583bf22703b1fd296989c6340c6d9182316bb2b Mon Sep 17 00:00:00 2001
From: Andrii Usachov <andrii.usachov@cern.ch>
Date: Sun, 18 Sep 2022 20:10:32 +0200
Subject: [PATCH 03/15] fix assert in Kf tool

---
 Tr/PrKalmanFilter/src/KalmanFilterTool.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/Tr/PrKalmanFilter/src/KalmanFilterTool.cpp b/Tr/PrKalmanFilter/src/KalmanFilterTool.cpp
index d523b7e7129..34968da7282 100644
--- a/Tr/PrKalmanFilter/src/KalmanFilterTool.cpp
+++ b/Tr/PrKalmanFilter/src/KalmanFilterTool.cpp
@@ -59,7 +59,7 @@ namespace LHCb::Pr {
 
       if constexpr ( has_hit_type<HitType::VP, Types...> && !has_hit_type<HitType::FT, Types...> &&
                      !has_hit_type<HitType::UT, Types...> ) {
-        assert( track.checkType( TrackV1::Types::Velo ) || track.checkType( TrackV1::Types::Backward ) );
+        assert( track.checkType( TrackV1::Types::Velo ) || track.checkType( TrackV1::Types::VeloBackward ) );
       } else if constexpr ( !has_hit_type<HitType::VP, Types...> && has_hit_type<HitType::FT, Types...> &&
                             has_hit_type<HitType::UT, Types...> ) {
         assert( track.checkType( TrackV1::Types::Downstream ) );
-- 
GitLab


From 104e7c1d7cb0be20aed25f0e237d434bf64f5d2d Mon Sep 17 00:00:00 2001
From: Andrii Usachov <andrii.usachov@cern.ch>
Date: Sun, 18 Sep 2022 20:14:57 +0200
Subject: [PATCH 04/15] cleap up

---
 Tr/TrackUtils/src/TrackBestTrackCreator.cpp | 3 ---
 1 file changed, 3 deletions(-)

diff --git a/Tr/TrackUtils/src/TrackBestTrackCreator.cpp b/Tr/TrackUtils/src/TrackBestTrackCreator.cpp
index 4c22328e024..dea901f81c3 100644
--- a/Tr/TrackUtils/src/TrackBestTrackCreator.cpp
+++ b/Tr/TrackUtils/src/TrackBestTrackCreator.cpp
@@ -115,9 +115,6 @@ namespace LHCb {
           m_counters.emplace_back( owner, toString( static_cast<Type>( itype ) ) + "Backward." + tag );
         }
       }
-      // for ( auto itype{0}; itype < ilast; ++itype ) {
-      //   m_counters.emplace_back( owner, toString( static_cast<Type>( itype ) ) + "Backward." + tag );
-      // }
     }
     CounterType& operator()( LHCb::Track::Types type ) {
       return m_counters[static_cast<int>( type )];
-- 
GitLab


From 967734aabb5272ffc283e478879a77a164fb3700 Mon Sep 17 00:00:00 2001
From: Andrii Usachov <andrii.usachov@cern.ch>
Date: Mon, 19 Sep 2022 16:52:02 +0200
Subject: [PATCH 05/15] replace checkType by isBackward() function

---
 Rec/LoKiTrack/include/LoKi/TrackCuts.h               |  4 +---
 Rec/LoKiTrack/python/LoKiTrack/decorators.py         |  2 --
 Rec/LoKiTrack/python/LoKiTrack/functions.py          |  2 ++
 Rec/RecAlgs/src/RecSummaryAlg.cpp                    |  2 +-
 Tf/FastPV/src/FastPVMonitor.cpp                      |  4 ++--
 Tr/PatPV/src/LSAdaptPV3DFitter.cpp                   |  2 +-
 Tr/PatPV/src/LSAdaptPVFitter.cpp                     |  2 +-
 Tr/PrKalmanFilter/include/PrKalmanFilter/KF.h        |  2 +-
 Tr/PrKalmanFilter/src/KalmanFilterTool.cpp           |  4 ++--
 Tr/TrackCheckers/src/TrackIPResolutionChecker.cpp    |  2 +-
 Tr/TrackCheckers/src/TrackIPResolutionCheckerNT.cpp  |  2 +-
 Tr/TrackCheckers/src/TrackPVChecker.cpp              |  2 +-
 Tr/TrackCheckers/src/VertexChecker.cpp               |  2 +-
 Tr/TrackExtrapolators/src/TrackStateProvider.cpp     |  2 +-
 Tr/TrackFitter/src/TrackMasterFitter.cpp             | 12 ++++++------
 Tr/TrackKernel/include/TrackKernel/TrackPredicates.h |  2 +-
 Tr/TrackMCTools/src/MeasureIPResolution.cpp          |  2 +-
 Tr/TrackMonitors/src/TrackVPOverlapMonitor.cpp       |  2 +-
 Tr/TrackMonitors/src/TrackVertexMonitor.cpp          | 12 ++++++++----
 Tr/TrackMonitors/src/VPTrackMonitor.cpp              |  2 +-
 Tr/TrackTools/src/LongTrackReferenceCreator.cpp      |  2 +-
 Tr/TrackTools/src/TrackSelectorBase.h                |  2 +-
 Tr/TrackTools/src/UpgradeGhostId.cpp                 |  2 +-
 Tr/TrackTools/src/VeloMuonBuilder.cpp                |  2 +-
 24 files changed, 38 insertions(+), 36 deletions(-)

diff --git a/Rec/LoKiTrack/include/LoKi/TrackCuts.h b/Rec/LoKiTrack/include/LoKi/TrackCuts.h
index 2d7a78e8e8b..815f10ccaab 100644
--- a/Rec/LoKiTrack/include/LoKi/TrackCuts.h
+++ b/Rec/LoKiTrack/include/LoKi/TrackCuts.h
@@ -66,12 +66,10 @@ namespace LoKi {
      *    const bool backward = TrBACKWARD ( track ) ;
      *
      *  @endcode
-     *  @see LoKi::Track::TrTYPE
      *  @author Vanya BELYAEV ibelyaev@physics.syr.edu
      *  @date   2007-06-08
      */
-    inline const auto TrBACKWARD =
-        LoKi::EqualToValue<const LHCb::Track*, double>{TrTYPE, static_cast<int>( LHCb::Track::Types::VeloBackward )};
+    inline const auto TrBACKWARD = LoKi::Track::isBackward{};
     
     // ========================================================================
     /** @var TrCHI2
diff --git a/Rec/LoKiTrack/python/LoKiTrack/decorators.py b/Rec/LoKiTrack/python/LoKiTrack/decorators.py
index 62612158fba..10e8b05fd54 100644
--- a/Rec/LoKiTrack/python/LoKiTrack/decorators.py
+++ b/Rec/LoKiTrack/python/LoKiTrack/decorators.py
@@ -130,8 +130,6 @@ _decorated = _decorate()  ## ATTENTION
 
 ## @see LoKi::Cuts::TrDOWNSTREAM
 TrDOWNSTREAM = equal_to(TrTYPE, TrackEnums.Type.Downstream)
-## @see LoKi::Cuts::TrBACKWARD
-TrBACKWARD = equal_to(TrTYPE, TrackEnums.Type.VeloBackward)
 ## @see LoKi::Cuts::TrLONG
 TrLONG = equal_to(TrTYPE, TrackEnums.Type.Long)
 ## @see LoKi::Cuts::TrMUON
diff --git a/Rec/LoKiTrack/python/LoKiTrack/functions.py b/Rec/LoKiTrack/python/LoKiTrack/functions.py
index 8f28563a4ed..61a194a56f5 100644
--- a/Rec/LoKiTrack/python/LoKiTrack/functions.py
+++ b/Rec/LoKiTrack/python/LoKiTrack/functions.py
@@ -70,6 +70,8 @@ TrTYPE = LoKi.Track.Type()
 
 ## @see @see LoKi::Cuts::TrALL
 TrALL = LoKi.Constant(_T, bool)(True)
+## @see LoKi::Cuts::TrBACKWARD
+TrBACKWARD = LoKi.Track.isVeloBackward()
 ## @see LoKi::Cuts::TrCHI2
 TrCHI2 = LoKi.Track.Chi2()
 ## @see LoKi::Cuts::TrCHI2PDOF
diff --git a/Rec/RecAlgs/src/RecSummaryAlg.cpp b/Rec/RecAlgs/src/RecSummaryAlg.cpp
index 14e92c40282..7654788cb33 100644
--- a/Rec/RecAlgs/src/RecSummaryAlg.cpp
+++ b/Rec/RecAlgs/src/RecSummaryAlg.cpp
@@ -179,7 +179,7 @@ StatusCode RecSummaryAlg::execute() {
         ++nT;
         break;
       case LHCb::Track::Types::Velo:
-        if ( tk->checkType( LHCb::Track::Types::VeloBackward ) ) ++nBack;
+        if ( tk->isVeloBackward() ) ++nBack;
         break;
       default:;
       }
diff --git a/Tf/FastPV/src/FastPVMonitor.cpp b/Tf/FastPV/src/FastPVMonitor.cpp
index 484443a6ee5..9d638b6cd06 100644
--- a/Tf/FastPV/src/FastPVMonitor.cpp
+++ b/Tf/FastPV/src/FastPVMonitor.cpp
@@ -196,7 +196,7 @@ StatusCode FastPVMonitor::execute() {
 
   // Number of tracks with IP between min and max values
   for ( LHCb::Tracks::iterator itT = tracks->begin(); tracks->end() != itT; ++itT ) { // loop over tracks
-    if ( ( *itT )->checkType( LHCb::Track::Types::VeloBackward ) ) continue;              // avoid backward tracks
+    if ( ( *itT )->isVeloBackward() ) continue;              // avoid backward tracks
     Gaudi::XYZPoint  point = ( *itT )->position();                                    // track position (first hit ?)
     Gaudi::XYZVector dir   = ( *itT )->slopes();                                      // track direction
 
@@ -260,7 +260,7 @@ StatusCode FastPVMonitor::execute() {
 #ifdef DEBUG_HISTO
   if ( MCvs ) {
     for ( LHCb::Tracks::iterator itT = tracks->begin(); tracks->end() != itT; ++itT ) // loop over tracks
-    { // if ( (*itT)->checkType( LHCb::Track::Types::VeloBackward ) ) continue;                       // avoid backward
+    { // if ( (*itT)->isVeloBackward() ) continue;                       // avoid backward
       // tracks
       Gaudi::XYZPoint  point = ( *itT )->position(); // track position (first hit ?)
       Gaudi::XYZVector dir   = ( *itT )->slopes();   // track direction
diff --git a/Tr/PatPV/src/LSAdaptPV3DFitter.cpp b/Tr/PatPV/src/LSAdaptPV3DFitter.cpp
index 298291ea143..5fcc2f455e0 100644
--- a/Tr/PatPV/src/LSAdaptPV3DFitter.cpp
+++ b/Tr/PatPV/src/LSAdaptPV3DFitter.cpp
@@ -311,7 +311,7 @@ double LSAdaptPV3DFitter::err2d0( const LHCb::Track* track, const Gaudi::XYZPoin
   double fsin2 = tr2 / ( 1. + tr2 );
   double err2  = ( ex2 + ey2 ) * fcos2;
 
-  bool backward = track->checkType( LHCb::Track::Types::VeloBackward );
+  bool backward = track->isVeloBackward();
 
   double z_seed = seed.z();
   double dz_pv  = z - z_seed;
diff --git a/Tr/PatPV/src/LSAdaptPVFitter.cpp b/Tr/PatPV/src/LSAdaptPVFitter.cpp
index 33a3189b10b..79a3d14fd1d 100644
--- a/Tr/PatPV/src/LSAdaptPVFitter.cpp
+++ b/Tr/PatPV/src/LSAdaptPVFitter.cpp
@@ -234,7 +234,7 @@ StatusCode LSAdaptPVFitter::fit( LHCb::RecVertex& vtx, std::vector<PVTrack*>& pv
 
       if ( ( *itrack )->chi2 < 100. ) {
         const LHCb::Track* lbtrack = ( *itrack )->refTrack;
-        int                back    = lbtrack->checkType( LHCb::Track::Types::VeloBackward );
+        int                back    = lbtrack->isVeloBackward();
         int                velo =
             ( lbtrack->checkType( LHCb::Track::Types::Velo ) || lbtrack->checkType( LHCb::Track::Types::Upstream ) );
         int longtr = lbtrack->checkType( LHCb::Track::Types::Long );
diff --git a/Tr/PrKalmanFilter/include/PrKalmanFilter/KF.h b/Tr/PrKalmanFilter/include/PrKalmanFilter/KF.h
index 3d42795cf65..2c09e535655 100644
--- a/Tr/PrKalmanFilter/include/PrKalmanFilter/KF.h
+++ b/Tr/PrKalmanFilter/include/PrKalmanFilter/KF.h
@@ -1022,7 +1022,7 @@ namespace LHCb::Pr::Tracks::Fit {
         is_ctb_first = ctb_z < first_hit.z();
         if constexpr ( std::is_same_v<TrackProxy, LHCb::Event::v1::Track> ) {
           // no effect for v3::Tracks
-          if ( newtrack.checkType( LHCb::Track::Types::VeloBackward ) ) is_ctb_first = !is_ctb_first;
+          if ( newtrack.isVeloBackward() ) is_ctb_first = !is_ctb_first;
         }
       }
 
diff --git a/Tr/PrKalmanFilter/src/KalmanFilterTool.cpp b/Tr/PrKalmanFilter/src/KalmanFilterTool.cpp
index 34968da7282..360318a4a09 100644
--- a/Tr/PrKalmanFilter/src/KalmanFilterTool.cpp
+++ b/Tr/PrKalmanFilter/src/KalmanFilterTool.cpp
@@ -59,7 +59,7 @@ namespace LHCb::Pr {
 
       if constexpr ( has_hit_type<HitType::VP, Types...> && !has_hit_type<HitType::FT, Types...> &&
                      !has_hit_type<HitType::UT, Types...> ) {
-        assert( track.checkType( TrackV1::Types::Velo ) || track.checkType( TrackV1::Types::VeloBackward ) );
+        assert( track.checkType( TrackV1::Types::Velo ) || track.isVeloBackward() );
       } else if constexpr ( !has_hit_type<HitType::VP, Types...> && has_hit_type<HitType::FT, Types...> &&
                             has_hit_type<HitType::UT, Types...> ) {
         assert( track.checkType( TrackV1::Types::Downstream ) );
@@ -71,7 +71,7 @@ namespace LHCb::Pr {
         assert( track.checkType( TrackV1::Types::Ttrack ) );
       } else if constexpr ( has_hit_type<HitType::VP, Types...> && has_hit_type<HitType::FT, Types...> &&
                             has_hit_type<HitType::UT, Types...> ) {
-        assert( track.checkType( TrackV1::Types::Long ) || track.checkType( TrackV1::Types::Velo ) || track.checkType( TrackV1::Types::VeloBackward ) || track.checkType( TrackV1::Types::Downstream ) || track.checkType( TrackV1::Types::Upstream ) );
+        assert( track.checkType( TrackV1::Types::Long ) || track.checkType( TrackV1::Types::Velo ) || track.isVeloBackward() || track.checkType( TrackV1::Types::Downstream ) || track.checkType( TrackV1::Types::Upstream ) );
       } else {
         static_assert( always_false<std::integral_constant<HitType, Types>...>::value,
                        "Hit Containers do not match any supported track type" );
diff --git a/Tr/TrackCheckers/src/TrackIPResolutionChecker.cpp b/Tr/TrackCheckers/src/TrackIPResolutionChecker.cpp
index 4f5a284065f..d44e4123b8b 100644
--- a/Tr/TrackCheckers/src/TrackIPResolutionChecker.cpp
+++ b/Tr/TrackCheckers/src/TrackIPResolutionChecker.cpp
@@ -431,7 +431,7 @@ StatusCode TrackIPResolutionChecker::execute() {
   // Finally, we also want to monitor the reconstructed IP, so the IP with respect to the reconstructed PVs.
   if ( !pvs.empty() ) {
     for ( const LHCb::Track* track : tracks )
-      if ( !track->checkType( LHCb::Track::Types::VeloBackward ) ) {
+      if ( !track->isVeloBackward() ) {
         const LHCb::MCParticle* mcparticle = linker.first( track );
         // distinghuish secondaries, from primaries, from ghosts
         bool        hasMCMatch = mcparticle && mcparticle->originVertex();
diff --git a/Tr/TrackCheckers/src/TrackIPResolutionCheckerNT.cpp b/Tr/TrackCheckers/src/TrackIPResolutionCheckerNT.cpp
index 601c75651ea..d97ce79035a 100644
--- a/Tr/TrackCheckers/src/TrackIPResolutionCheckerNT.cpp
+++ b/Tr/TrackCheckers/src/TrackIPResolutionCheckerNT.cpp
@@ -146,7 +146,7 @@ namespace {
           .ignore( /* AUTOMATICALLY ADDED FOR gaudi/Gaudi!763 */ );
       theTuple->column( "TNdof", track->info( LHCb::Track::AdditionalInfo::FitTNDoF, 0 ) )
           .ignore( /* AUTOMATICALLY ADDED FOR gaudi/Gaudi!763 */ );
-      theTuple->column( "backward", track->checkType( LHCb::Track::Types::VeloBackward ) )
+      theTuple->column( "backward", track->isVeloBackward() )
           .ignore( /* AUTOMATICALLY ADDED FOR gaudi/Gaudi!763 */ );
 
       const LHCb::State* stateAtFirstHit = track->stateAt( LHCb::State::Location::FirstMeasurement );
diff --git a/Tr/TrackCheckers/src/TrackPVChecker.cpp b/Tr/TrackCheckers/src/TrackPVChecker.cpp
index 9bae21173cf..430d4ac441b 100644
--- a/Tr/TrackCheckers/src/TrackPVChecker.cpp
+++ b/Tr/TrackCheckers/src/TrackPVChecker.cpp
@@ -610,7 +610,7 @@ void TrackPVChecker::operator()( PrimaryVertexContainer const& vertices, ///< Al
       plot1D( wtrk.weight, "pvtrkweight", "Track weight", 0, 1 );
       if ( wtrk.track ) plot1D( int( wtrk.track->type() ), "pvtrktype", "Track type", -0.5, 20.5, 21 );
       usedtracks.insert( wtrk.track );
-      if ( !wtrk.track || wtrk.track->checkType( Track::Type::VeloBackward ) ) ++numbackward;
+      if ( !wtrk.track || wtrk.track->isVeloBackward() ) ++numbackward;
     }
     plot1D( numbackward, "pvnumbackwardtracks", "Number of backward tracks", -0.5, 50.5, 51 );
   }
diff --git a/Tr/TrackCheckers/src/VertexChecker.cpp b/Tr/TrackCheckers/src/VertexChecker.cpp
index d5fa1f0ee29..1e9bc65f765 100644
--- a/Tr/TrackCheckers/src/VertexChecker.cpp
+++ b/Tr/TrackCheckers/src/VertexChecker.cpp
@@ -211,7 +211,7 @@ void VertexChecker::operator()( LHCb::MCVertices const& mcVertices, LHCb::RecVer
 
   // Number of tracks with IP between min and max values
   for ( const auto& itT : veloTracks ) {
-    if ( itT->checkType( LHCb::Track::Types::VeloBackward ) ) continue;
+    if ( itT->isVeloBackward() ) continue;
     Gaudi::XYZPoint  point = itT->position();
     Gaudi::XYZVector dir   = itT->slopes();
     auto [lowestIP, best]  = std::accumulate(
diff --git a/Tr/TrackExtrapolators/src/TrackStateProvider.cpp b/Tr/TrackExtrapolators/src/TrackStateProvider.cpp
index 7bc57a81012..6b70dcc7724 100644
--- a/Tr/TrackExtrapolators/src/TrackStateProvider.cpp
+++ b/Tr/TrackExtrapolators/src/TrackStateProvider.cpp
@@ -406,7 +406,7 @@ TrackCache TrackStateProvider::createCacheEntry( TkCacheKey key, const LHCb::Tra
   // at the beamline and at rich2. For the trajectory approximation
   // used in DTF for Long-Long Ks, this is not enough. Add a state at
   // the end of the Velo.
-  if ( !track.checkType( LHCb::Track::Types::VeloBackward ) && track.hasVelo() &&
+  if ( !track.isVeloBackward() && track.hasVelo() &&
        !track.stateAt( LHCb::State::Location::FirstMeasurement ) ) {
     addState( tc, StateParameters::ZEndVelo, geometry, LHCb::State::Location::EndVelo );
   }
diff --git a/Tr/TrackFitter/src/TrackMasterFitter.cpp b/Tr/TrackFitter/src/TrackMasterFitter.cpp
index 4e88d9a75fa..51e152e5cf7 100644
--- a/Tr/TrackFitter/src/TrackMasterFitter.cpp
+++ b/Tr/TrackFitter/src/TrackMasterFitter.cpp
@@ -355,8 +355,8 @@ StatusCode TrackMasterFitter::determineStates( Track& track ) const {
   auto* lastMeasurementNode  = ( jnode != nodes_.crend() ? *jnode : nullptr );
 
   bool upstream = nodes_.front()->z() > nodes_.back()->z();
-  bool reversed = ( upstream && !track.checkType( Track::Types::VeloBackward ) ) ||
-                  ( !upstream && track.checkType( Track::Types::VeloBackward ) );
+  bool reversed = ( upstream && !track.isVeloBackward() ) ||
+                  ( !upstream && track.isVeloBackward() );
 
   // This state is not filtered for a forward only fit.
   if ( m_addDefaultRefNodes.value() ) {
@@ -617,7 +617,7 @@ StatusCode TrackMasterFitter::makeNodes( Track& track, const LHCb::Tr::PID pid,
 
   // Add reference nodes depending on track type
   if ( m_addDefaultRefNodes.value() ) {
-    if ( track.hasVelo() && !track.checkType( Track::Types::VeloBackward ) )
+    if ( track.hasVelo() && !track.isVeloBackward() )
       nodes.push_back( new FitNode( StateParameters::ZEndVelo, State::Location::EndVelo ) );
     if ( track.hasUT() ) {
       nodes.push_back( new FitNode( StateParameters::ZBegRich1, State::Location::BegRich1 ) );
@@ -633,12 +633,12 @@ StatusCode TrackMasterFitter::makeNodes( Track& track, const LHCb::Tr::PID pid,
   // At a node for the position at the beamline
   if ( m_stateAtBeamLine.value() && track.hasVelo() ) {
     const LHCb::State& refstate =
-        *( track.checkType( Track::Types::VeloBackward ) ? track.states().back() : track.states().front() );
+        *( track.isVeloBackward() ? track.states().back() : track.states().front() );
     nodes.push_back( new FitNode( closestToBeamLine( refstate ), State::Location::ClosestToBeam ) );
   }
 
   // Sort the nodes in z
-  bool backward = track.checkType( LHCb::Track::Types::VeloBackward );
+  bool backward = track.isVeloBackward();
   bool upstream = ( m_upstream.value() && !backward ) || ( !m_upstream.value() && backward );
   if ( upstream ) {
     std::stable_sort( nodes.begin(), nodes.end(), TrackFunctor::decreasingByZ() );
@@ -852,7 +852,7 @@ StatusCode TrackMasterFitter::initializeRefStates( LHCb::Track& track, IGeometry
   const LHCb::State* stateAtT = track.stateAt( LHCb::State::Location::AtT );
   const LHCb::State& refstate =
       stateAtT ? *stateAtT
-               : *( track.checkType( Track::Types::VeloBackward ) ? track.states().front() : track.states().back() );
+               : *( track.isVeloBackward() ? track.states().front() : track.states().back() );
   for ( auto* state : track.states() ) const_cast<LHCb::State*>( state )->setQOverP( refstate.qOverP() );
 
   // collect the z-positions where we want the states
diff --git a/Tr/TrackKernel/include/TrackKernel/TrackPredicates.h b/Tr/TrackKernel/include/TrackKernel/TrackPredicates.h
index 1491d760174..6c7fab21902 100644
--- a/Tr/TrackKernel/include/TrackKernel/TrackPredicates.h
+++ b/Tr/TrackKernel/include/TrackKernel/TrackPredicates.h
@@ -30,7 +30,7 @@ namespace TrackPredicates {
     int m_sign;
     VeloSide( int asign ) : m_sign( asign ) {}
     bool operator()( const LHCb::Track* track ) const {
-      return track->firstState().tx() * m_sign * ( track->checkType( LHCb::Track::Types::VeloBackward ) ? -1 : 1 ) > 0;
+      return track->firstState().tx() * m_sign * ( track->isVeloBackward() ? -1 : 1 ) > 0;
     }
   };
 
diff --git a/Tr/TrackMCTools/src/MeasureIPResolution.cpp b/Tr/TrackMCTools/src/MeasureIPResolution.cpp
index 5fb11069bc0..3232e8e170d 100644
--- a/Tr/TrackMCTools/src/MeasureIPResolution.cpp
+++ b/Tr/TrackMCTools/src/MeasureIPResolution.cpp
@@ -87,7 +87,7 @@ StatusCode MeasureIPResolution::execute() {
   LinkedTo<LHCb::MCParticle> trackLinker( evtSvc(), msgSvc(), m_containerName );
 
   for ( LHCb::Tracks::const_iterator itT = tracks->begin(); tracks->end() != itT; ++itT ) {
-    if ( ( *itT )->checkType( LHCb::Track::Types::VeloBackward ) ) continue;
+    if ( ( *itT )->isVeloBackward() ) continue;
     LHCb::MCParticle* part = trackLinker.first( *itT );
     /*
     if ( 0 == part ) continue;
diff --git a/Tr/TrackMonitors/src/TrackVPOverlapMonitor.cpp b/Tr/TrackMonitors/src/TrackVPOverlapMonitor.cpp
index 28614806777..814a08b4e01 100644
--- a/Tr/TrackMonitors/src/TrackVPOverlapMonitor.cpp
+++ b/Tr/TrackMonitors/src/TrackVPOverlapMonitor.cpp
@@ -62,7 +62,7 @@ namespace LHCb::Tr::Monitor {
       };
 
       for ( const Track* track : tracks ) { // start of track-loop
-        const bool bwd  = track->checkType( Track::Types::VeloBackward );
+        const bool bwd  = track->isVeloBackward();
         const auto type = track->type();
         if ( type != Track::Types::Velo && type != Track::Types::Long && !bwd ) { continue; }
         const bool fitted = track->checkFitStatus( Track::FitStatus::Fitted );
diff --git a/Tr/TrackMonitors/src/TrackVertexMonitor.cpp b/Tr/TrackMonitors/src/TrackVertexMonitor.cpp
index b1eed888f43..b0e6e07aaa6 100644
--- a/Tr/TrackMonitors/src/TrackVertexMonitor.cpp
+++ b/Tr/TrackMonitors/src/TrackVertexMonitor.cpp
@@ -237,8 +237,12 @@ namespace {
     return [=]( const LHCb::Track* track ) { return track->type() == atype; };
   };
 
-  auto TrackTypeAntiPredicate = []( LHCb::Track::Types atype ) {
-    return [=]( const LHCb::Track* track ) { return track->type() != atype; };
+  auto TrackBackwardPredicate = []( ) {
+    return [=]( const LHCb::Track* track ) { return track->isVeloBackward() };
+  };
+
+  auto TrackForwardPredicate = []( ) {
+    return [=]( const LHCb::Track* track ) { return !track->isVeloBackward() };
   };
 
   auto TrackFlagPredicate = []( LHCb::Track::Flags flag, bool positive ) {
@@ -278,8 +282,8 @@ namespace {
 void TrackVertexMonitor::operator()( LHCb::RecVertex::Range const& pvcontainer, LHCb::Track::Range const& alltracks,
                                      DetectorElement const& lhcb ) const {
   const auto isLong     = TrackTypePredicate( LHCb::Track::Types::Long );
-  const auto isBackward = TrackTypePredicate( LHCb::Track::Types::VeloBackward );
-  const auto isForward  = TrackTypeAntiPredicate( LHCb::Track::Types::VeloBackward );;
+  const auto isBackward = TrackBackwardPredicate();
+  const auto isForward  = TrackForwardPredicate();
 
   // lists needed
   // - primary vertices
diff --git a/Tr/TrackMonitors/src/VPTrackMonitor.cpp b/Tr/TrackMonitors/src/VPTrackMonitor.cpp
index c3c86141f7a..de93fc09245 100644
--- a/Tr/TrackMonitors/src/VPTrackMonitor.cpp
+++ b/Tr/TrackMonitors/src/VPTrackMonitor.cpp
@@ -261,7 +261,7 @@ namespace LHCb::Tr::Monitor {
 
       // start of track-loop
       for ( const LHCb::Track* track : tracks ) {
-        const bool bwd  = track->checkType( LHCb::Track::Types::VeloBackward );
+        const bool bwd  = track->isVeloBackward();
         const auto type = track->type();
 
         if constexpr ( outmode == OutputMode::Histograms ) {
diff --git a/Tr/TrackTools/src/LongTrackReferenceCreator.cpp b/Tr/TrackTools/src/LongTrackReferenceCreator.cpp
index 13eb8526615..dc0b46b12d7 100644
--- a/Tr/TrackTools/src/LongTrackReferenceCreator.cpp
+++ b/Tr/TrackTools/src/LongTrackReferenceCreator.cpp
@@ -83,7 +83,7 @@ StatusCode LongTrackReferenceCreator::execute( LHCb::Track& track ) const {
     const LHCb::State* stateAtT = track.stateAt( LHCb::State::Location::AtT );
     const LHCb::State& refstate =
         stateAtT ? *stateAtT
-                 : *( track.checkType( Track::Types::VeloBackward ) ? track.states().front() : track.states().back() );
+                 : *( track.isVeloBackward() ? track.states().front() : track.states().back() );
     for ( auto& s : track.states() ) s->setQOverP( refstate.qOverP() );
 
     // collect the z-positions where we want the states
diff --git a/Tr/TrackTools/src/TrackSelectorBase.h b/Tr/TrackTools/src/TrackSelectorBase.h
index 35367541994..24bea0e7b4b 100644
--- a/Tr/TrackTools/src/TrackSelectorBase.h
+++ b/Tr/TrackTools/src/TrackSelectorBase.h
@@ -74,7 +74,7 @@ protected:
   // Check track type
   bool checkTrackType( const LHCb::Track& aTrack ) const {
     if ( m_selTypes.value()( aTrack.type() ) ) {
-      return m_onlyBackwardTracks ? aTrack.checkType( LHCb::Track::Types::VeloBackward ) : true;
+      return m_onlyBackwardTracks ? aTrack.isVeloBackward() : true;
     }
     if ( msgLevel( MSG::VERBOSE ) ) verbose() << " -> Track type " << aTrack.type() << " is rejected" << endmsg;
     return false;
diff --git a/Tr/TrackTools/src/UpgradeGhostId.cpp b/Tr/TrackTools/src/UpgradeGhostId.cpp
index e49a9c49cc4..494a6470d8c 100644
--- a/Tr/TrackTools/src/UpgradeGhostId.cpp
+++ b/Tr/TrackTools/src/UpgradeGhostId.cpp
@@ -233,7 +233,7 @@ StatusCode UpgradeGhostId::execute( LHCb::Track& aTrack ) const {
   if ( LHCb::Track::Types::Long != aTrack.type() && LHCb::Track::Types::Downstream != aTrack.type() ) {
     variables.push_back( aTrack.nDoF() );
   }
-  if ( (LHCb::Track::Types::Velo != aTrack.type()) && (LHCb::Track::Types::VeloBackward != aTrack.type())) { variables.push_back( aTrack.pt() ); }
+  if ( (LHCb::Track::Types::Velo != aTrack.type()) && !aTrack.isVeloBackward() ) { variables.push_back( aTrack.pt() ); }
   variables.push_back( aTrack.pseudoRapidity() );
 
   float netresponse = std::numeric_limits<float>::max();
diff --git a/Tr/TrackTools/src/VeloMuonBuilder.cpp b/Tr/TrackTools/src/VeloMuonBuilder.cpp
index 04f16fa0702..8655b17197f 100644
--- a/Tr/TrackTools/src/VeloMuonBuilder.cpp
+++ b/Tr/TrackTools/src/VeloMuonBuilder.cpp
@@ -89,7 +89,7 @@ LHCb::Tracks VeloMuonBuilder::operator()( const LHCb::Tracks& muontracks, const
     // loop over velos - chose the one with the closest distance at the extrapolated position in the magnet
     for ( auto& velotrack : velotracks ) {
 
-      if ( velotrack->checkType( LHCb::Track::Types::VeloBackward ) ) continue;
+      if ( velotrack->isVeloBackward() ) continue;
 
       // extrapolate the velo track to the position in the magnet
       Gaudi::XYZPoint velopunktx, velopunkty;
-- 
GitLab


From 1585fd734c925cd3cd82f6e913f6cade08423aac Mon Sep 17 00:00:00 2001
From: Andrii Usachov <andrii.usachov@cern.ch>
Date: Tue, 20 Sep 2022 16:20:15 +0200
Subject: [PATCH 06/15] fixes

---
 Rec/LoKiTrack/include/LoKi/Track.h          | 13 +++++++++++++
 Rec/LoKiTrack/include/LoKi/TrackCuts.h      |  2 +-
 Tr/TrackMonitors/src/TrackVertexMonitor.cpp |  4 ++--
 3 files changed, 16 insertions(+), 3 deletions(-)

diff --git a/Rec/LoKiTrack/include/LoKi/Track.h b/Rec/LoKiTrack/include/LoKi/Track.h
index 64db9495c2d..0ecafd40840 100644
--- a/Rec/LoKiTrack/include/LoKi/Track.h
+++ b/Rec/LoKiTrack/include/LoKi/Track.h
@@ -439,6 +439,19 @@ namespace LoKi::Track {
     std::ostream& fillStream( std::ostream& s ) const override;
     // ======================================================================
   };
+    // ========================================================================
+  /** @class isVeloBackward
+   *  simple evaluator of the LHCb::Track::isVeloBackward
+   *  @see LoKi::Cuts::TrBACKWARD
+   */
+  namespace details {
+    struct isVeloBackward {
+      static constexpr auto       fun      = &LHCb::Track::isVeloBackward;
+      static constexpr const char symbol[] = "TrBACKWARD";
+      static constexpr auto       invalid  = -1;
+    };
+  } // namespace details
+  using isVeloBackward = details::UnaryFun<details::isVeloBackward>;
   // ========================================================================
   /** @class Chi2
    *  simple evaluator of the LHcb::Track::chi2
diff --git a/Rec/LoKiTrack/include/LoKi/TrackCuts.h b/Rec/LoKiTrack/include/LoKi/TrackCuts.h
index 815f10ccaab..bd3871b00d2 100644
--- a/Rec/LoKiTrack/include/LoKi/TrackCuts.h
+++ b/Rec/LoKiTrack/include/LoKi/TrackCuts.h
@@ -69,7 +69,7 @@ namespace LoKi {
      *  @author Vanya BELYAEV ibelyaev@physics.syr.edu
      *  @date   2007-06-08
      */
-    inline const auto TrBACKWARD = LoKi::Track::isBackward{};
+    inline const auto TrBACKWARD = LoKi::Track::isVeloBackward{};
     
     // ========================================================================
     /** @var TrCHI2
diff --git a/Tr/TrackMonitors/src/TrackVertexMonitor.cpp b/Tr/TrackMonitors/src/TrackVertexMonitor.cpp
index b0e6e07aaa6..a07c17ed3b5 100644
--- a/Tr/TrackMonitors/src/TrackVertexMonitor.cpp
+++ b/Tr/TrackMonitors/src/TrackVertexMonitor.cpp
@@ -238,11 +238,11 @@ namespace {
   };
 
   auto TrackBackwardPredicate = []( ) {
-    return [=]( const LHCb::Track* track ) { return track->isVeloBackward() };
+    return [=]( const LHCb::Track* track ) { return track->isVeloBackward(); };
   };
 
   auto TrackForwardPredicate = []( ) {
-    return [=]( const LHCb::Track* track ) { return !track->isVeloBackward() };
+    return [=]( const LHCb::Track* track ) { return !track->isVeloBackward(); };
   };
 
   auto TrackFlagPredicate = []( LHCb::Track::Flags flag, bool positive ) {
-- 
GitLab


From 70a79b46beefb34c6402accaf33ba81482216e3a Mon Sep 17 00:00:00 2001
From: Gitlab CI <noreply@cern.ch>
Date: Tue, 20 Sep 2022 14:20:52 +0000
Subject: [PATCH 07/15] Fixed formatting

patch generated by https://gitlab.cern.ch/lhcb/Rec/-/jobs/24666936
---
 Pr/PrConverters/src/PrConvertersInfo.h        | 20 ++++++++++---------
 Pr/PrConverters/src/fromV3TrackV1Track.cpp    |  2 +-
 Rec/LoKiTrack/include/LoKi/Track.h            |  2 +-
 Rec/LoKiTrack/include/LoKi/TrackCuts.h        |  2 +-
 Tf/FastPV/src/FastPVMonitor.cpp               |  2 +-
 Tr/PrKalmanFilter/src/KalmanFilterTool.cpp    |  4 +++-
 .../src/TrackIPResolutionCheckerNT.cpp        |  3 +--
 Tr/TrackCheckers/src/TrackResChecker.cpp      |  6 +++---
 .../src/TrackStateProvider.cpp                |  3 +--
 Tr/TrackFitter/src/TrackMasterFitter.cpp      |  9 +++------
 Tr/TrackMonitors/src/TrackMonitor.cpp         |  8 ++++----
 Tr/TrackMonitors/src/TrackVertexMonitor.cpp   |  8 ++------
 .../src/LongTrackReferenceCreator.cpp         |  3 +--
 Tr/TrackTools/src/TrackSelectorBase.h         |  4 +---
 Tr/TrackTools/src/UpgradeGhostId.cpp          | 16 ++++++++-------
 Tr/TrackUtils/src/TrackBestTrackCreator.cpp   |  8 +++-----
 Tr/TrackUtils/src/TracksVPConverter.cpp       |  6 +++---
 17 files changed, 49 insertions(+), 57 deletions(-)

diff --git a/Pr/PrConverters/src/PrConvertersInfo.h b/Pr/PrConverters/src/PrConvertersInfo.h
index 8954f50bb29..b3366a6686e 100644
--- a/Pr/PrConverters/src/PrConvertersInfo.h
+++ b/Pr/PrConverters/src/PrConvertersInfo.h
@@ -82,8 +82,8 @@ namespace LHCb::Pr::ConversionInfo {
     static constexpr LHCb::Event::v1::Track::History PrHistory = LHCb::Event::v1::Track::History::PrPixel;
     static constexpr std::array<std::pair<LHCb::State::Location, int>, 2> StateLocations = {
         std::make_pair( LHCb::State::Location::ClosestToBeam, 0 ), std::make_pair( LHCb::State::Location::EndVelo, 1 )};
-    static constexpr bool                                           AddStatesFromAncestor = false;
-    static constexpr std::array<const char*, 0>                     AncestorLocations     = {};
+    static constexpr bool                       AddStatesFromAncestor = false;
+    static constexpr std::array<const char*, 0> AncestorLocations     = {};
   };
 
   struct VeloBackward {
@@ -91,20 +91,22 @@ namespace LHCb::Pr::ConversionInfo {
     static constexpr LHCb::Event::v1::Track::History PrHistory = LHCb::Event::v1::Track::History::PrPixel;
     static constexpr std::array<std::pair<LHCb::State::Location, int>, 1> StateLocations = {
         std::make_pair( LHCb::State::Location::ClosestToBeam, 0 )};
-    static constexpr bool                                           AddStatesFromAncestor = false;
-    static constexpr std::array<const char*, 0>                     AncestorLocations     = {{}};
+    static constexpr bool                       AddStatesFromAncestor = false;
+    static constexpr std::array<const char*, 0> AncestorLocations     = {{}};
   };
 
   struct Velo {
-    static LHCb::Event::v1::Track::Types Type( bool backward=false ){
-      if ( backward ) return LHCb::Event::v1::Track::Types::VeloBackward;
-      else return LHCb::Event::v1::Track::Types::Velo;  
+    static LHCb::Event::v1::Track::Types Type( bool backward = false ) {
+      if ( backward )
+        return LHCb::Event::v1::Track::Types::VeloBackward;
+      else
+        return LHCb::Event::v1::Track::Types::Velo;
     }
     static constexpr LHCb::Event::v1::Track::History PrHistory = LHCb::Event::v1::Track::History::PrPixel;
     static constexpr std::array<std::pair<LHCb::State::Location, int>, 2> StateLocations = {
         std::make_pair( LHCb::State::Location::ClosestToBeam, 0 ), std::make_pair( LHCb::State::Location::EndVelo, 1 )};
-    static constexpr bool                                           AddStatesFromAncestor = false;
-    static constexpr std::array<const char*, 0>                     AncestorLocations     = {};
+    static constexpr bool                       AddStatesFromAncestor = false;
+    static constexpr std::array<const char*, 0> AncestorLocations     = {};
   };
 
   struct Seeding {
diff --git a/Pr/PrConverters/src/fromV3TrackV1Track.cpp b/Pr/PrConverters/src/fromV3TrackV1Track.cpp
index 5a0177d7db7..e1c1601ae7e 100644
--- a/Pr/PrConverters/src/fromV3TrackV1Track.cpp
+++ b/Pr/PrConverters/src/fromV3TrackV1Track.cpp
@@ -208,7 +208,7 @@ namespace LHCb::Converters::Track::v1 {
       int counter = 0;
       for ( auto const track_with_extra_info : tracks_with_extra_infos ) {
         auto new_track = new LHCb::Event::v1::Track{};
-        if ( in_tracks.backward() ) 
+        if ( in_tracks.backward() )
           new_track->setType( LHCb::Track::Types::VeloBackward );
         else
           new_track->setType( conversion::to_v1_track_type( track_with_extra_info.type() ) );
diff --git a/Rec/LoKiTrack/include/LoKi/Track.h b/Rec/LoKiTrack/include/LoKi/Track.h
index 0ecafd40840..3531f5e57a1 100644
--- a/Rec/LoKiTrack/include/LoKi/Track.h
+++ b/Rec/LoKiTrack/include/LoKi/Track.h
@@ -439,7 +439,7 @@ namespace LoKi::Track {
     std::ostream& fillStream( std::ostream& s ) const override;
     // ======================================================================
   };
-    // ========================================================================
+  // ========================================================================
   /** @class isVeloBackward
    *  simple evaluator of the LHCb::Track::isVeloBackward
    *  @see LoKi::Cuts::TrBACKWARD
diff --git a/Rec/LoKiTrack/include/LoKi/TrackCuts.h b/Rec/LoKiTrack/include/LoKi/TrackCuts.h
index bd3871b00d2..3f2bd288524 100644
--- a/Rec/LoKiTrack/include/LoKi/TrackCuts.h
+++ b/Rec/LoKiTrack/include/LoKi/TrackCuts.h
@@ -70,7 +70,7 @@ namespace LoKi {
      *  @date   2007-06-08
      */
     inline const auto TrBACKWARD = LoKi::Track::isVeloBackward{};
-    
+
     // ========================================================================
     /** @var TrCHI2
      *  the simple function which returns LHCb::Track::Chi2
diff --git a/Tf/FastPV/src/FastPVMonitor.cpp b/Tf/FastPV/src/FastPVMonitor.cpp
index 9d638b6cd06..9cec7c53af8 100644
--- a/Tf/FastPV/src/FastPVMonitor.cpp
+++ b/Tf/FastPV/src/FastPVMonitor.cpp
@@ -196,7 +196,7 @@ StatusCode FastPVMonitor::execute() {
 
   // Number of tracks with IP between min and max values
   for ( LHCb::Tracks::iterator itT = tracks->begin(); tracks->end() != itT; ++itT ) { // loop over tracks
-    if ( ( *itT )->isVeloBackward() ) continue;              // avoid backward tracks
+    if ( ( *itT )->isVeloBackward() ) continue;                                       // avoid backward tracks
     Gaudi::XYZPoint  point = ( *itT )->position();                                    // track position (first hit ?)
     Gaudi::XYZVector dir   = ( *itT )->slopes();                                      // track direction
 
diff --git a/Tr/PrKalmanFilter/src/KalmanFilterTool.cpp b/Tr/PrKalmanFilter/src/KalmanFilterTool.cpp
index 360318a4a09..99c828ac8be 100644
--- a/Tr/PrKalmanFilter/src/KalmanFilterTool.cpp
+++ b/Tr/PrKalmanFilter/src/KalmanFilterTool.cpp
@@ -71,7 +71,9 @@ namespace LHCb::Pr {
         assert( track.checkType( TrackV1::Types::Ttrack ) );
       } else if constexpr ( has_hit_type<HitType::VP, Types...> && has_hit_type<HitType::FT, Types...> &&
                             has_hit_type<HitType::UT, Types...> ) {
-        assert( track.checkType( TrackV1::Types::Long ) || track.checkType( TrackV1::Types::Velo ) || track.isVeloBackward() || track.checkType( TrackV1::Types::Downstream ) || track.checkType( TrackV1::Types::Upstream ) );
+        assert( track.checkType( TrackV1::Types::Long ) || track.checkType( TrackV1::Types::Velo ) ||
+                track.isVeloBackward() || track.checkType( TrackV1::Types::Downstream ) ||
+                track.checkType( TrackV1::Types::Upstream ) );
       } else {
         static_assert( always_false<std::integral_constant<HitType, Types>...>::value,
                        "Hit Containers do not match any supported track type" );
diff --git a/Tr/TrackCheckers/src/TrackIPResolutionCheckerNT.cpp b/Tr/TrackCheckers/src/TrackIPResolutionCheckerNT.cpp
index d97ce79035a..bb74266e204 100644
--- a/Tr/TrackCheckers/src/TrackIPResolutionCheckerNT.cpp
+++ b/Tr/TrackCheckers/src/TrackIPResolutionCheckerNT.cpp
@@ -146,8 +146,7 @@ namespace {
           .ignore( /* AUTOMATICALLY ADDED FOR gaudi/Gaudi!763 */ );
       theTuple->column( "TNdof", track->info( LHCb::Track::AdditionalInfo::FitTNDoF, 0 ) )
           .ignore( /* AUTOMATICALLY ADDED FOR gaudi/Gaudi!763 */ );
-      theTuple->column( "backward", track->isVeloBackward() )
-          .ignore( /* AUTOMATICALLY ADDED FOR gaudi/Gaudi!763 */ );
+      theTuple->column( "backward", track->isVeloBackward() ).ignore( /* AUTOMATICALLY ADDED FOR gaudi/Gaudi!763 */ );
 
       const LHCb::State* stateAtFirstHit = track->stateAt( LHCb::State::Location::FirstMeasurement );
       theTuple->column( "firsthittx", double( stateAtFirstHit ? stateAtFirstHit->tx() : 0 ) )
diff --git a/Tr/TrackCheckers/src/TrackResChecker.cpp b/Tr/TrackCheckers/src/TrackResChecker.cpp
index 84d0bfd9c52..4f7161d34ec 100644
--- a/Tr/TrackCheckers/src/TrackResChecker.cpp
+++ b/Tr/TrackCheckers/src/TrackResChecker.cpp
@@ -94,9 +94,9 @@ StatusCode TrackResChecker::initialize() {
   return Consumer::initialize().andThen( [&] {
     m_histoTools[0] = createHistoTool( "ALL" );
     if ( splitByType() ) {
-      using Type = LHCb::Track::Types;
-      constexpr auto types =
-          std::array{Type::Velo, Type::VeloBackward, Type::Long, Type::Upstream, Type::Downstream, Type::Ttrack, Type::Muon};
+      using Type           = LHCb::Track::Types;
+      constexpr auto types = std::array{Type::Velo,       Type::VeloBackward, Type::Long, Type::Upstream,
+                                        Type::Downstream, Type::Ttrack,       Type::Muon};
       for ( auto type : types ) { m_histoTools[static_cast<int>( type )] = createHistoTool( toString( type ) ); }
     }
   } );
diff --git a/Tr/TrackExtrapolators/src/TrackStateProvider.cpp b/Tr/TrackExtrapolators/src/TrackStateProvider.cpp
index 6b70dcc7724..9e4136ed24e 100644
--- a/Tr/TrackExtrapolators/src/TrackStateProvider.cpp
+++ b/Tr/TrackExtrapolators/src/TrackStateProvider.cpp
@@ -406,8 +406,7 @@ TrackCache TrackStateProvider::createCacheEntry( TkCacheKey key, const LHCb::Tra
   // at the beamline and at rich2. For the trajectory approximation
   // used in DTF for Long-Long Ks, this is not enough. Add a state at
   // the end of the Velo.
-  if ( !track.isVeloBackward() && track.hasVelo() &&
-       !track.stateAt( LHCb::State::Location::FirstMeasurement ) ) {
+  if ( !track.isVeloBackward() && track.hasVelo() && !track.stateAt( LHCb::State::Location::FirstMeasurement ) ) {
     addState( tc, StateParameters::ZEndVelo, geometry, LHCb::State::Location::EndVelo );
   }
 
diff --git a/Tr/TrackFitter/src/TrackMasterFitter.cpp b/Tr/TrackFitter/src/TrackMasterFitter.cpp
index 51e152e5cf7..cd849fb8add 100644
--- a/Tr/TrackFitter/src/TrackMasterFitter.cpp
+++ b/Tr/TrackFitter/src/TrackMasterFitter.cpp
@@ -355,8 +355,7 @@ StatusCode TrackMasterFitter::determineStates( Track& track ) const {
   auto* lastMeasurementNode  = ( jnode != nodes_.crend() ? *jnode : nullptr );
 
   bool upstream = nodes_.front()->z() > nodes_.back()->z();
-  bool reversed = ( upstream && !track.isVeloBackward() ) ||
-                  ( !upstream && track.isVeloBackward() );
+  bool reversed = ( upstream && !track.isVeloBackward() ) || ( !upstream && track.isVeloBackward() );
 
   // This state is not filtered for a forward only fit.
   if ( m_addDefaultRefNodes.value() ) {
@@ -632,8 +631,7 @@ StatusCode TrackMasterFitter::makeNodes( Track& track, const LHCb::Tr::PID pid,
 
   // At a node for the position at the beamline
   if ( m_stateAtBeamLine.value() && track.hasVelo() ) {
-    const LHCb::State& refstate =
-        *( track.isVeloBackward() ? track.states().back() : track.states().front() );
+    const LHCb::State& refstate = *( track.isVeloBackward() ? track.states().back() : track.states().front() );
     nodes.push_back( new FitNode( closestToBeamLine( refstate ), State::Location::ClosestToBeam ) );
   }
 
@@ -851,8 +849,7 @@ StatusCode TrackMasterFitter::initializeRefStates( LHCb::Track& track, IGeometry
   // velo-TT
   const LHCb::State* stateAtT = track.stateAt( LHCb::State::Location::AtT );
   const LHCb::State& refstate =
-      stateAtT ? *stateAtT
-               : *( track.isVeloBackward() ? track.states().front() : track.states().back() );
+      stateAtT ? *stateAtT : *( track.isVeloBackward() ? track.states().front() : track.states().back() );
   for ( auto* state : track.states() ) const_cast<LHCb::State*>( state )->setQOverP( refstate.qOverP() );
 
   // collect the z-positions where we want the states
diff --git a/Tr/TrackMonitors/src/TrackMonitor.cpp b/Tr/TrackMonitors/src/TrackMonitor.cpp
index 22c347a9a3f..e35e10996a1 100644
--- a/Tr/TrackMonitors/src/TrackMonitor.cpp
+++ b/Tr/TrackMonitors/src/TrackMonitor.cpp
@@ -281,8 +281,8 @@ private:
   using Type = LHCb::Event::Enum::Track::Type;
   Gaudi::Property<std::vector<Type>> m_typesToMonitor{this,
                                                       "typesToMonitor",
-                                                      {Type::Unknown, Type::Velo, Type::VeloBackward, Type::Long, Type::Upstream,
-                                                       Type::Downstream, Type::Ttrack, Type::Muon,
+                                                      {Type::Unknown, Type::Velo, Type::VeloBackward, Type::Long,
+                                                       Type::Upstream, Type::Downstream, Type::Ttrack, Type::Muon,
                                                        Type::UT}};
 
   // HISTOGRAM DEFINITION
@@ -389,8 +389,8 @@ void TrackMonitor<TFitResult, TNode>::initializeHistogramMap() {
 
   if ( splitByType() ) {
     for ( auto const& type : m_typesToMonitor.value() ) {
-      std::string typo                            = toString( type );
-      m_histograms[toString( type )]              = std::make_unique<TypeTrackHistogram>( this, typo );
+      std::string typo               = toString( type );
+      m_histograms[toString( type )] = std::make_unique<TypeTrackHistogram>( this, typo );
       for ( auto hittype = 0; hittype < HitType::HitTypeUnknown; ++hittype ) {
         const auto name = HitTypeName[hittype];
         m_named_histograms[toString( type )][name] =
diff --git a/Tr/TrackMonitors/src/TrackVertexMonitor.cpp b/Tr/TrackMonitors/src/TrackVertexMonitor.cpp
index a07c17ed3b5..a2bee75f446 100644
--- a/Tr/TrackMonitors/src/TrackVertexMonitor.cpp
+++ b/Tr/TrackMonitors/src/TrackVertexMonitor.cpp
@@ -237,13 +237,9 @@ namespace {
     return [=]( const LHCb::Track* track ) { return track->type() == atype; };
   };
 
-  auto TrackBackwardPredicate = []( ) {
-    return [=]( const LHCb::Track* track ) { return track->isVeloBackward(); };
-  };
+  auto TrackBackwardPredicate = []() { return [=]( const LHCb::Track* track ) { return track->isVeloBackward(); }; };
 
-  auto TrackForwardPredicate = []( ) {
-    return [=]( const LHCb::Track* track ) { return !track->isVeloBackward(); };
-  };
+  auto TrackForwardPredicate = []() { return [=]( const LHCb::Track* track ) { return !track->isVeloBackward(); }; };
 
   auto TrackFlagPredicate = []( LHCb::Track::Flags flag, bool positive ) {
     return [=]( const LHCb::Track* track ) {
diff --git a/Tr/TrackTools/src/LongTrackReferenceCreator.cpp b/Tr/TrackTools/src/LongTrackReferenceCreator.cpp
index dc0b46b12d7..e8fc03ff955 100644
--- a/Tr/TrackTools/src/LongTrackReferenceCreator.cpp
+++ b/Tr/TrackTools/src/LongTrackReferenceCreator.cpp
@@ -82,8 +82,7 @@ StatusCode LongTrackReferenceCreator::execute( LHCb::Track& track ) const {
     // velo-TT
     const LHCb::State* stateAtT = track.stateAt( LHCb::State::Location::AtT );
     const LHCb::State& refstate =
-        stateAtT ? *stateAtT
-                 : *( track.isVeloBackward() ? track.states().front() : track.states().back() );
+        stateAtT ? *stateAtT : *( track.isVeloBackward() ? track.states().front() : track.states().back() );
     for ( auto& s : track.states() ) s->setQOverP( refstate.qOverP() );
 
     // collect the z-positions where we want the states
diff --git a/Tr/TrackTools/src/TrackSelectorBase.h b/Tr/TrackTools/src/TrackSelectorBase.h
index 24bea0e7b4b..fdcb43f09a6 100644
--- a/Tr/TrackTools/src/TrackSelectorBase.h
+++ b/Tr/TrackTools/src/TrackSelectorBase.h
@@ -73,9 +73,7 @@ public:
 protected:
   // Check track type
   bool checkTrackType( const LHCb::Track& aTrack ) const {
-    if ( m_selTypes.value()( aTrack.type() ) ) {
-      return m_onlyBackwardTracks ? aTrack.isVeloBackward() : true;
-    }
+    if ( m_selTypes.value()( aTrack.type() ) ) { return m_onlyBackwardTracks ? aTrack.isVeloBackward() : true; }
     if ( msgLevel( MSG::VERBOSE ) ) verbose() << " -> Track type " << aTrack.type() << " is rejected" << endmsg;
     return false;
   }
diff --git a/Tr/TrackTools/src/UpgradeGhostId.cpp b/Tr/TrackTools/src/UpgradeGhostId.cpp
index 494a6470d8c..91a11d408d1 100644
--- a/Tr/TrackTools/src/UpgradeGhostId.cpp
+++ b/Tr/TrackTools/src/UpgradeGhostId.cpp
@@ -159,12 +159,12 @@ StatusCode UpgradeGhostId::initialize() {
   return GaudiTool::initialize().andThen( [&] {
     m_flatters.clear();
     m_flatters.resize( static_cast<int>( LHCb::Track::Types::Last ) );
-    m_flatters[static_cast<int>( LHCb::Track::Types::Velo )]       = Update_VeloTable();
-    m_flatters[static_cast<int>( LHCb::Track::Types::VeloBackward )]       = Update_VeloTable();
-    m_flatters[static_cast<int>( LHCb::Track::Types::Upstream )]   = Update_UpstreamTable();
-    m_flatters[static_cast<int>( LHCb::Track::Types::Downstream )] = Update_DownstreamTable();
-    m_flatters[static_cast<int>( LHCb::Track::Types::Long )]       = Update_LongTable();
-    m_flatters[static_cast<int>( LHCb::Track::Types::Ttrack )]     = Update_TtrackTable();
+    m_flatters[static_cast<int>( LHCb::Track::Types::Velo )]         = Update_VeloTable();
+    m_flatters[static_cast<int>( LHCb::Track::Types::VeloBackward )] = Update_VeloTable();
+    m_flatters[static_cast<int>( LHCb::Track::Types::Upstream )]     = Update_UpstreamTable();
+    m_flatters[static_cast<int>( LHCb::Track::Types::Downstream )]   = Update_DownstreamTable();
+    m_flatters[static_cast<int>( LHCb::Track::Types::Long )]         = Update_LongTable();
+    m_flatters[static_cast<int>( LHCb::Track::Types::Ttrack )]       = Update_TtrackTable();
   } );
 }
 
@@ -233,7 +233,9 @@ StatusCode UpgradeGhostId::execute( LHCb::Track& aTrack ) const {
   if ( LHCb::Track::Types::Long != aTrack.type() && LHCb::Track::Types::Downstream != aTrack.type() ) {
     variables.push_back( aTrack.nDoF() );
   }
-  if ( (LHCb::Track::Types::Velo != aTrack.type()) && !aTrack.isVeloBackward() ) { variables.push_back( aTrack.pt() ); }
+  if ( ( LHCb::Track::Types::Velo != aTrack.type() ) && !aTrack.isVeloBackward() ) {
+    variables.push_back( aTrack.pt() );
+  }
   variables.push_back( aTrack.pseudoRapidity() );
 
   float netresponse = std::numeric_limits<float>::max();
diff --git a/Tr/TrackUtils/src/TrackBestTrackCreator.cpp b/Tr/TrackUtils/src/TrackBestTrackCreator.cpp
index dea901f81c3..b8fb21f77cc 100644
--- a/Tr/TrackUtils/src/TrackBestTrackCreator.cpp
+++ b/Tr/TrackUtils/src/TrackBestTrackCreator.cpp
@@ -116,9 +116,7 @@ namespace LHCb {
         }
       }
     }
-    CounterType& operator()( LHCb::Track::Types type ) {
-      return m_counters[static_cast<int>( type )];
-    }
+    CounterType& operator()( LHCb::Track::Types type ) { return m_counters[static_cast<int>( type )]; }
 
   private:
     ToolHandle<ITrackFitter>      m_fitter{this, "Fitter", "TrackMasterFitter"};
@@ -369,8 +367,8 @@ void LHCb::TrackBestTrackCreator::fitAndUpdateCounters( TrackData& td, IGeometry
     ( *m_fitter )( track, geometry, Tr::PID::Pion() ).ignore();
   }
 
-  bool badinput   = false;
-  bool fitfailed  = false;
+  bool badinput  = false;
+  bool fitfailed = false;
 
   if ( m_doNotRefit &&
        ( td.previousStatus() == Track::FitStatus::Fitted || td.previousStatus() == Track::FitStatus::FitFailed ) ) {
diff --git a/Tr/TrackUtils/src/TracksVPConverter.cpp b/Tr/TrackUtils/src/TracksVPConverter.cpp
index fde57672a62..09b1ae36030 100644
--- a/Tr/TrackUtils/src/TracksVPConverter.cpp
+++ b/Tr/TrackUtils/src/TracksVPConverter.cpp
@@ -101,7 +101,7 @@ public:
       auto state_endvelo = getState( track, 1 );
       state_endvelo.setLocation( LHCb::State::Location::EndVelo );
       newTrack.addToStates( state_endvelo );
-      newTrack.setType( LHCb::Event::v2::Track::Type::Velo ); 
+      newTrack.setType( LHCb::Event::v2::Track::Type::Velo );
       SetFlagsAndPt( newTrack, m_ptVelo );
     }
 
@@ -140,7 +140,7 @@ public:
       auto state_endvelo = getState( fwdtrack, 1 );
       state_endvelo.setLocation( LHCb::State::Location::EndVelo );
       newTrack.addToStates( state_endvelo );
-      newTrack.setType( LHCb::Event::v2::Track::Type::Velo ); 
+      newTrack.setType( LHCb::Event::v2::Track::Type::Velo );
       SetFlagsAndPt( newTrack, m_ptVelo );
     }
 
@@ -151,7 +151,7 @@ public:
       auto state_beam = getState( bwdtrack, 0 );
       state_beam.setLocation( LHCb::State::Location::ClosestToBeam );
       newTrack.addToStates( state_beam );
-      newTrack.setType( LHCb::Event::v2::Track::Type::VeloBackward ); 
+      newTrack.setType( LHCb::Event::v2::Track::Type::VeloBackward );
       SetFlagsAndPt( newTrack, m_ptVelo );
     }
 
-- 
GitLab


From d989f39c145bb1cbd01b04d556847992c18a04dd Mon Sep 17 00:00:00 2001
From: Andrii Usachov <andrii.usachov@cern.ch>
Date: Wed, 21 Sep 2022 16:49:58 +0200
Subject: [PATCH 08/15] fix extrapolator for VeloBackward in MasterFitter, fix
 clone killers

---
 Tr/TrackFitter/src/TrackMasterFitter.h  |  2 +-
 Tr/TrackUtils/src/TrackCloneCleaner.cpp |  2 ++
 Tr/TrackUtils/src/TrackCloneKiller.cpp  | 11 +++++++++++
 3 files changed, 14 insertions(+), 1 deletion(-)

diff --git a/Tr/TrackFitter/src/TrackMasterFitter.h b/Tr/TrackFitter/src/TrackMasterFitter.h
index 9d47718ef85..f3c5cefc580 100644
--- a/Tr/TrackFitter/src/TrackMasterFitter.h
+++ b/Tr/TrackFitter/src/TrackMasterFitter.h
@@ -89,7 +89,7 @@ private:
   StatusCode updateTransport( LHCb::Track& track, IGeometryInfo const& geometry ) const;
 
   const ITrackExtrapolator* extrapolator( LHCb::Track::Types tracktype ) const {
-    if ( tracktype == LHCb::Track::Types::Velo ) return &( *m_veloExtrapolator );
+    if ( ( tracktype == LHCb::Track::Types::Velo ) || ( tracktype == LHCb::Track::Types::VeloBackward ) ) return &( *m_veloExtrapolator );
     return &( *m_extrapolator );
   }
 
diff --git a/Tr/TrackUtils/src/TrackCloneCleaner.cpp b/Tr/TrackUtils/src/TrackCloneCleaner.cpp
index 8dcd19e2832..0f80d2c47ec 100644
--- a/Tr/TrackUtils/src/TrackCloneCleaner.cpp
+++ b/Tr/TrackUtils/src/TrackCloneCleaner.cpp
@@ -73,6 +73,8 @@ namespace {
       return 3;
     case LHCb::Track::Types::Velo:
       return 4;
+    case LHCb::Track::Types::VeloBackward:
+      return 5;
     case LHCb::Track::Types::Muon:
       return 6;
     default:
diff --git a/Tr/TrackUtils/src/TrackCloneKiller.cpp b/Tr/TrackUtils/src/TrackCloneKiller.cpp
index 0f973a24fb7..30056eb6322 100644
--- a/Tr/TrackUtils/src/TrackCloneKiller.cpp
+++ b/Tr/TrackUtils/src/TrackCloneKiller.cpp
@@ -298,6 +298,13 @@ bool TrackCloneKiller::areClones( const TrackData& it, const TrackData& jt ) con
   case to_index( LHCb::Track::Types::Upstream, LHCb::Track::Types::Velo ):
   case to_index( LHCb::Track::Types::Velo, LHCb::Track::Types::Upstream ):
   case to_index( LHCb::Track::Types::Velo, LHCb::Track::Types::Velo ):
+  case to_index( LHCb::Track::Types::Long, LHCb::Track::Types::VeloBackward ):
+  case to_index( LHCb::Track::Types::VeloBackward, LHCb::Track::Types::Long ):
+  case to_index( LHCb::Track::Types::Upstream, LHCb::Track::Types::VeloBackward ):
+  case to_index( LHCb::Track::Types::VeloBackward, LHCb::Track::Types::Upstream ):
+  case to_index( LHCb::Track::Types::VeloBackward, LHCb::Track::Types::VeloBackward ):
+  case to_index( LHCb::Track::Types::Velo, LHCb::Track::Types::VeloBackward ):
+  case to_index( LHCb::Track::Types::VeloBackward, LHCb::Track::Types::Velo ):
     return veloOrClones( it, jt );
   case to_index( LHCb::Track::Types::Long, LHCb::Track::Types::Ttrack ):
   case to_index( LHCb::Track::Types::Ttrack, LHCb::Track::Types::Long ):
@@ -311,6 +318,10 @@ bool TrackCloneKiller::areClones( const TrackData& it, const TrackData& jt ) con
   case to_index( LHCb::Track::Types::Velo, LHCb::Track::Types::Ttrack ):
   case to_index( LHCb::Track::Types::Downstream, LHCb::Track::Types::Velo ):
   case to_index( LHCb::Track::Types::Velo, LHCb::Track::Types::Downstream ):
+  case to_index( LHCb::Track::Types::Ttrack, LHCb::Track::Types::VeloBackward ):
+  case to_index( LHCb::Track::Types::VeloBackward, LHCb::Track::Types::Ttrack ):
+  case to_index( LHCb::Track::Types::Downstream, LHCb::Track::Types::VeloBackward ):
+  case to_index( LHCb::Track::Types::VeloBackward, LHCb::Track::Types::Downstream ):
   case to_index( LHCb::Track::Types::Downstream, LHCb::Track::Types::Upstream ):
   case to_index( LHCb::Track::Types::Upstream, LHCb::Track::Types::Downstream ):
     break;
-- 
GitLab


From c606b37292523258a9ee3ef75b11a0c5e9cc4a0a Mon Sep 17 00:00:00 2001
From: Gitlab CI <noreply@cern.ch>
Date: Wed, 21 Sep 2022 14:50:40 +0000
Subject: [PATCH 09/15] Fixed formatting

patch generated by https://gitlab.cern.ch/lhcb/Rec/-/jobs/24694825
---
 Tr/TrackFitter/src/TrackMasterFitter.h | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/Tr/TrackFitter/src/TrackMasterFitter.h b/Tr/TrackFitter/src/TrackMasterFitter.h
index f3c5cefc580..bff0b0248e7 100644
--- a/Tr/TrackFitter/src/TrackMasterFitter.h
+++ b/Tr/TrackFitter/src/TrackMasterFitter.h
@@ -89,7 +89,8 @@ private:
   StatusCode updateTransport( LHCb::Track& track, IGeometryInfo const& geometry ) const;
 
   const ITrackExtrapolator* extrapolator( LHCb::Track::Types tracktype ) const {
-    if ( ( tracktype == LHCb::Track::Types::Velo ) || ( tracktype == LHCb::Track::Types::VeloBackward ) ) return &( *m_veloExtrapolator );
+    if ( ( tracktype == LHCb::Track::Types::Velo ) || ( tracktype == LHCb::Track::Types::VeloBackward ) )
+      return &( *m_veloExtrapolator );
     return &( *m_extrapolator );
   }
 
-- 
GitLab


From 4d9a40c815484c7b34a86aa7747e61680cf7f4fd Mon Sep 17 00:00:00 2001
From: Andrii Usachov <andrii.usachov@cern.ch>
Date: Mon, 26 Sep 2022 15:26:15 +0200
Subject: [PATCH 10/15] fix conflict

---
 Tr/TrackUtils/src/TrackBestTrackCreator.cpp | 9 +++++++--
 1 file changed, 7 insertions(+), 2 deletions(-)

diff --git a/Tr/TrackUtils/src/TrackBestTrackCreator.cpp b/Tr/TrackUtils/src/TrackBestTrackCreator.cpp
index b8fb21f77cc..c269acca4ff 100644
--- a/Tr/TrackUtils/src/TrackBestTrackCreator.cpp
+++ b/Tr/TrackUtils/src/TrackBestTrackCreator.cpp
@@ -115,8 +115,13 @@ namespace LHCb {
           m_counters.emplace_back( owner, toString( static_cast<Type>( itype ) ) + "Backward." + tag );
         }
       }
-    }
-    CounterType& operator()( LHCb::Track::Types type ) { return m_counters[static_cast<int>( type )]; }
+      CounterType& operator()( LHCb::Track::Types type ) { return m_counters[static_cast<int>( type )]; }
+      
+    private:
+      // the actual counters
+      std::deque<CounterType> m_counters;
+    };
+
 
   private:
     ToolHandle<ITrackFitter>      m_fitter{this, "Fitter", "TrackMasterFitter"};
-- 
GitLab


From b498d1dd40b3e87bd5ca90b299a27d45ac708d9e Mon Sep 17 00:00:00 2001
From: Gitlab CI <noreply@cern.ch>
Date: Mon, 26 Sep 2022 13:26:48 +0000
Subject: [PATCH 11/15] Fixed formatting

patch generated by https://gitlab.cern.ch/lhcb/Rec/-/jobs/24784877
---
 .../src/TrackMaterialParametrizer.cpp         | 29 +++++++++----------
 Tr/TrackUtils/src/TrackBestTrackCreator.cpp   |  3 +-
 2 files changed, 15 insertions(+), 17 deletions(-)

diff --git a/Tr/TrackTools/src/TrackMaterialParametrizer.cpp b/Tr/TrackTools/src/TrackMaterialParametrizer.cpp
index e67e1c1f632..a11687f77aa 100644
--- a/Tr/TrackTools/src/TrackMaterialParametrizer.cpp
+++ b/Tr/TrackTools/src/TrackMaterialParametrizer.cpp
@@ -55,7 +55,7 @@ public:
 private:
   Gaudi::Property<std::string>   m_tracksInContainer{this, "TracksInContainer",
                                                    LHCb::TrackLocation::Default}; ///< Input Tracks container location
-  Gaudi::Property<bool>          m_printIntersect{this, "PrintIntersections", false };
+  Gaudi::Property<bool>          m_printIntersect{this, "PrintIntersections", false};
   ToolHandle<ITrackExtrapolator> m_extrapolator    = {"TrackMasterExtrapolator"};
   ToolHandle<IMaterialLocator>   m_materiallocator = {"DetailedMaterialLocator"};
 };
@@ -148,8 +148,7 @@ namespace {
       // Check measurement type compatible with 2D measurements
       rc = node.measurement().visit(
           []( LHCb::Measurement::FT const& ) { return FTHit; }, []( LHCb::Measurement::VP const& ) { return VPHit; },
-          []( LHCb::Measurement::VP2D const& ) { return VPHit; },
-          []( LHCb::Measurement::UT const& ) { return UTHit; },
+          []( LHCb::Measurement::VP2D const& ) { return VPHit; }, []( LHCb::Measurement::UT const& ) { return UTHit; },
           []( LHCb::Measurement::Muon const& ) { return MuonHit; },
           [&]( ... ) {
             std::cout << "Unknown node type for measurement: " << node.measurement().type() << std::endl;
@@ -199,11 +198,10 @@ StatusCode TrackMaterialParametrizer::execute() {
     for ( const auto& is : fitresult->intersections() ) {
       const auto radthickness = std::abs( is.z2 - is.z1 ) / is.material->radiationLength();
       // Print intersections
-      if ( m_printIntersect.value() &&
-          std::min( is.z1, is.z2 ) < StateParameters::ZBegRich1 && radthickness > 0.01
-          // && is.material->name() != std::string("Air")
-          // && std::max( is.z1,is.z2 ) > StateParameters::ZEndVelo
-          ) {
+      if ( m_printIntersect.value() && std::min( is.z1, is.z2 ) < StateParameters::ZBegRich1 && radthickness > 0.01
+           // && is.material->name() != std::string("Air")
+           // && std::max( is.z1,is.z2 ) > StateParameters::ZEndVelo
+      ) {
         auto state = tracktraj.stateVector( 0.5 * ( is.z1 + is.z2 ) );
         std::cout << "intersect: "
                   << "z1= " << std::setprecision( 1 ) << std::fixed << is.z1 << "; z2= " << is.z2
@@ -217,7 +215,7 @@ StatusCode TrackMaterialParametrizer::execute() {
         auto state = tracktraj.stateVector( 0.5 * ( is.z1 + is.z2 ) );
         profile2D( state.x(), state.y(), std::abs( is.z2 - is.z1 ), "aluthicknessvsxy", -50, 50, -50, 50, 100, 100 );
         profile2D( state.y() + state.x(), state.y() - state.x(), std::abs( is.z2 - is.z1 ), "aluthicknessvsxyrotated",
-                  -50, 50, -50, 50, 100, 100 );
+                   -50, 50, -50, 50, 100, 100 );
       }
     }
     // let's loop over the nodes
@@ -262,7 +260,7 @@ StatusCode TrackMaterialParametrizer::execute() {
         plot1D( std::sqrt( Q( 3, 3 ) / covtyty ), "velostynorm", 0, xmax, nbins );
         profile2D( state.x(), state.y(), std::sqrt( Q( 2, 2 ) / covtxtx ), "velostxnormvsxy", -50, 50, -50, 50, 100,
                    100 );
-      // Special histograms for VPHit to ClosestToBeam transitions
+        // Special histograms for VPHit to ClosestToBeam transitions
       } else if ( prevnode && nodetype( *prevnode ) == VPHit && nodetype( *node ) == ClosestToBeam ) {
         plot1D( std::sqrt( Q( 2, 2 ) / covtxtx ), "velostxnormBL", 0, xmax, nbins );
         plot1D( Q( 3, 2 ) / covtxty, "velostxynormBL", 0, xmax, nbins );
@@ -281,7 +279,8 @@ StatusCode TrackMaterialParametrizer::execute() {
       }
 
       // Skip node pairs with small z position difference.
-      // Note that with 1D Velo measurements, we have two separate nodes at the same z and there's no material noise between those.
+      // Note that with 1D Velo measurements, we have two separate nodes at the same z and there's no material noise
+      // between those.
       if ( prevnode && std::abs( node->z() - prevnode->z() ) > 0.5 && covtxtx > 0 ) {
         bool infoil = false;
         if ( nodetype( *node ) == VPHit && nodetype( *prevnode ) == VPHit ) {
@@ -294,8 +293,8 @@ StatusCode TrackMaterialParametrizer::execute() {
           const auto yprime = y - x;
           infoil = ( yprime > -15 && xprime >= 0 && xprime < 15 ) || ( yprime < 15 && xprime > -15 && xprime <= 0 );
         }
-        // Prepare folder names for all transitions. For VPHit-VPHit transition we add Foil suffix if the node is within RF foil.
-        // This way we divide VPHit to VPHit transitions in two categories.
+        // Prepare folder names for all transitions. For VPHit-VPHit transition we add Foil suffix if the node is within
+        // RF foil. This way we divide VPHit to VPHit transitions in two categories.
         const std::string foilfix = infoil ? "Foil" : "";
         const std::string prefix =
             nodeTypeToString( nodetype( *prevnode ) ) + nodeTypeToString( nodetype( *node ) ) + foilfix + "/";
@@ -385,7 +384,7 @@ StatusCode TrackMaterialParametrizer::execute() {
     }
   }
 
-  //Tuple theTuple = nTuple( "scattertuple", "", CLID_ColumnWiseTuple );
-  //theTuple->write().ignore();
+  // Tuple theTuple = nTuple( "scattertuple", "", CLID_ColumnWiseTuple );
+  // theTuple->write().ignore();
   return StatusCode::SUCCESS;
 }
diff --git a/Tr/TrackUtils/src/TrackBestTrackCreator.cpp b/Tr/TrackUtils/src/TrackBestTrackCreator.cpp
index c269acca4ff..f31ba50cc65 100644
--- a/Tr/TrackUtils/src/TrackBestTrackCreator.cpp
+++ b/Tr/TrackUtils/src/TrackBestTrackCreator.cpp
@@ -116,13 +116,12 @@ namespace LHCb {
         }
       }
       CounterType& operator()( LHCb::Track::Types type ) { return m_counters[static_cast<int>( type )]; }
-      
+
     private:
       // the actual counters
       std::deque<CounterType> m_counters;
     };
 
-
   private:
     ToolHandle<ITrackFitter>      m_fitter{this, "Fitter", "TrackMasterFitter"};
     ToolHandle<IGhostProbability> m_ghostTool{this, "GhostIdTool", "UpgradeGhostId"};
-- 
GitLab


From 17a834010451c6479b6e1d480e572f41fb2d3112 Mon Sep 17 00:00:00 2001
From: Andrii Usachov <andrii.usachov@cern.ch>
Date: Mon, 26 Sep 2022 15:31:29 +0200
Subject: [PATCH 12/15] rm TrackMaterialParametrizer added by accident

---
 .../src/TrackMaterialParametrizer.cpp         | 390 ------------------
 1 file changed, 390 deletions(-)
 delete mode 100644 Tr/TrackTools/src/TrackMaterialParametrizer.cpp

diff --git a/Tr/TrackTools/src/TrackMaterialParametrizer.cpp b/Tr/TrackTools/src/TrackMaterialParametrizer.cpp
deleted file mode 100644
index a11687f77aa..00000000000
--- a/Tr/TrackTools/src/TrackMaterialParametrizer.cpp
+++ /dev/null
@@ -1,390 +0,0 @@
-/*****************************************************************************\
-* (c) Copyright 2000-2019 CERN for the benefit of the LHCb Collaboration      *
-*                                                                             *
-* This software is distributed under the terms of the GNU General Public      *
-* Licence version 3 (GPL Version 3), copied verbatim in the file "COPYING".   *
-*                                                                             *
-* In applying this licence, CERN does not waive the privileges and immunities *
-* granted to it by virtue of its status as an Intergovernmental Organization  *
-* or submit itself to any jurisdiction.                                       *
-\*****************************************************************************/
-// Include files
-
-// from Gaudi
-#include "GaudiAlg/GaudiTupleAlg.h"
-#include "GaudiKernel/ToolHandle.h"
-
-#include "Event/FitNode.h"
-#include "Event/KalmanFitResult.h"
-#include "Event/Measurement.h"
-#include "Event/StateParameters.h"
-#include "TrackInterfaces/IMaterialLocator.h"
-#include "TrackInterfaces/ITrackExtrapolator.h"
-#include "TrackKernel/CubicStateInterpolationTraj.h"
-#include "TrackKernel/TrackTraj.h"
-
-#include "DetDesc/Material.h"
-
-// from Event/LinkerEvent
-#include "Linker/LinkedFrom.h"
-
-// from Event/TrackEvent
-#include "Event/Track.h"
-
-// from Event/MCEvent
-#include "Event/MCHit.h"
-#include "Event/MCParticle.h"
-
-using namespace LHCb::Event::v1;
-
-class TrackMaterialParametrizer : public GaudiTupleAlg {
-
-public:
-  /** Standard construtor */
-  using GaudiTupleAlg::GaudiTupleAlg;
-
-  /** Algorithm execute */
-  StatusCode execute() override;
-
-  /** Algorithm initialize */
-  StatusCode initialize() override;
-
-  /** Algorithm initialize */
-  StatusCode finalize() override;
-
-private:
-  Gaudi::Property<std::string>   m_tracksInContainer{this, "TracksInContainer",
-                                                   LHCb::TrackLocation::Default}; ///< Input Tracks container location
-  Gaudi::Property<bool>          m_printIntersect{this, "PrintIntersections", false};
-  ToolHandle<ITrackExtrapolator> m_extrapolator    = {"TrackMasterExtrapolator"};
-  ToolHandle<IMaterialLocator>   m_materiallocator = {"DetailedMaterialLocator"};
-};
-
-DECLARE_COMPONENT( TrackMaterialParametrizer )
-
-StatusCode TrackMaterialParametrizer::initialize() {
-  StatusCode sc = GaudiTupleAlg::initialize();
-  if ( sc.isSuccess() ) sc = m_extrapolator.retrieve();
-  if ( sc.isSuccess() ) sc = m_materiallocator.retrieve();
-  setHistoTopDir( "Track/" );
-  return sc;
-}
-
-StatusCode TrackMaterialParametrizer::finalize() {
-  m_extrapolator.release().ignore();
-  m_materiallocator.release().ignore();
-  return GaudiTupleAlg::finalize();
-}
-
-//=============================================================================
-// Main execution
-//=============================================================================
-namespace {
-  enum NodeType {
-    VPHit,
-    UTHit,
-    FTHit,
-    ClosestToBeam,
-    EndVelo,
-    BegRich1,
-    EndRich1,
-    AtT,
-    BegRich2,
-    EndRich2,
-    MuonHit,
-    RefNode,
-    HitNode,
-    NTypes
-  };
-
-  std::string nodeTypeToString( NodeType node ) {
-    switch ( node ) {
-    case VPHit:
-      return "VPHit";
-      break;
-    case UTHit:
-      return "UTHit";
-      break;
-    case FTHit:
-      return "FTHit";
-      break;
-    case MuonHit:
-      return "MuonHit";
-      break;
-    case ClosestToBeam:
-      return "ClosestToBeam";
-      break;
-    case EndVelo:
-      return "EndVelo";
-      break;
-    case BegRich1:
-      return "BegRich1";
-      break;
-    case EndRich1:
-      return "EndRich1";
-      break;
-    case BegRich2:
-      return "BegRich2";
-      break;
-    case EndRich2:
-      return "EndRich2";
-      break;
-    case AtT:
-      return "AtT";
-      break;
-    case RefNode:
-      return "RefNode";
-    case HitNode:
-      return "HitNode";
-    case NTypes:
-      return "Unknown";
-    }
-    return "Unknown";
-  }
-
-  NodeType nodetype( const LHCb::FitNode& node ) {
-    NodeType rc = NTypes;
-    if ( node.hasMeasurement() ) {
-      // Check measurement type compatible with 2D measurements
-      rc = node.measurement().visit(
-          []( LHCb::Measurement::FT const& ) { return FTHit; }, []( LHCb::Measurement::VP const& ) { return VPHit; },
-          []( LHCb::Measurement::VP2D const& ) { return VPHit; }, []( LHCb::Measurement::UT const& ) { return UTHit; },
-          []( LHCb::Measurement::Muon const& ) { return MuonHit; },
-          [&]( ... ) {
-            std::cout << "Unknown node type for measurement: " << node.measurement().type() << std::endl;
-            return HitNode;
-          } );
-    } else {
-      switch ( node.state().location() ) {
-      case LHCb::State::ClosestToBeam:
-        rc = ClosestToBeam;
-        break;
-      case LHCb::State::EndVelo:
-        rc = EndVelo;
-        break;
-      case LHCb::State::BegRich1:
-        rc = BegRich1;
-        break;
-      case LHCb::State::EndRich1:
-        rc = EndRich1;
-        break;
-      case LHCb::State::BegRich2:
-        rc = BegRich2;
-        break;
-      case LHCb::State::EndRich2:
-        rc = EndRich2;
-        break;
-      case LHCb::State::AtT:
-        rc = AtT;
-        break;
-      default:
-        rc = RefNode;
-        std::cout << "Unknown reference node type: " << node.state().location() << std::endl;
-      }
-    }
-    return rc;
-  }
-} // namespace
-
-StatusCode TrackMaterialParametrizer::execute() {
-  // Get the Tracks
-  Track::Range tracks = get<Track::Range>( m_tracksInContainer );
-
-  // Loop over the nodes and fill some histograms
-  for ( const auto& trk : tracks ) {
-    auto fitresult = dynamic_cast<const LHCb::KalmanFitResult*>( trk->fitResult() );
-    if ( !fitresult || fitresult->nodes().empty() ) continue;
-    LHCb::TrackTraj tracktraj( {fitresult->nodes().data(), fitresult->nodes().size()} );
-    for ( const auto& is : fitresult->intersections() ) {
-      const auto radthickness = std::abs( is.z2 - is.z1 ) / is.material->radiationLength();
-      // Print intersections
-      if ( m_printIntersect.value() && std::min( is.z1, is.z2 ) < StateParameters::ZBegRich1 && radthickness > 0.01
-           // && is.material->name() != std::string("Air")
-           // && std::max( is.z1,is.z2 ) > StateParameters::ZEndVelo
-      ) {
-        auto state = tracktraj.stateVector( 0.5 * ( is.z1 + is.z2 ) );
-        std::cout << "intersect: "
-                  << "z1= " << std::setprecision( 1 ) << std::fixed << is.z1 << "; z2= " << is.z2
-                  << "; dz= " << std::abs( is.z2 - is.z1 ) << "; (x,y)_mid=(" << state.x() << "," << state.y() << ")"
-                  << "; Z= " << std::setw( 4 ) << is.material->Z() << "; name= " << std::setw( 10 )
-                  << is.material->name() << "; radthickness= " << std::scientific << radthickness << std::endl;
-      }
-      // Map intersections with aluminium (RF foil)
-      if ( is.material->Z() == 13 ) {
-        // find out at which x,y position this is?
-        auto state = tracktraj.stateVector( 0.5 * ( is.z1 + is.z2 ) );
-        profile2D( state.x(), state.y(), std::abs( is.z2 - is.z1 ), "aluthicknessvsxy", -50, 50, -50, 50, 100, 100 );
-        profile2D( state.y() + state.x(), state.y() - state.x(), std::abs( is.z2 - is.z1 ), "aluthicknessvsxyrotated",
-                   -50, 50, -50, 50, 100, 100 );
-      }
-    }
-    // let's loop over the nodes
-    for ( const auto& node : fitresult->nodes() ) {
-      // Get the noise matrix. This is the noise between this node and the previous node. it is added to prediction
-      // after propagation:
-      //  C_{k,k-1} = F_k C_{k-1} F_k + Qk
-      const auto& Q = node->noiseMatrix();
-
-      // Get the reference state.
-      const auto& state = node->refVector();
-
-      // Get the scattering momentum.
-      const auto pscatter = fitresult->pScatter();
-
-      // let's complete the correction for a thin scatterer, then use
-      // that to take the known effects out of the noise.
-      const auto   tx      = state.tx();
-      const auto   ty      = state.ty();
-      const auto   tx2     = tx * tx;
-      const auto   ty2     = ty * ty;
-      const auto   n2      = 1 + tx2 + ty2;
-      const auto   n       = std::sqrt( n2 );
-      const auto   invp    = 1 / pscatter;
-      const auto   normCms = n * n2 * invp * invp;
-      const double covtxtx = ( 1 + tx2 ) * normCms;
-      const double covtyty = ( 1 + ty2 ) * normCms;
-      const double covtxty = tx * ty * normCms;
-
-      const auto prevnode = node->prevNode( LHCb::FitNode::Forward );
-      // std::cout << "Node: " << node->z() << " " << nodetype( *node ) << " " << node->state().location() << std::endl;
-      // std::cout << "Prev node: " << " " << node->z() << " " << nodetype( *node ) << std::endl ;
-
-      const double xmax  = 4;
-      const int    nbins = 200;
-      // Special histograms for all VPHit to VPHit transitions
-      // Later we divide VPHit-VPHit transitions based on whether they pass through RF foil
-      if ( prevnode && nodetype( *node ) == VPHit && nodetype( *prevnode ) == VPHit &&
-           std::abs( prevnode->z() - node->z() ) > 1 ) {
-        plot1D( std::sqrt( Q( 2, 2 ) / covtxtx ), "velostxnorm", 0, xmax, nbins );
-        plot1D( Q( 3, 2 ) / covtxty, "velostxynorm", 0, xmax, nbins );
-        plot1D( std::sqrt( Q( 3, 3 ) / covtyty ), "velostynorm", 0, xmax, nbins );
-        profile2D( state.x(), state.y(), std::sqrt( Q( 2, 2 ) / covtxtx ), "velostxnormvsxy", -50, 50, -50, 50, 100,
-                   100 );
-        // Special histograms for VPHit to ClosestToBeam transitions
-      } else if ( prevnode && nodetype( *prevnode ) == VPHit && nodetype( *node ) == ClosestToBeam ) {
-        plot1D( std::sqrt( Q( 2, 2 ) / covtxtx ), "velostxnormBL", 0, xmax, nbins );
-        plot1D( Q( 3, 2 ) / covtxty, "velostxynormBL", 0, xmax, nbins );
-        plot1D( std::sqrt( Q( 3, 3 ) / covtyty ), "velostynormBL", 0, xmax, nbins );
-        profile2D( state.x(), state.y(), std::sqrt( Q( 2, 2 ) / covtxtx ), "velostxnormvsxyBL", -50, 50, -50, 50, 100,
-                   100 );
-        // we also make an alternative norm: assume that this is a
-        // thick scatterer and divide by z. perhaps we better treat
-        // the RF foil as a thick one, but we may also have to treat
-        // it as a fixed diameter cylinder. (some profile plots
-        // would help)
-        const double dz = prevnode->z() - node->z();
-        plot1D( std::sqrt( Q( 2, 2 ) / covtxtx / dz ), "velostxLnormBL", 0, 1, nbins );
-        plot1D( Q( 3, 2 ) / covtxty / dz, "velostxyLnormBL", 0, 1, nbins );
-        plot1D( std::sqrt( Q( 3, 3 ) / covtyty / dz ), "velostyLnormBL", 0, 1, nbins );
-      }
-
-      // Skip node pairs with small z position difference.
-      // Note that with 1D Velo measurements, we have two separate nodes at the same z and there's no material noise
-      // between those.
-      if ( prevnode && std::abs( node->z() - prevnode->z() ) > 0.5 && covtxtx > 0 ) {
-        bool infoil = false;
-        if ( nodetype( *node ) == VPHit && nodetype( *prevnode ) == VPHit ) {
-          // Check whether the Velo node is already inside rf foil.
-          // Remember that the previous node is more downstream
-          // as we are now parametrizing for fit in upstream direction.
-          const auto x      = state.x();
-          const auto y      = state.y();
-          const auto xprime = y + x;
-          const auto yprime = y - x;
-          infoil = ( yprime > -15 && xprime >= 0 && xprime < 15 ) || ( yprime < 15 && xprime > -15 && xprime <= 0 );
-        }
-        // Prepare folder names for all transitions. For VPHit-VPHit transition we add Foil suffix if the node is within
-        // RF foil. This way we divide VPHit to VPHit transitions in two categories.
-        const std::string foilfix = infoil ? "Foil" : "";
-        const std::string prefix =
-            nodeTypeToString( nodetype( *prevnode ) ) + nodeTypeToString( nodetype( *node ) ) + foilfix + "/";
-
-        // std::cout << node->state().location() << " "
-        // 	  << node->z() << " " << nodetype(*prevnode) << " " << nodetype(*node) << " " << prefix << std::endl ;
-        const auto dz   = node->z() - prevnode->z();
-        const auto xmax = 20.;
-        // std::cout << "delta-z: "
-        // 	  << dz << " "
-        // 	  << node->transportMatrix()(2,0) << " "
-        // 	  << node->transportMatrix()(0,2) << std::endl ;
-
-        // Make histograms for scattering parameters
-        const double reldzxx  = std::sqrt( Q( 0, 0 ) / Q( 2, 2 ) ) / std::abs( dz );
-        const double reldzxtx = Q( 2, 0 ) / Q( 2, 2 ) / dz;
-        plot1D( reldzxx, prefix + "reldzxx", "reldzxx", 0, 1, nbins );
-        plot1D( reldzxtx, prefix + "reldzxtx", "reldzxtx", 0, 1, nbins );
-        plot1D( std::sqrt( Q( 2, 2 ) / covtxtx ), prefix + "stxnorm", "stxnorm", 0., xmax, nbins );
-
-        // Make histograms for other interesting quantities that tell something
-        // about material and scattering
-        plot1D( Q( 3, 2 ) / covtxty, prefix + "stxynorm", "stxynorm", 0., xmax, nbins );
-        plot1D( std::sqrt( Q( 3, 3 ) / covtyty ), prefix + "stynorm", "stynorm", 0., xmax, nbins );
-        plot1D( std::sqrt( Q( 0, 0 ) / Q( 2, 2 ) ), prefix + "effectivedz", "effectivedz", 0, 400, nbins );
-        plot1D( Q( 2, 0 ) * Q( 2, 0 ) / ( Q( 2, 2 ) * Q( 0, 0 ) ), prefix + "thicknessy", "thicknessy", 0, 1, nbins );
-
-        const float zav     = 0.5 * ( node->z() + prevnode->z() );
-        const float thexmax = std::max( 0.3 * zav, 50. );
-
-        profile2D( state.x(), state.y(), std::sqrt( Q( 2, 2 ) / covtxtx ), prefix + "stxnormvsxy", "stxnormvsxy",
-                   -thexmax, thexmax, -thexmax, thexmax, 100, 100 );
-        profile2D( tx, ty, std::sqrt( Q( 2, 2 ) / covtxtx ), prefix + "stxnormvstxtynarrow", "stxnormvstxty", -0.05,
-                   0.05, -0.05, 0.05, 100, 100 );
-        profile2D( tx, ty, std::sqrt( Q( 2, 2 ) / covtxtx ), prefix + "stxnormvstxty", "stxnormvstxty", -0.4, 0.4, -0.4,
-                   0.4, 100, 100 );
-
-        const double eta = -std::log( std::tan( 0.5 * std::atan( std::sqrt( tx2 + ty2 ) ) ) );
-        // const double eta = state.momentum().PseudoRapidity() ;
-        const double relnoise2 = Q( 2, 2 ) / covtxtx;
-        const double relnoise  = std::sqrt( relnoise2 );
-        const double dE        = std::abs( 1 / node->state().qOverP() ) - std::abs( 1 / prevnode->state().qOverP() );
-
-        // Make some more profile plots
-        if ( relnoise < 50.0 ) {
-          const double t = std::sqrt( tx2 + ty2 );
-          profile1D( eta, relnoise, prefix + "stxnormvseta", "stxnormvseta", 1., 7., 100 );
-          profile1D( t, relnoise, prefix + "stxnormvst", "stxnormvst", 0, 0.4 );
-
-          profile1D( t, relnoise2, prefix + "stxnorm2vst", "stxnorm2vst", 0, 0.4, 40 );
-          profile1D( t, reldzxx, prefix + "reldzxxvst", "reldzxxvst", 0, 0.4, 40 );
-          profile1D( t, reldzxtx, prefix + "reldzxtxvst", "reldzxtxvst", 0, 0.4, 40 );
-          profile1D( t, dE / n, prefix + "dEvst", "dEvst", 0, 0.4, 40 );
-
-          const double R1 = std::sqrt( state.x() * state.x() + state.y() * state.y() );
-          profile1D( R1, relnoise, prefix + "stxnormvsR1", "stxnormvsR1", 0., 100., 100 );
-          const auto   prevstate = prevnode->state();
-          const double R2        = std::sqrt( prevstate.x() * prevstate.x() + prevstate.y() * prevstate.y() );
-          profile1D( log( R2 ) / log( 10 ), relnoise, prefix + "stxnormvsR2", "stxnormvsR2", 0., 4., 100 );
-        }
-
-        // also add energy loss (divided by wall thickness)
-        plot1D( dE / n, prefix + "normdE", "normdE", 0., 100., 10 * nbins );
-
-        // Wouter's notes:
-
-        // we still miss:
-        // - module support/cooling block: very visible between last velo-hit and end-velo
-        // - heavy material close to beam pipe, especially between endvelo and end rich
-        // - there is a very big object in the middle of UT.
-        //   the AtT-EndRich1 step now accounts for this because most tracks that go through UT actually have UT hits.
-        //   We need to find a different solution here.
-
-        // to be added volumes:
-        // * VP->EndVelo: between 30 and 50 mm in R is very much
-        // heavier. should be easy to add. there are basically no tracks
-        // above 50, which really surprises me ... WARNING: we see the R of the most upstream part. that explains.
-        // indeed the material is at LOW angles: we go through the support material of other modules.
-        // * EndVelo->BegRich1: 20<R<45 (but there is basically nothing below 20)
-        // * EndRich1-BegRich1: narrow thing between 25<R<30; probably narrower in angle (4.2<eta<4.5)
-        // AtT-UTHit: heavy for R<50 (eta>5)
-        // surprising: nothing between UT-EndRich1: probably because UT hits are outside beampipe
-        // but: you do see it in AtT->EndRich1 (no UT hits): something
-        // heavy for R<50 (5<eta) note that this is at larger angle
-        // than in Rich1 itself.
-      }
-    }
-  }
-
-  // Tuple theTuple = nTuple( "scattertuple", "", CLID_ColumnWiseTuple );
-  // theTuple->write().ignore();
-  return StatusCode::SUCCESS;
-}
-- 
GitLab


From 7110be1c3130666e6e27901cc371f1614e32b6af Mon Sep 17 00:00:00 2001
From: Andrii Usachov <andrii.usachov@cern.ch>
Date: Wed, 12 Oct 2022 17:29:08 +0200
Subject: [PATCH 13/15] clean up

---
 Tr/TrackUtils/src/TrackBestTrackCreator.cpp | 3 ---
 1 file changed, 3 deletions(-)

diff --git a/Tr/TrackUtils/src/TrackBestTrackCreator.cpp b/Tr/TrackUtils/src/TrackBestTrackCreator.cpp
index f31ba50cc65..8b8345b70bd 100644
--- a/Tr/TrackUtils/src/TrackBestTrackCreator.cpp
+++ b/Tr/TrackUtils/src/TrackBestTrackCreator.cpp
@@ -111,9 +111,6 @@ namespace LHCb {
         for ( auto itype{0}; itype < ilast; ++itype ) {
           m_counters.emplace_back( owner, toString( static_cast<Type>( itype ) ) + "." + tag );
         }
-        for ( auto itype{0}; itype < ilast; ++itype ) {
-          m_counters.emplace_back( owner, toString( static_cast<Type>( itype ) ) + "Backward." + tag );
-        }
       }
       CounterType& operator()( LHCb::Track::Types type ) { return m_counters[static_cast<int>( type )]; }
 
-- 
GitLab


From b0c4103c3dd0989e5f8cd8132d82b65feff94ae8 Mon Sep 17 00:00:00 2001
From: Andrii Usachov <andrii.usachov@cern.ch>
Date: Wed, 12 Oct 2022 17:54:16 +0200
Subject: [PATCH 14/15] use VeloBackward type in TrackSelector options

---
 Phys/JetAccessories/python/JetAccessories/HltJetConf.py         | 2 +-
 .../python/JetAccessories/OldParticleFlow_Config.py             | 2 +-
 .../JetAccessories/python/JetAccessories/ParticleFlow_Config.py | 2 +-
 3 files changed, 3 insertions(+), 3 deletions(-)

diff --git a/Phys/JetAccessories/python/JetAccessories/HltJetConf.py b/Phys/JetAccessories/python/JetAccessories/HltJetConf.py
index 33c6d176fd2..dcaea840be3 100644
--- a/Phys/JetAccessories/python/JetAccessories/HltJetConf.py
+++ b/Phys/JetAccessories/python/JetAccessories/HltJetConf.py
@@ -150,7 +150,7 @@ class HltParticleFlowConf(object):
         protos.Inputs = ["Rec/Track/Best"]
         protos.Output = "Rec/ProtoP/VeloProtoPMaker"
         protos.addTool(DelegatingTrackSelector, name="TrackSelector")
-        protos.TrackSelector.TrackTypes = ["Velo"]
+        protos.TrackSelector.TrackTypes = ["Velo", "VeloBackward"]
         self.seq.Members += [protos]
         return protos.Output
 
diff --git a/Phys/JetAccessories/python/JetAccessories/OldParticleFlow_Config.py b/Phys/JetAccessories/python/JetAccessories/OldParticleFlow_Config.py
index 38c9ce36c25..0b197d05b5a 100644
--- a/Phys/JetAccessories/python/JetAccessories/OldParticleFlow_Config.py
+++ b/Phys/JetAccessories/python/JetAccessories/OldParticleFlow_Config.py
@@ -198,7 +198,7 @@ class OldParticleFlowConf(object):
                 protos.Inputs = ["Rec/Track/Best"]
                 protos.Output = "Rec/ProtoP/VeloProtoPMaker"
                 protos.addTool(DelegatingTrackSelector, name="TrackSelector")
-                protos.TrackSelector.TrackTypes = ["Velo"]
+                protos.TrackSelector.TrackTypes = ["Velo", "VeloBackward"]
                 self.setupTypeTrackSelector("Velo", protos.TrackSelector,
                                             TrackCuts["Velo"])
                 self.algorithms.append(protos)
diff --git a/Phys/JetAccessories/python/JetAccessories/ParticleFlow_Config.py b/Phys/JetAccessories/python/JetAccessories/ParticleFlow_Config.py
index 2e4c56819bb..8502c81e3e7 100644
--- a/Phys/JetAccessories/python/JetAccessories/ParticleFlow_Config.py
+++ b/Phys/JetAccessories/python/JetAccessories/ParticleFlow_Config.py
@@ -199,7 +199,7 @@ class ParticleFlowConf(object):
                 protos.Inputs = ["Rec/Track/Best"]
                 protos.Output = "Rec/ProtoP/VeloProtoPMaker"
                 protos.addTool(DelegatingTrackSelector, name="TrackSelector")
-                protos.TrackSelector.TrackTypes = ["Velo"]
+                protos.TrackSelector.TrackTypes = ["Velo", "VeloBackward"]
                 self.setupTypeTrackSelector("Velo", protos.TrackSelector,
                                             TrackCuts["Velo"])
                 self.PFSeq.Members += [protos]
-- 
GitLab


From 722ca96a0d9112ea712951d8c22f06d87b8be56b Mon Sep 17 00:00:00 2001
From: Andrii Usachov <andrii.usachov@cern.ch>
Date: Thu, 13 Oct 2022 15:57:35 +0200
Subject: [PATCH 15/15] fix warning in TrackVertexMonitor

---
 Tr/TrackMonitors/src/TrackVertexMonitor.cpp | 7 -------
 1 file changed, 7 deletions(-)

diff --git a/Tr/TrackMonitors/src/TrackVertexMonitor.cpp b/Tr/TrackMonitors/src/TrackVertexMonitor.cpp
index a2bee75f446..5f934c1439d 100644
--- a/Tr/TrackMonitors/src/TrackVertexMonitor.cpp
+++ b/Tr/TrackMonitors/src/TrackVertexMonitor.cpp
@@ -241,13 +241,6 @@ namespace {
 
   auto TrackForwardPredicate = []() { return [=]( const LHCb::Track* track ) { return !track->isVeloBackward(); }; };
 
-  auto TrackFlagPredicate = []( LHCb::Track::Flags flag, bool positive ) {
-    return [=]( const LHCb::Track* track ) {
-      auto f = track->checkFlag( flag );
-      return positive ? f : !f;
-    };
-  };
-
   auto TrackVeloSidePredicate = []( int asign ) {
     // +1: left side only, 0: overlap track, -1: right side only
     // for asign > 0 select left-side tracks only, for a < 0 select right-side tracks, reject overlap tracks
-- 
GitLab