LCOV - code coverage report
Current view: top level - TRD/TRDbase - AliTRDtrackerV1.cxx (source / functions) Hit Total Coverage
Test: coverage.info Lines: 489 2130 23.0 %
Date: 2016-06-14 17:26:59 Functions: 28 78 35.9 %

          Line data    Source code
       1             : /**************************************************************************
       2             : * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
       3             : *                                                                        *
       4             : * Author: The ALICE Off-line Project.                                    *
       5             : * Contributors are mentioned in the code where appropriate.              *
       6             : *                                                                        *
       7             : * Permission to use, copy, modify and distribute this software and its   *
       8             : * documentation strictly for non-commercial purposes is hereby granted   *
       9             : * without fee, provided that the above copyright notice appears in all   *
      10             : * copies and that both the copyright notice and this permission notice   *
      11             : * appear in the supporting documentation. The authors make no claims     *
      12             : * about the suitability of this software for any purpose. It is          *
      13             : * provided "as is" without express or implied warranty.                  *
      14             : **************************************************************************/
      15             : 
      16             : /* $Id$ */
      17             : 
      18             : ///////////////////////////////////////////////////////////////////////////////
      19             : //                                                                           //
      20             : //  Track finder                                                             //
      21             : //                                                                           //
      22             : //  Authors:                                                                 //
      23             : //    Alex Bercuci <A.Bercuci@gsi.de>                                        //
      24             : //    Markus Fasel <M.Fasel@gsi.de>                                          //
      25             : //                                                                           //
      26             : ///////////////////////////////////////////////////////////////////////////////
      27             : 
      28             : #include <TBranch.h>
      29             : #include <TDirectory.h>
      30             : #include <TLinearFitter.h>
      31             : #include <TTree.h>  
      32             : #include <TClonesArray.h>
      33             : #include <TTreeStream.h>
      34             : #include <TGeoMatrix.h>
      35             : #include <TGeoManager.h>
      36             : 
      37             : #include "AliLog.h"
      38             : #include "AliMathBase.h"
      39             : #include "AliESDEvent.h"
      40             : #include "AliGeomManager.h"
      41             : #include "AliRieman.h"
      42             : #include "AliTrackPointArray.h"
      43             : 
      44             : #include "AliTRDgeometry.h"
      45             : #include "AliTRDpadPlane.h"
      46             : #include "AliTRDcalibDB.h"
      47             : #include "AliTRDReconstructor.h"
      48             : #include "AliTRDCalibraFillHisto.h"
      49             : #include "AliTRDrecoParam.h"
      50             : 
      51             : #include "AliTRDcluster.h" 
      52             : #include "AliTRDdigitsParam.h"
      53             : #include "AliTRDseedV1.h"
      54             : #include "AliTRDtrackV1.h"
      55             : #include "AliTRDtrackerV1.h"
      56             : #include "AliTRDtrackerDebug.h"
      57             : #include "AliTRDtrackingChamber.h"
      58             : #include "AliTRDchamberTimeBin.h"
      59             : 
      60          48 : ClassImp(AliTRDtrackerV1)
      61          48 : ClassImp(AliTRDtrackerV1::AliTRDLeastSquare)
      62          48 : ClassImp(AliTRDtrackerV1::AliTRDtrackFitterRieman)
      63             : 
      64             : AliTRDtrackerV1::ETRDtrackerV1BetheBloch AliTRDtrackerV1::fgBB = AliTRDtrackerV1::kGeant;
      65             : Double_t AliTRDtrackerV1::fgTopologicQA[kNConfigs] = {
      66             :   0.5112, 0.5112, 0.5112, 0.0786, 0.0786,
      67             :   0.0786, 0.0786, 0.0579, 0.0579, 0.0474,
      68             :   0.0474, 0.0408, 0.0335, 0.0335, 0.0335
      69             : };  
      70             : const Double_t AliTRDtrackerV1::fgkX0[kNPlanes]    = {
      71             :   300.2, 312.8, 325.4, 338.0, 350.6, 363.2};
      72             : // Number of Time Bins/chamber should be also stored independently by the traker
      73             : // (also in AliTRDReconstructor) in oder to be able to run HLT. Fix TODO
      74             : Int_t AliTRDtrackerV1::fgNTimeBins = 0;
      75             : AliRieman* AliTRDtrackerV1::fgRieman = NULL;
      76             : TLinearFitter* AliTRDtrackerV1::fgTiltedRieman = NULL;
      77             : TLinearFitter* AliTRDtrackerV1::fgTiltedRiemanConstrained = NULL;
      78             : 
      79             : //____________________________________________________________________
      80          74 : AliTRDtrackerV1::AliTRDtrackerV1(const AliTRDReconstructor *rec) 
      81           2 :   :AliTracker()
      82           2 :   ,fkReconstructor(NULL)
      83           2 :   ,fkRecoParam(NULL)
      84           2 :   ,fGeom(NULL)
      85           2 :   ,fClusters(NULL)
      86           2 :   ,fTracklets(NULL)
      87           2 :   ,fTracks(NULL)
      88           2 :   ,fTracksESD(NULL)
      89           2 :   ,fSieveSeeding(0)
      90           2 :   ,fEventInFile(-1)
      91          10 : {
      92             :   //
      93             :   // Default constructor.
      94             :   // 
      95             :   
      96           2 :   SetReconstructor(rec); // initialize reconstructor
      97             : 
      98             :   // initialize geometry
      99           2 :   if(!AliGeomManager::GetGeometry()){
     100           0 :     AliFatal("Could not get geometry.");
     101             :   }
     102           6 :   fGeom = new AliTRDgeometry();
     103           2 :   fGeom->CreateClusterMatrixArray();
     104             :   TGeoHMatrix *matrix = NULL;
     105           2 :   Double_t loc[] = {0., 0., 0.};
     106           2 :   Double_t glb[] = {0., 0., 0.};
     107          16 :   for(Int_t ily=kNPlanes; ily--;){
     108             :     Int_t ism = 0;
     109          48 :     while(!(matrix = fGeom->GetClusterMatrix(AliTRDgeometry::GetDetector(ily, 2, ism)))) ism++;
     110          12 :     if(!matrix){
     111           0 :       AliError(Form("Could not get transformation matrix for layer %d. Use default.", ily));
     112           0 :       fR[ily] = fgkX0[ily];
     113           0 :       continue;
     114             :     }
     115          12 :     matrix->LocalToMaster(loc, glb);
     116          12 :     fR[ily] = glb[0]+ AliTRDgeometry::AnodePos()-.5*AliTRDgeometry::AmThick() - AliTRDgeometry::DrThick();
     117          12 :   }
     118             : 
     119             :   // initialize cluster containers
     120         112 :   for (Int_t isector = 0; isector < AliTRDgeometry::kNsector; isector++) new(&fTrSec[isector]) AliTRDtrackingSector(fGeom, isector);
     121             :   
     122             :   // initialize arrays
     123           2 :   memset(fTrackQuality, 0, kMaxTracksStack*sizeof(Double_t));
     124           2 :   memset(fSeedLayer, 0, kMaxTracksStack*sizeof(Int_t));
     125           2 :   memset(fSeedTB, 0, kNSeedPlanes*sizeof(AliTRDchamberTimeBin*));
     126           6 :   fTracksESD = new TClonesArray("AliESDtrack", 2*kMaxTracksStack);
     127           2 :   fTracksESD->SetOwner();
     128           4 : }
     129             : 
     130             : //____________________________________________________________________
     131             : AliTRDtrackerV1::~AliTRDtrackerV1()
     132          12 : { 
     133             :   //
     134             :   // Destructor
     135             :   //
     136             : 
     137           4 :   if(fgRieman) delete fgRieman; fgRieman = NULL;
     138           4 :   if(fgTiltedRieman) delete fgTiltedRieman; fgTiltedRieman = NULL;
     139           4 :   if(fgTiltedRiemanConstrained) delete fgTiltedRiemanConstrained; fgTiltedRiemanConstrained = NULL;
     140          28 :   for(Int_t isl =0; isl<kNSeedPlanes; isl++) if(fSeedTB[isl]) delete fSeedTB[isl];
     141           8 :   if(fTracksESD){ fTracksESD->Delete(); delete fTracksESD; }
     142           2 :   if(fTracks) {fTracks->Delete(); delete fTracks;}
     143           8 :   if(fTracklets) {fTracklets->Delete(); delete fTracklets;}
     144           4 :   if(IsClustersOwner() && fClusters) {
     145           0 :     AliInfo(Form("tracker[%p] removing %d own clusters @ %p", (void*)this, fClusters->GetEntries(), (void*)fClusters));
     146           0 :     fClusters->Delete(); delete fClusters;
     147             :   }
     148           6 :   if(fGeom) delete fGeom;
     149          44 : }
     150             : 
     151             : //____________________________________________________________________
     152             : Int_t AliTRDtrackerV1::Clusters2Tracks(AliESDEvent *esd)
     153             : {
     154             :   //
     155             :   // Steering stand alone tracking for full TRD detector
     156             :   //
     157             :   // Parameters :
     158             :   //   esd     : The ESD event. On output it contains 
     159             :   //             the ESD tracks found in TRD.
     160             :   //
     161             :   // Output :
     162             :   //   Number of tracks found in the TRD detector.
     163             :   // 
     164             :   // Detailed description
     165             :   // 1. Launch individual SM trackers. 
     166             :   //    See AliTRDtrackerV1::Clusters2TracksSM() for details.
     167             :   //
     168             : 
     169           0 :   if(!fkRecoParam){
     170           0 :     AliError("Reconstruction configuration not initialized. Call first AliTRDReconstructor::SetRecoParam().");
     171           0 :     return 0;
     172             :   }
     173             :   
     174             :   //AliInfo("Start Track Finder ...");
     175             :   Int_t ntracks = 0;
     176           0 :   for(int ism=0; ism<AliTRDgeometry::kNsector; ism++){
     177             :     //  for(int ism=1; ism<2; ism++){
     178             :     //AliInfo(Form("Processing supermodule %i ...", ism));
     179           0 :     ntracks += Clusters2TracksSM(ism, esd);
     180             :   }
     181           0 :   AliInfo(Form("Number of tracks: !TRDin[%d]", ntracks));
     182             :   return ntracks;
     183           0 : }
     184             : 
     185             : 
     186             : //_____________________________________________________________________________
     187             : Bool_t AliTRDtrackerV1::GetTrackPoint(Int_t index, AliTrackPoint &p) const
     188             : {
     189             :   //AliInfo(Form("Asking for tracklet %d", index));
     190             :   
     191             :   // reset position of the point before using it
     192         230 :   p.SetXYZ(0., 0., 0.);
     193         115 :   AliTRDseedV1 *tracklet = GetTracklet(index); 
     194         115 :   if (!tracklet) return kFALSE;
     195             : 
     196             :   // get detector for this tracklet
     197         115 :   Int_t det = tracklet->GetDetector();
     198         115 :   Int_t sec = fGeom->GetSector(det);
     199         115 :   Double_t alpha = (sec+.5)*AliTRDgeometry::GetAlpha(),
     200         115 :            sinA  = TMath::Sin(alpha),
     201         115 :            cosA  = TMath::Cos(alpha);
     202         115 :   Double_t local[3];
     203         115 :   local[0] = tracklet->GetX(); 
     204         115 :   local[1] = tracklet->GetY();
     205         115 :   local[2] = tracklet->GetZ();
     206         115 :   Double_t global[3];
     207         115 :   fGeom->RotateBack(det, local, global);
     208             : 
     209         115 :   Double_t cov2D[3]; Float_t cov[6];
     210         115 :   tracklet->GetCovAt(local[0], cov2D);
     211         115 :   cov[0] = cov2D[0]*sinA*sinA;
     212         115 :   cov[1] =-cov2D[0]*sinA*cosA;
     213         115 :   cov[2] =-cov2D[1]*sinA;
     214         115 :   cov[3] = cov2D[0]*cosA*cosA;
     215         115 :   cov[4] = cov2D[1]*cosA;
     216         115 :   cov[5] = cov2D[2];
     217             :   // store the global position of the tracklet and its covariance matrix in the track point 
     218         115 :   p.SetXYZ(global[0],global[1],global[2], cov);
     219             :   
     220             :   // setting volume id
     221         115 :   AliGeomManager::ELayerID iLayer = AliGeomManager::ELayerID(AliGeomManager::kTRD1+fGeom->GetLayer(det));
     222         115 :   Int_t    modId = fGeom->GetSector(det) * AliTRDgeometry::kNstack + fGeom->GetStack(det);
     223         115 :   UShort_t volid = AliGeomManager::LayerToVolUID(iLayer, modId);
     224         115 :   p.SetVolumeID(volid);
     225             :     
     226             :   return kTRUE;
     227         230 : }
     228             : 
     229             : //____________________________________________________________________
     230             : TLinearFitter* AliTRDtrackerV1::GetTiltedRiemanFitter()
     231             : {
     232           0 :   if(!fgTiltedRieman) fgTiltedRieman = new TLinearFitter(4, "hyp4");
     233           0 :   return fgTiltedRieman;
     234           0 : }
     235             : 
     236             : //____________________________________________________________________
     237             : TLinearFitter* AliTRDtrackerV1::GetTiltedRiemanFitterConstraint()
     238             : {
     239           0 :   if(!fgTiltedRiemanConstrained) fgTiltedRiemanConstrained = new TLinearFitter(2, "hyp2");
     240           0 :   return fgTiltedRiemanConstrained;
     241           0 : }
     242             :   
     243             : //____________________________________________________________________  
     244             : AliRieman* AliTRDtrackerV1::GetRiemanFitter()
     245             : {
     246           0 :   if(!fgRieman) fgRieman = new AliRieman(AliTRDseedV1::kNtb * AliTRDgeometry::kNlayer);
     247           0 :   return fgRieman;
     248           0 : }
     249             :   
     250             : //_____________________________________________________________________________
     251             : Int_t AliTRDtrackerV1::PropagateBack(AliESDEvent *event) 
     252             : {
     253             : // Propagation of ESD tracks from TPC to TOF detectors and building of the TRD track. For building
     254             : // a TRD track an ESD track is used as seed. The informations obtained on the TRD track (measured points,
     255             : // covariance, PID, etc.) are than used to update the corresponding ESD track.
     256             : // Each track seed is first propagated to the geometrical limit of the TRD detector. 
     257             : // Its prolongation is searched in the TRD and if corresponding clusters are found tracklets are 
     258             : // constructed out of them (see AliTRDseedV1::AttachClusters()) and the track is updated. 
     259             : // Otherwise the ESD track is left unchanged.
     260             : // 
     261             : // The following steps are performed:
     262             : // 1. Selection of tracks based on the variance in the y-z plane.
     263             : // 2. Propagation to the geometrical limit of the TRD volume. If track propagation fails the AliESDtrack::kTRDStop is set.
     264             : // 3. Prolongation inside the fiducial volume (see AliTRDtrackerV1::FollowBackProlongation()) and marking
     265             : // the following status bits:
     266             : //   - AliESDtrack::kTRDin - if the tracks enters the TRD fiducial volume
     267             : //   - AliESDtrack::kTRDStop - if the tracks fails propagation
     268             : //   - AliESDtrack::kTRDbackup - if the tracks fulfills chi2 conditions and qualify for refitting
     269             : // 4. Writting to friends, PID, MC label, quality etc. Setting status bit AliESDtrack::kTRDout.
     270             : // 5. Propagation to TOF. If track propagation fails the AliESDtrack::kTRDStop is set.
     271             : //  
     272          48 :   AliInfoF("Extra Tolerances: boundary check: %.2f, roadY: %.2f, roadZ: %.2f, extra cl/layer: %d, ExtraChi2out: %.2f",
     273             :            AliTRDReconstructor::GetExtraBoundaryTolerance(),
     274             :            AliTRDReconstructor::GetExtraRoadY(),
     275             :            AliTRDReconstructor::GetExtraRoadZ(),
     276             :            AliTRDReconstructor::GetExtraMaxClPerLayer(),
     277             :            AliTRDReconstructor::GetExtraChi2Out());
     278             :   //
     279          16 :   if(!fClusters || !fClusters->GetEntriesFast()){ 
     280           0 :     AliInfo("No TRD clusters");
     281           0 :     return 0;
     282             :   }
     283           8 :   AliTRDCalibraFillHisto *calibra = AliTRDCalibraFillHisto::Instance(); // Calibration monitor
     284           8 :   if (!calibra) AliInfo("Could not get Calibra instance");
     285          10 :   if (!fgNTimeBins) fgNTimeBins = fkReconstructor->GetNTimeBins(); 
     286             : 
     287             :   // Define scalers
     288             :   Int_t nFound   = 0, // number of tracks found
     289             :         nBacked  = 0, // number of tracks backed up for refit
     290             :         nSeeds   = 0, // total number of ESD seeds
     291             :         nTRDseeds= 0, // number of seeds in the TRD acceptance
     292             :         nTPCseeds= 0; // number of TPC seeds
     293             :   Float_t foundMin = 20.0;
     294             : 
     295           8 :   fEventInFile  = event->GetEventNumberInFile();
     296           8 :   nSeeds   = event->GetNumberOfTracks();
     297             :   
     298           8 :   Float_t quality[nSeeds];
     299           8 :   Int_t   index[nSeeds];
     300             :   // Sort tracks according to quality 
     301             :   // (covariance in the yz plane)
     302           8 :   if(nSeeds){  
     303             :     //    quality = new Float_t[nSeeds]; // RS move on stack
     304             :     //    index   = new Int_t[4*nSeeds];
     305         320 :     for (Int_t iSeed = nSeeds; iSeed--;) {
     306         152 :       AliESDtrack *seed = event->GetTrack(iSeed);
     307         152 :       Double_t covariance[15];
     308         152 :       seed->GetExternalCovariance(covariance);
     309         152 :       quality[iSeed] = covariance[0] + covariance[2];
     310         152 :     }
     311           8 :     TMath::Sort(nSeeds, quality, index,kFALSE);
     312           8 :   }
     313             :   
     314             :   // Propagate all seeds
     315             :   Int_t   expectedClr;
     316           8 :   AliTRDtrackV1 track;
     317         320 :   for (Int_t iSeed = 0; iSeed < nSeeds; iSeed++) {
     318             :   
     319             :     // Get the seeds in sorted sequence
     320         152 :     AliESDtrack *seed = event->GetTrack(index[iSeed]);
     321         456 :     Float_t p4  = seed->GetC(seed->GetBz());
     322             :   
     323             :     // Check the seed status
     324         152 :     ULong_t status = seed->GetStatus();
     325         152 :     if ((status & AliESDtrack::kTRDout) != 0) continue;
     326         152 :     if ((status & AliESDtrack::kTPCout)){
     327         670 :       AliDebug(3, Form("Prolongate seed[%2d] which is TPC.", iSeed));
     328             :       // set steering parameters for TPC
     329             :       //fkRecoParam->SetTrackParam(kTPC);
     330             : /*    } else {
     331             :       if ((status & AliESDtrack::kITSout)){
     332             :         AliDebug(3, Form("Prolongate seed[%2d] which is ITS.", iSeed));
     333             :         // set steering parameters for ITS
     334             :         //fkRecoParam->SetTrackParam(kITS);
     335             :         // rotate
     336             :         Float_t  globalToTracking = AliTRDgeometry::GetAlpha()*(Int_t(seed->GetAlpha()/AliTRDgeometry::GetAlpha()) + (seed->GetAlpha()>0. ? 0.5 : -0.5));
     337             :         if(!seed->Rotate(globalToTracking)) continue;
     338             :       } else continue;*/
     339          18 :     } else continue;
     340             : 
     341             :     // Propagate to the entrance in the TRD mother volume
     342         134 :     track.~AliTRDtrackV1();
     343         268 :     new(&track) AliTRDtrackV1(*seed);
     344         536 :     if(AliTRDgeometry::GetXtrdBeg() > (AliTRDReconstructor::GetMaxStep() + track.GetX()) && !PropagateToX(track, AliTRDgeometry::GetXtrdBeg(), AliTRDReconstructor::GetMaxStep())){
     345          28 :       seed->UpdateTrackParams(&track, AliESDtrack::kTRDStop);
     346          28 :       continue;
     347             :     }    
     348         212 :     if(!AdjustSector(&track)){
     349           0 :       seed->UpdateTrackParams(&track, AliESDtrack::kTRDStop);
     350           0 :       continue;
     351             :     }
     352         212 :     if(TMath::Abs(track.GetSnp()) > AliTRDReconstructor::GetMaxSnp()) {
     353           0 :       seed->UpdateTrackParams(&track, AliESDtrack::kTRDStop);
     354           0 :       continue;
     355             :     }
     356         106 :     nTPCseeds++;
     357         530 :     AliDebug(2, Form("TRD propagate TPC seed[%d] = %d.", iSeed, index[iSeed]));
     358             :     // store track status at TRD entrance
     359         106 :     seed->UpdateTrackParams(&track, AliESDtrack::kTRDbackup);
     360             : 
     361             :     // prepare track and do propagation in the TRD
     362         106 :     track.SetReconstructor(fkReconstructor);
     363         212 :     track.SetKink(Bool_t(seed->GetKinkIndex(0)));
     364         106 :     track.SetPrimary(status & AliESDtrack::kTPCin);
     365         106 :     expectedClr = FollowBackProlongation(track);
     366             :     // check if track entered the TRD fiducial volume
     367         106 :     if(track.GetTrackIn()){ 
     368          42 :       seed->UpdateTrackParams(&track, AliESDtrack::kTRDin);
     369          42 :       nTRDseeds++;
     370          42 :     }
     371             :     // check if track was stopped in the TRD
     372         106 :     if (expectedClr<0){      
     373           2 :       seed->UpdateTrackParams(&track, AliESDtrack::kTRDStop);
     374           2 :       continue;
     375             :     } else {
     376         104 :       nFound++;  
     377             :       // compute PID
     378         104 :       track.CookPID();
     379             :       //compute MC label
     380         104 :       track.CookLabel(1. - AliTRDReconstructor::GetLabelFraction());
     381             :       // update calibration references using this track
     382         104 :       if(calibra->GetHisto2d()) calibra->UpdateHistogramsV1(&track);
     383             :       // save calibration object
     384         104 :       if (fkRecoParam->GetStreamLevel(AliTRDrecoParam::kTracker) > 0 || AliTRDReconstructor::GetStreamLevel()>0 ) { 
     385         208 :         AliTRDtrackV1 *calibTrack = new AliTRDtrackV1(track);
     386         104 :         calibTrack->SetOwner();
     387         104 :         seed->AddCalibObject(calibTrack);
     388         104 :       }
     389             :       //update ESD track
     390         104 :       seed->UpdateTrackParams(&track, AliESDtrack::kTRDout);
     391         104 :       track.UpdateESDtrack(seed);
     392             :     }
     393             : 
     394             :     // Make backup for back propagation
     395         314 :     if ((TMath::Abs(track.GetC(track.GetBz()) - p4) / TMath::Abs(p4) < 0.2) || (track.Pt() > 0.8)) {
     396         103 :       Int_t foundClr = track.GetNumberOfClusters();
     397         103 :       if (foundClr >= foundMin) {
     398             :         //if(track.GetBackupTrack()) UseClusters(track.GetBackupTrack());
     399             : 
     400             :         // Sign only gold tracks
     401          80 :         if (track.GetChi2() / track.GetNumberOfClusters() < 4) {
     402             :           //if ((seed->GetKinkIndex(0)      ==   0) && (track.Pt() <  1.5)) UseClusters(&track);
     403             :         }
     404             :         Bool_t isGold = kFALSE;
     405             :   
     406             :         // Full gold track
     407          80 :         if (track.GetChi2() / track.GetNumberOfClusters() < 5) {
     408          40 :           if (track.GetBackupTrack()) seed->UpdateTrackParams(track.GetBackupTrack(),AliESDtrack::kTRDbackup);
     409          40 :           nBacked++;
     410             :           isGold = kTRUE;
     411          40 :         }
     412             :   
     413             :         // Almost gold track
     414          40 :         if ((!isGold)  && (track.GetNCross() == 0) &&   (track.GetChi2() / track.GetNumberOfClusters()  < 7)) {
     415             :           //seed->UpdateTrackParams(track, AliESDtrack::kTRDbackup);
     416           0 :           if (track.GetBackupTrack()) seed->UpdateTrackParams(track.GetBackupTrack(),AliESDtrack::kTRDbackup);
     417           0 :           nBacked++;
     418             :           isGold = kTRUE;
     419           0 :         }
     420             :         
     421          40 :         if ((!isGold) && (track.GetBackupTrack())) {
     422           0 :           if ((track.GetBackupTrack()->GetNumberOfClusters() > foundMin) && ((track.GetBackupTrack()->GetChi2()/(track.GetBackupTrack()->GetNumberOfClusters()+1)) < 7)) {
     423           0 :             seed->UpdateTrackParams(track.GetBackupTrack(),AliESDtrack::kTRDbackup);
     424           0 :             nBacked++;
     425             :             isGold = kTRUE;
     426           0 :           }
     427             :         }
     428          40 :       }
     429         103 :     }
     430             :     
     431             :     // Propagation to the TOF
     432         208 :     if(!(seed->GetStatus()&AliESDtrack::kTRDStop)) {
     433         104 :       Int_t sm = track.GetSector();
     434             :       // default value in case we have problems with the geometry.
     435             :       Double_t xtof  = 371.; 
     436             :       //Calculate radial position of the beginning of the TOF
     437             :       //mother volume. In order to avoid mixing of the TRD 
     438             :       //and TOF modules some hard values are needed. This are:
     439             :       //1. The path to the TOF module.
     440             :       //2. The width of the TOF (29.05 cm)
     441             :       //(with the help of Annalisa de Caro Mar-17-2009)
     442         104 :       if(gGeoManager){
     443         208 :         gGeoManager->cd(Form("/ALIC_1/B077_1/BSEGMO%d_1/BTOF%d_1", sm, sm));
     444             :         TGeoHMatrix *m = NULL;
     445         104 :         Double_t loc[]={0., 0., -.5*29.05}, glob[3];
     446             :         
     447         208 :         if((m=gGeoManager->GetCurrentMatrix())){
     448         104 :           m->LocalToMaster(loc, glob);
     449         104 :           xtof = TMath::Sqrt(glob[0]*glob[0]+glob[1]*glob[1]);
     450         104 :         }
     451         104 :       }
     452         416 :       if(xtof > (AliTRDReconstructor::GetMaxStep() + track.GetX()) && !PropagateToX(track, xtof, AliTRDReconstructor::GetMaxStep())){
     453           0 :         seed->UpdateTrackParams(&track, AliESDtrack::kTRDStop);
     454           0 :         continue;
     455             :       }
     456         208 :       if(!AdjustSector(&track)){ 
     457           0 :         seed->UpdateTrackParams(&track, AliESDtrack::kTRDStop);
     458           0 :         continue;
     459             :       }
     460         208 :       if(TMath::Abs(track.GetSnp()) > AliTRDReconstructor::GetMaxSnp()){
     461           2 :         seed->UpdateTrackParams(&track, AliESDtrack::kTRDStop);
     462           2 :         continue;
     463             :       }
     464             :       //seed->UpdateTrackParams(&track, AliESDtrack::kTRDout);
     465             :       // TODO obsolete - delete
     466         204 :       seed->SetTRDQuality(track.StatusForTOF()); 
     467         102 :     }
     468         102 :     seed->SetTRDBudget(track.GetBudget(0));
     469         102 :   }
     470             :   //  if(index) delete [] index; // RS moved to stack
     471             :   //  if(quality) delete [] quality;
     472             : 
     473          24 :   AliInfo(Form("Number of seeds: TPCout[%d] TRDin[%d]", nTPCseeds, nTRDseeds));
     474          24 :   AliInfo(Form("Number of tracks: TRDout[%d] TRDbackup[%d]", nFound, nBacked));
     475             : 
     476             :   // run stand alone tracking
     477           8 :   if (fkReconstructor->IsSeeding()) Clusters2Tracks(event);
     478             :   
     479             :   return 0;
     480          16 : }
     481             : 
     482             : 
     483             : //____________________________________________________________________
     484             : Int_t AliTRDtrackerV1::RefitInward(AliESDEvent *event)
     485             : {
     486             :   //
     487             :   // Refits tracks within the TRD. The ESD event is expected to contain seeds 
     488             :   // at the outer part of the TRD. 
     489             :   // The tracks are propagated to the innermost time bin 
     490             :   // of the TRD and the ESD event is updated
     491             :   // Origin: Thomas KUHR (Thomas.Kuhr@cern.ch)
     492             :   //
     493             : 
     494             :   Int_t   nseed    = 0; // contor for loaded seeds
     495             :   Int_t   found    = 0; // contor for updated TRD tracks
     496             :   
     497             :   
     498          24 :   if(!fClusters || !fClusters->GetEntriesFast()){ 
     499           0 :     AliInfo("No TRD clusters");
     500           0 :     return 0;
     501             :   }
     502           8 :   AliTRDtrackV1 track;
     503         480 :   for (Int_t itrack = 0; itrack < event->GetNumberOfTracks(); itrack++) {
     504         152 :     AliESDtrack *seed = event->GetTrack(itrack);
     505         152 :     ULong_t status = seed->GetStatus();
     506             : 
     507         304 :     new(&track) AliTRDtrackV1(*seed);
     508         304 :     if (track.GetX() < 270.0) {
     509          44 :       seed->UpdateTrackParams(&track, AliESDtrack::kTRDbackup);
     510          44 :       continue;
     511             :     }
     512             : 
     513             :     // reject tracks which failed propagation in the TRD or
     514             :     // are produced by the TRD stand alone tracker
     515         112 :     if(!(status & AliESDtrack::kTRDout)) continue;
     516         166 :     if(!(status & AliESDtrack::kTRDin)) continue;
     517          42 :     nseed++; 
     518             : 
     519          42 :     track.ResetCovariance(50.0);
     520             : 
     521             :     // do the propagation and processing
     522             :     Bool_t kUPDATE = kFALSE;
     523             :     Double_t xTPC = 250.0;
     524          84 :     if(FollowProlongation(track)){      
     525             :       // Update the friend track
     526          42 :       if (fkRecoParam->GetStreamLevel(AliTRDrecoParam::kTracker) > 0  || AliTRDReconstructor::GetStreamLevel()>0 ){ 
     527             :         TObject *o = NULL; Int_t ic = 0;
     528             :         AliTRDtrackV1 *calibTrack = NULL; 
     529         272 :         while((o = seed->GetCalibObject(ic++))){
     530         219 :           if(!(calibTrack = dynamic_cast<AliTRDtrackV1*>(o))) continue;
     531          42 :           calibTrack->SetTrackOut(&track);
     532             :         }
     533          42 :       }
     534             : 
     535             :       // Prolongate to TPC
     536          84 :       if (PropagateToX(track, xTPC, AliTRDReconstructor::GetMaxStep())) { //  -with update
     537          42 :         seed->UpdateTrackParams(&track, AliESDtrack::kTRDrefit);
     538          42 :         found++;
     539             :         kUPDATE = kTRUE;
     540          42 :       }
     541             :     }
     542             :     
     543             :     // Prolongate to TPC without update
     544          42 :     if(!kUPDATE) {
     545           0 :       AliTRDtrackV1 tt(*seed);
     546           0 :       if (PropagateToX(tt, xTPC, AliTRDReconstructor::GetMaxStep())) seed->UpdateTrackParams(&tt, AliESDtrack::kTRDbackup);
     547           0 :     }
     548          42 :   }
     549          24 :   AliInfo(Form("Number of seeds: TRDout[%d]", nseed));
     550          24 :   AliInfo(Form("Number of tracks: TRDrefit[%d]", found));
     551             :   
     552             :   return 0;
     553          16 : }
     554             : 
     555             : //____________________________________________________________________
     556             : Int_t AliTRDtrackerV1::FollowProlongation(AliTRDtrackV1 &t)
     557             : {
     558             :   // Extrapolates the TRD track in the TPC direction.
     559             :   //
     560             :   // Parameters
     561             :   //   t : the TRD track which has to be extrapolated
     562             :   // 
     563             :   // Output
     564             :   //   number of clusters attached to the track
     565             :   //
     566             :   // Detailed description
     567             :   //
     568             :   // Starting from current radial position of track <t> this function
     569             :   // extrapolates the track through the 6 TRD layers. The following steps
     570             :   // are being performed for each plane:
     571             :   // 1. prepare track:
     572             :   //   a. get plane limits in the local x direction
     573             :   //   b. check crossing sectors 
     574             :   //   c. check track inclination
     575             :   // 2. search tracklet in the tracker list (see GetTracklet() for details)
     576             :   // 3. evaluate material budget using the geo manager
     577             :   // 4. propagate and update track using the tracklet information.
     578             :   //
     579             :   // Debug level 2
     580             :   //
     581             :   
     582          84 :   Int_t    nClustersExpected = 0;
     583         420 :   for (Int_t iplane = kNPlanes; iplane--;) {
     584         252 :     Int_t   index(-1);
     585         252 :     AliTRDseedV1 *tracklet = GetTracklet(&t, iplane, index);
     586         756 :     AliDebug(2, Form("Tracklet[%p] ly[%d] idx[%d]", (void*)tracklet, iplane, index));
     587         298 :     if(!tracklet) continue;
     588         206 :     if(!tracklet->IsOK()){ 
     589           0 :       AliDebug(1, Form("Tracklet Det[%d] !OK", tracklet->GetDetector()));
     590           0 :       continue;
     591             :     }
     592         206 :     Double_t x  = tracklet->GetX();//GetX0();
     593             :     // reject tracklets which are not considered for inward refit
     594         206 :     if(x > t.GetX()+AliTRDReconstructor::GetMaxStep()) continue;
     595             : 
     596             :     // append tracklet to track
     597         206 :     t.SetTracklet(tracklet, index);
     598             :     
     599         412 :     if (x < (t.GetX()-AliTRDReconstructor::GetMaxStep()) && !PropagateToX(t, x+AliTRDReconstructor::GetMaxStep(), AliTRDReconstructor::GetMaxStep())) break;
     600         206 :     if (!AdjustSector(&t)) break;
     601             :     
     602             :     // Start global position
     603         206 :     Double_t xyz0[3];
     604         206 :     t.GetXYZ(xyz0);
     605             : 
     606             :     // End global position
     607         206 :     Double_t alpha = t.GetAlpha(), y, z;
     608         206 :     if (!t.GetProlongation(x,y,z)) break;    
     609         206 :     Double_t xyz1[3];
     610         206 :     xyz1[0] =  x * TMath::Cos(alpha) - y * TMath::Sin(alpha);
     611         206 :     xyz1[1] =  x * TMath::Sin(alpha) + y * TMath::Cos(alpha);
     612         206 :     xyz1[2] =  z;
     613             :         
     614         206 :     Double_t length = TMath::Sqrt(
     615         412 :       (xyz0[0]-xyz1[0])*(xyz0[0]-xyz1[0]) +
     616         412 :       (xyz0[1]-xyz1[1])*(xyz0[1]-xyz1[1]) +
     617         206 :       (xyz0[2]-xyz1[2])*(xyz0[2]-xyz1[2])
     618             :     );
     619         206 :     if(length>0.){
     620             :       // Get material budget
     621         206 :       Double_t param[7];
     622         206 :       if(AliTracker::MeanMaterialBudget(xyz0, xyz1, param)<=0.) break;
     623         206 :       Double_t xrho= param[0]*param[4];
     624         206 :       Double_t xx0 = param[1]; // Get mean propagation parameters
     625             :   
     626             :       // Propagate and update           
     627         206 :       t.PropagateTo(x, xx0, xrho);
     628         206 :       if (!AdjustSector(&t)) break;
     629         412 :     }
     630             : 
     631         206 :     Double_t cov[3]; tracklet->GetCovAt(x, cov);
     632         206 :     Double_t p[2] = { tracklet->GetY(), tracklet->GetZ()};
     633         412 :     Double_t chi2 = ((AliExternalTrackParam)t).GetPredictedChi2(p, cov);
     634             : 
     635         206 :     if(fkReconstructor->IsDebugStreaming()){
     636           0 :       Int_t eventNumber = AliTRDtrackerDebug::GetEventNumber();
     637           0 :       TTreeSRedirector &cstreamer = *fkReconstructor->GetDebugStream(AliTRDrecoParam::kTracker);
     638           0 :       AliExternalTrackParam param0(t);
     639           0 :       AliExternalTrackParam param1(t);
     640           0 :       param1.Update(p, cov);
     641           0 :       TVectorD vcov(3,cov);
     642           0 :       TVectorD vpar(3,p);
     643           0 :       cstreamer << "FollowProlongationInfo"
     644           0 :                 << "EventNumber="       << eventNumber
     645           0 :                 << "iplane="<<iplane
     646           0 :                 << "vcov.="<<&vcov
     647           0 :                 << "vpar.="<<&vpar
     648           0 :                 << "tracklet.="      << tracklet
     649           0 :                 << "chi2="<< chi2 
     650           0 :                 << "param0.="           << &param0
     651           0 :                 << "param1.="           << &param1
     652           0 :                 << "\n";
     653           0 :     }
     654             :     /*
     655             :     AliInfo(Form("Pl:%d X:%+e : %+e P: %+e %+e Cov:%+e %+e %+e -> dXY: %+e %+e | chi2:%.2f pT:%.2f alp:%.3f",
     656             :                  iplane,x,t.GetX(),p[0],p[1],cov[0],cov[1],cov[2],
     657             :                  p[0]-t.GetY(),p[1]-t.GetZ(),
     658             :                  chi2,t.Pt()*t.Charge(),t.GetAlpha()));
     659             :     */
     660         412 :     if (chi2 < fkRecoParam->GetChi2Cut() && ((AliExternalTrackParam&)t).Update(p, cov)){  // MI parameterizad chi2 cut 03.05.2014
     661             :       //    if (chi2 < 1e+10 && ((AliExternalTrackParam&)t).Update(p, cov)){ 
     662             :       // Register info to track
     663         206 :       t.SetNumberOfClusters();
     664         206 :       t.UpdateChi2(chi2);
     665         206 :       nClustersExpected += tracklet->GetN();
     666         206 :     }
     667         952 :   }
     668             : 
     669          84 :   if(fkRecoParam->GetStreamLevel(AliTRDrecoParam::kTracker) > 1 || AliTRDReconstructor::GetStreamLevel()>1){
     670           0 :     Int_t index;
     671           0 :     for(int iplane=0; iplane<AliTRDgeometry::kNlayer; iplane++){
     672           0 :       AliTRDseedV1 *tracklet = GetTracklet(&t, iplane, index);
     673           0 :       if(!tracklet) continue;
     674           0 :       t.SetTracklet(tracklet, index);
     675           0 :     }
     676             : 
     677           0 :     if(fkReconstructor->IsDebugStreaming()){
     678           0 :       Int_t eventNumber = AliTRDtrackerDebug::GetEventNumber();
     679           0 :       TTreeSRedirector &cstreamer = *fkReconstructor->GetDebugStream(AliTRDrecoParam::kTracker);
     680           0 :       AliTRDtrackV1 track(t);
     681           0 :       track.SetOwner();
     682           0 :       cstreamer << "FollowProlongation"
     683           0 :           << "EventNumber="     << eventNumber
     684           0 :           << "ncl="                                     << nClustersExpected
     685           0 :           << "track.="                  << &track
     686           0 :           << "\n";
     687           0 :     }
     688           0 :   }
     689          84 :   return nClustersExpected;
     690             : 
     691          42 : }
     692             : 
     693             : //_____________________________________________________________________________
     694             : Int_t AliTRDtrackerV1::FollowBackProlongation(AliTRDtrackV1 &t)
     695             : {
     696             : // Extrapolates/Build the TRD track in the TOF direction.
     697             : //
     698             : // Parameters
     699             : //   t : the TRD track which has to be extrapolated
     700             : // 
     701             : // Output
     702             : //   number of clusters attached to the track
     703             : //
     704             : // Starting from current radial position of track <t> this function
     705             : // extrapolates the track through the 6 TRD layers. The following steps
     706             : // are being performed for each plane:
     707             : // 1. Propagate track to the entrance of the next chamber:
     708             : //   - get chamber limits in the radial direction
     709             : //   - check crossing sectors 
     710             : //   - check track inclination
     711             : //   - check track prolongation against boundary conditions (see exclusion boundaries on AliTRDgeometry::IsOnBoundary())
     712             : // 2. Build tracklet (see AliTRDseed::AttachClusters() for details) for this layer if needed. If only 
     713             : //    Kalman filter is needed and tracklets are already linked to the track this step is skipped.
     714             : // 3. Fit tracklet using the information from the Kalman filter.
     715             : // 4. Propagate and update track at reference radial position of the tracklet.
     716             : // 5. Register tracklet with the tracker and track; update pulls monitoring.
     717             : //
     718             : // Observation
     719             : //   1. During the propagation a bit map is filled detailing the status of the track in each TRD chamber. The following errors are being registered for each tracklet:
     720             : // - AliTRDtrackV1::kProlongation : track prolongation failed
     721             : // - AliTRDtrackV1::kPropagation : track prolongation failed
     722             : // - AliTRDtrackV1::kAdjustSector : failed during sector crossing
     723             : // - AliTRDtrackV1::kSnp : too large bending
     724             : // - AliTRDtrackV1::kTrackletInit : fail to initialize tracklet
     725             : // - AliTRDtrackV1::kUpdate : fail to attach clusters or fit the tracklet
     726             : // - AliTRDtrackV1::kUnknown : anything which is not covered before
     727             : //   2. By default the status of the track before first TRD update is saved. 
     728             : // 
     729             : // Debug level 2
     730             : //
     731             : // Author
     732             : //   Alexandru Bercuci <A.Bercuci@gsi.de>
     733             : //
     734             :   
     735             :   Int_t n = 0;
     736         212 :   Double_t driftLength = .5*AliTRDgeometry::AmThick() + AliTRDgeometry::DrThick();
     737             :   AliTRDtrackingChamber *chamber = NULL;
     738             :   
     739         212 :   Int_t debugLevel = fkReconstructor->IsDebugStreaming() ? fkRecoParam->GetStreamLevel(AliTRDrecoParam::kTracker) : 0;
     740         106 :   if ( AliTRDReconstructor::GetStreamLevel()>0) debugLevel= AliTRDReconstructor::GetStreamLevel();
     741         212 :   TTreeSRedirector *cstreamer = fkReconstructor->IsDebugStreaming() ? fkReconstructor->GetDebugStream(AliTRDrecoParam::kTracker) : 0x0;
     742             :   const double kBoundaryEps = 0.5;
     743         106 :   double boundaryEps = kBoundaryEps + AliTRDReconstructor::GetExtraBoundaryTolerance();
     744             :   Bool_t kStoreIn(kTRUE),     // toggel store track params. at TRD entry
     745             :          kStandAlone(kFALSE), // toggle tracker awarness of stand alone seeding 
     746         106 :          kUseTRD(fkRecoParam->IsOverPtThreshold(t.Pt()));// use TRD measurment to update Kalman
     747             : 
     748             :   Int_t startLayer(0);
     749         106 :   AliTRDseedV1 tracklet, *ptrTracklet = NULL;
     750             :   // Special case for stand alone tracking
     751             :   // - store all tracklets found by seeding
     752             :   // - start propagation from first tracklet found
     753         106 :   AliTRDseedV1 *tracklets[kNPlanes];
     754         106 :   memset(tracklets, 0, sizeof(AliTRDseedV1 *) * kNPlanes);
     755             :   //
     756         106 :   double chi2Cut = fkRecoParam->GetChi2Cut() + AliTRDReconstructor::GetExtraChi2Out();
     757             :   //
     758         848 :   for(Int_t ip(kNPlanes); ip--;){
     759         636 :     if(!(tracklets[ip] = t.GetTracklet(ip))) continue;
     760           0 :     t.UnsetTracklet(ip);
     761           0 :     if(tracklets[ip]->IsOK()) startLayer=ip;
     762             :     kStandAlone = kTRUE;
     763             :     kUseTRD = kTRUE;
     764             :   } 
     765         530 :   AliDebug(4, Form("SA[%c] Start[%d]\n"
     766             :     "  [0]idx[%d] traklet[%p]\n"
     767             :     "  [1]idx[%d] traklet[%p]\n"
     768             :     "  [2]idx[%d] traklet[%p]\n"
     769             :     "  [3]idx[%d] traklet[%p]\n"
     770             :     "  [4]idx[%d] traklet[%p]\n"
     771             :     "  [5]idx[%d] traklet[%p]"
     772             :     , kStandAlone?'y':'n', startLayer
     773             :     , t.GetTrackletIndex(0), (void*)tracklets[0]
     774             :     , t.GetTrackletIndex(1), (void*)tracklets[1]
     775             :     , t.GetTrackletIndex(2), (void*)tracklets[2]
     776             :     , t.GetTrackletIndex(3), (void*)tracklets[3]
     777             :     , t.GetTrackletIndex(4), (void*)tracklets[4]
     778             :     , t.GetTrackletIndex(5), (void*)tracklets[5]));
     779             : 
     780             :   // Loop through the TRD layers
     781             :   TGeoHMatrix *matrix = NULL;
     782         106 :   Double_t x(0.), y(0.), z(0.);
     783        1670 :   for (Int_t ily=startLayer, sm=-1, stk=-1, det=-1; ily < AliTRDgeometry::kNlayer; ily++) {
     784        3130 :     AliDebug(2, Form("Propagate to x[%d] = %7.2f", ily, fR[ily]));
     785             : 
     786             :     // rough estimate of the entry point
     787        1252 :     if (!t.GetProlongation(fR[ily], y, z)){
     788             :       n=-1; 
     789           0 :       t.SetErrStat(AliTRDtrackV1::kProlongation);
     790           0 :       AliDebug(4, Form("Failed Rough Prolongation to ly[%d] x[%7.2f] y[%7.2f] z[%7.2f]", ily, fR[ily], y, z));
     791           0 :       break;
     792             :     }
     793             : 
     794             :     // find sector / stack / detector
     795         626 :     sm = t.GetSector();
     796             :     // TODO cross check with y value !
     797         626 :     stk = fGeom->GetStack(z, ily);
     798        1878 :     det = stk>=0 ? AliTRDgeometry::GetDetector(ily, stk, sm) : -1;
     799        1878 :     matrix = det>=0 ? fGeom->GetClusterMatrix(det) : NULL;
     800             : 
     801             :     // check if supermodule/chamber is installed
     802         626 :     if( !fGeom->GetSMstatus(sm) ||
     803         626 :         stk<0. ||
     804        1878 :         fGeom->IsHole(ily, stk, sm) ||
     805         626 :         !matrix ){ 
     806         815 :       AliDebug(4, Form("Missing Geometry ly[%d]. Guess radial position", ily));
     807             :       // propagate to the default radial position
     808         652 :       if(fR[ily] > (AliTRDReconstructor::GetMaxStep() + t.GetX()) && !PropagateToX(t, fR[ily], AliTRDReconstructor::GetMaxStep())){
     809             :         n=-1; 
     810           0 :         t.SetErrStat(AliTRDtrackV1::kPropagation);
     811           0 :         AliDebug(4, "Failed Propagation [Missing Geometry]");
     812           0 :         break;
     813             :       }
     814         326 :       if(!AdjustSector(&t)){
     815             :         n=-1; 
     816           0 :         t.SetErrStat(AliTRDtrackV1::kAdjustSector);
     817           0 :         AliDebug(4, "Failed Adjust Sector [Missing Geometry]");
     818           0 :         break;
     819             :       }
     820         326 :       if(TMath::Abs(t.GetSnp()) > AliTRDReconstructor::GetMaxSnp()){
     821             :         n=-1; 
     822           1 :         t.SetErrStat(AliTRDtrackV1::kSnp);
     823           5 :         AliDebug(4, "Failed Max Snp [Missing Geometry]");
     824           1 :         break;
     825             :       }
     826         162 :       t.SetErrStat(AliTRDtrackV1::kGeometry, ily);
     827         162 :       continue;
     828             :     }
     829             : 
     830             :     // retrieve rotation matrix for the current chamber
     831         463 :     Double_t loc[] = {AliTRDgeometry::AnodePos()- driftLength, 0., 0.};
     832         463 :     Double_t glb[] = {0., 0., 0.};
     833         463 :     matrix->LocalToMaster(loc, glb);
     834        2315 :     AliDebug(3, Form("Propagate to det[%3d] x_anode[%7.2f] (%f %f)", det, glb[0]+driftLength, glb[1], glb[2]));
     835             : 
     836             :     // Propagate to the radial distance of the current layer
     837         463 :     x = glb[0] - AliTRDReconstructor::GetMaxStep();
     838        1852 :     if(x > (AliTRDReconstructor::GetMaxStep() + t.GetX()) && !PropagateToX(t, x, AliTRDReconstructor::GetMaxStep())){
     839             :       n=-1; 
     840           1 :       t.SetErrStat(AliTRDtrackV1::kPropagation);
     841           5 :       AliDebug(4, Form("Failed Initial Propagation to x[%7.2f]", x));
     842           1 :       break;
     843             :     }
     844         924 :     if(!AdjustSector(&t)){
     845             :       n=-1; 
     846           0 :       t.SetErrStat(AliTRDtrackV1::kAdjustSector);
     847           0 :       AliDebug(4, "Failed Adjust Sector Start");
     848           0 :       break;
     849             :     }
     850         924 :     if(TMath::Abs(t.GetSnp()) > AliTRDReconstructor::GetMaxSnp()) {
     851             :       n=-1; 
     852           0 :       t.SetErrStat(AliTRDtrackV1::kSnp);
     853           0 :       AliDebug(4, Form("Failed Max Snp[%f] MaxSnp[%f]", t.GetSnp(), AliTRDReconstructor::GetMaxSnp()));
     854           0 :       break;
     855             :     }
     856             :     Bool_t doRecalculate = kFALSE;
     857         924 :     if(sm != t.GetSector()){
     858           9 :       sm = t.GetSector(); 
     859             :       doRecalculate = kTRUE;
     860           9 :     }
     861         924 :     if(stk != fGeom->GetStack(z, ily)){
     862           0 :       stk = fGeom->GetStack(z, ily);
     863             :       doRecalculate = kTRUE;
     864           0 :     }
     865         462 :     if(doRecalculate){
     866           9 :       det = AliTRDgeometry::GetDetector(ily, stk, sm);
     867          18 :       if(!(matrix = fGeom->GetClusterMatrix(det))){ 
     868           0 :         t.SetErrStat(AliTRDtrackV1::kGeometry, ily);
     869           0 :         AliDebug(4, Form("Failed Geometry Matrix ly[%d]", ily));
     870           0 :         continue;
     871             :       }
     872           9 :       matrix->LocalToMaster(loc, glb);
     873           9 :       x = glb[0] - AliTRDReconstructor::GetMaxStep();
     874           9 :     }
     875             : 
     876             :     // check if track is well inside fiducial volume 
     877         924 :     if (!t.GetProlongation(x+AliTRDReconstructor::GetMaxStep(), y, z)) {
     878             :       n=-1; 
     879           0 :       t.SetErrStat(AliTRDtrackV1::kProlongation);
     880           0 :       AliDebug(4, Form("Failed Prolongation to x[%7.2f] y[%7.2f] z[%7.2f]", x+AliTRDReconstructor::GetMaxStep(), y, z));
     881           0 :       break;
     882             :     }
     883         924 :     if(fGeom->IsOnBoundary(det, y, z, boundaryEps)){ 
     884          60 :       t.SetErrStat(AliTRDtrackV1::kBoundary, ily);
     885         300 :       AliDebug(4, "Failed Track on Boundary");
     886          60 :       continue;
     887             :     }
     888             : 
     889        1206 :     Float_t prod(t.GetBz()*t.Charge());
     890         402 :     ptrTracklet  = tracklets[ily];
     891         804 :     if(!ptrTracklet){ // BUILD TRACKLET
     892        2010 :       AliDebug(3, Form("Building tracklet det[%d]", det));
     893             :       // check data in supermodule
     894         402 :       if(!fTrSec[sm].GetNChambers()){ 
     895         114 :         t.SetErrStat(AliTRDtrackV1::kNoClusters, ily);
     896         570 :         AliDebug(4, "Failed NoClusters");
     897         114 :         continue;
     898             :       }
     899         288 :       if(fTrSec[sm].GetX(ily) < 1.){ 
     900           2 :         t.SetErrStat(AliTRDtrackV1::kNoClusters, ily);
     901          10 :         AliDebug(4, "Failed NoX");
     902           2 :         continue;
     903             :       }
     904             :       
     905             :       // check data in chamber
     906         572 :       if(!(chamber = fTrSec[sm].GetChamber(stk, ily))){ 
     907          22 :         t.SetErrStat(AliTRDtrackV1::kNoClusters, ily);
     908         110 :         AliDebug(4, "Failed No Detector");
     909          22 :         continue;
     910             :       }
     911         528 :       if(chamber->GetNClusters() < fgNTimeBins*fkRecoParam ->GetFindableClusters()){ 
     912           2 :         t.SetErrStat(AliTRDtrackV1::kNoClusters, ily);
     913          10 :         AliDebug(4, "Failed Not Enough Clusters in Detector");
     914           2 :         continue;
     915             :       }      
     916             :       // build tracklet
     917         262 :       tracklet.~AliTRDseedV1();
     918         524 :       ptrTracklet = new(&tracklet) AliTRDseedV1(det);
     919         262 :       ptrTracklet->SetReconstructor(fkReconstructor);
     920         262 :       ptrTracklet->SetKink(t.IsKink());
     921         524 :       ptrTracklet->SetPrimary(t.IsPrimary());
     922         524 :       ptrTracklet->SetPadPlane(fGeom->GetPadPlane(ily, stk));
     923             :       //set first approximation of radial position of anode wire corresponding to middle chamber y=0, z=0
     924             :       // the uncertainty is given by the actual position of the tracklet (y,z) and chamber inclination
     925         262 :       ptrTracklet->SetX0(glb[0]+driftLength);
     926         524 :       if(!ptrTracklet->Init(&t)){
     927             :         n=-1; 
     928           0 :         t.SetErrStat(AliTRDtrackV1::kTrackletInit);
     929           0 :         AliDebug(4, "Failed Tracklet Init");
     930           0 :         break;
     931             :       }
     932             :       // Select attachment base on track to B field sign not only track charge which is buggy
     933             :       // mark kFALSE same sign tracks and kTRUE opposite sign tracks
     934             :       // A.Bercuci 3.11.2011
     935         524 :       if(!ptrTracklet->AttachClusters(chamber, kTRUE, prod<0.?kTRUE:kFALSE, fEventInFile)){
     936          34 :         t.SetErrStat(AliTRDtrackV1::kNoAttach, ily);
     937          34 :         if(debugLevel>3){
     938           0 :           AliTRDseedV1 trackletCp(*ptrTracklet);
     939           0 :           UChar_t status(t.GetStatusTRD(ily));
     940           0 :           (*cstreamer)   << "FollowBackProlongation4"
     941           0 :           <<"status="    << status
     942           0 :           <<"tracklet.=" << &trackletCp
     943           0 :           << "\n";
     944           0 :         }
     945         170 :         AliDebug(4, "Failed Attach Clusters");
     946          34 :         continue;
     947             :       }
     948        1140 :       AliDebug(3, Form("Number of Clusters in Tracklet: %d", ptrTracklet->GetN()));
     949         228 :       if(ptrTracklet->GetN() < fgNTimeBins*fkRecoParam->GetFindableClusters()){
     950           0 :         t.SetErrStat(AliTRDtrackV1::kNoClustersTracklet, ily);
     951           0 :         if(debugLevel>3){
     952           0 :           AliTRDseedV1 trackletCp(*ptrTracklet);
     953           0 :           UChar_t status(t.GetStatusTRD(ily));
     954           0 :           (*cstreamer)   << "FollowBackProlongation4"
     955           0 :           <<"status="    << status
     956           0 :           <<"tracklet.=" << &trackletCp
     957           0 :           << "\n";
     958           0 :         }
     959           0 :         AliDebug(4, "Failed N Clusters Attached");
     960           0 :         continue;
     961             :       }
     962         228 :       ptrTracklet->UpdateUsed();
     963         402 :     } else AliDebug(2, Form("Use external tracklet ly[%d]", ily));
     964             :     // propagate track to the radial position of the tracklet
     965             : 
     966             :     // fit tracklet in the local chamber coordinate system 
     967             :     // tilt correction options
     968             :     // 0 : no correction
     969             :     // 2 : pseudo tilt correction
     970        1368 :     if(!ptrTracklet->FitRobust(fGeom->GetPadPlane(ily, stk), matrix, t.GetBz(), t.Charge(), 0, t.GetTgl())){
     971           0 :       t.SetErrStat(AliTRDtrackV1::kNoFit, ily);
     972           0 :       AliDebug(4, "Failed Tracklet Fit");
     973           0 :       continue;
     974             :     } 
     975             :     // Calculate tracklet position in tracking coordinates
     976             :     // A.Bercuci 27.11.2013    
     977         228 :     ptrTracklet->SetXYZ(matrix);
     978             : 
     979         456 :     x = ptrTracklet->GetX(); //GetX0();
     980         912 :     if(x > (AliTRDReconstructor::GetMaxStep() + t.GetX()) && !PropagateToX(t, x, AliTRDReconstructor::GetMaxStep())) {
     981             :       n=-1; 
     982           0 :       t.SetErrStat(AliTRDtrackV1::kPropagation);
     983           0 :       AliDebug(4, Form("Failed Propagation to Tracklet x[%7.2f]", x));
     984           0 :       break;
     985             :     }
     986         456 :     if(!AdjustSector(&t)) {
     987             :       n=-1; 
     988           0 :       t.SetErrStat(AliTRDtrackV1::kAdjustSector);
     989           0 :       AliDebug(4, "Failed Adjust Sector");
     990           0 :       break;
     991             :     }
     992         456 :     if(TMath::Abs(t.GetSnp()) > AliTRDReconstructor::GetMaxSnp()) {
     993             :       n=-1; 
     994           0 :       t.SetErrStat(AliTRDtrackV1::kSnp);
     995           0 :       AliDebug(4, Form("Failed Max Snp[%f] MaxSnp[%f]", t.GetSnp(), AliTRDReconstructor::GetMaxSnp()));
     996           0 :       break;
     997             :     }
     998         228 :     Double_t cov[3]; ptrTracklet->GetCovAt(x, cov);
     999         684 :     Double_t p[2] = { ptrTracklet->GetY(), ptrTracklet->GetZ()};
    1000         684 :     Double_t chi2 = ((AliExternalTrackParam)t).GetPredictedChi2(p, cov);
    1001             :     /*
    1002             :     AliInfo(Form("Pl:%d X:%+e : %+e P: %+e %+e Cov:%+e %+e %+e -> dXY: %+e %+e | chi2:%.2f pT:%.2f alp:%.3f",
    1003             :                  ily,x,t.GetX(),p[0],p[1],cov[0],cov[1],cov[2],
    1004             :                  p[0]-t.GetY(),p[1]-t.GetZ(),
    1005             :                  chi2,t.Pt()*t.Charge(),t.GetAlpha()));
    1006             :     */
    1007             : 
    1008         228 :      if(fkReconstructor->IsDebugStreaming()){
    1009           0 :       Int_t eventNumber = AliTRDtrackerDebug::GetEventNumber();
    1010             :       //      TTreeSRedirector &cstreamer = *fkReconstructor->GetDebugStream(AliTRDrecoParam::kTracker);
    1011           0 :       AliExternalTrackParam param0(t);
    1012           0 :       AliExternalTrackParam param1(t);
    1013           0 :       param1.Update(p, cov);
    1014           0 :       TVectorD vcov(3,cov);
    1015           0 :       TVectorD vpar(3,p);
    1016           0 :       (*cstreamer) << "FollowBackProlongationInfo"
    1017           0 :                 << "EventNumber="       << eventNumber
    1018           0 :                 << "chi2="<<chi2
    1019           0 :                 << "iplane="<<ily
    1020           0 :                 << "vcov.="<<&vcov
    1021           0 :                 << "vpar.="<<&vpar
    1022           0 :                 << "tracklet.="      << ptrTracklet
    1023           0 :                 << "param0.="           << &param0
    1024           0 :                 << "param1.="           << &param1
    1025           0 :                 << "\n";
    1026           0 :      }
    1027             :      
    1028             :      // update Kalman with the TRD measurement
    1029         228 :      if (chi2> chi2Cut){ // MI parameterizad chi2 cut 03.05.2014
    1030          22 :       t.SetErrStat(AliTRDtrackV1::kChi2, ily);
    1031          22 :       if(debugLevel > 2){
    1032           0 :         UChar_t status(t.GetStatusTRD());
    1033           0 :         AliTRDseedV1  trackletCp(*ptrTracklet);
    1034           0 :         AliTRDtrackV1 trackCp(t);
    1035           0 :         trackCp.SetOwner();
    1036           0 :         (*cstreamer) << "FollowBackProlongation3"
    1037           0 :             << "status="      << status
    1038           0 :             << "tracklet.="   << &trackletCp
    1039           0 :             << "track.="      << &trackCp
    1040           0 :             << "\n";
    1041           0 :       }
    1042         110 :       AliDebug(4, Form("Failed Chi2[%f]", chi2));
    1043          22 :       continue; 
    1044             :     }
    1045             :     // mark track as entering the FIDUCIAL volume of TRD
    1046         206 :     if(kStoreIn){
    1047          42 :       t.SetTrackIn();
    1048             :       kStoreIn = kFALSE;
    1049          42 :     }
    1050         206 :     if(kUseTRD){
    1051         412 :       if(!((AliExternalTrackParam&)t).Update(p, cov)) {
    1052             :         n=-1; 
    1053           0 :         t.SetErrStat(AliTRDtrackV1::kUpdate);
    1054           0 :         if(debugLevel > 2){
    1055           0 :           UChar_t status(t.GetStatusTRD());
    1056           0 :           AliTRDseedV1  trackletCp(*ptrTracklet);
    1057           0 :           AliTRDtrackV1 trackCp(t);
    1058           0 :           trackCp.SetOwner();
    1059           0 :           (*cstreamer) << "FollowBackProlongation3"
    1060           0 :               << "status="      << status
    1061           0 :               << "tracklet.="   << &trackletCp
    1062           0 :               << "track.="      << &trackCp
    1063           0 :               << "\n";
    1064           0 :         }
    1065           0 :         AliDebug(4, Form("Failed Track Update @ y[%7.2f] z[%7.2f] s2y[%f] s2z[%f] covyz[%f]", p[0], p[1], cov[0], cov[2], cov[1]));
    1066           0 :         break;
    1067             :       }
    1068             :     }
    1069         412 :     if(!kStandAlone) ptrTracklet->UseClusters();
    1070             :     // fill residuals ?!
    1071         412 :     AliTracker::FillResiduals(&t, p, cov, ptrTracklet->GetVolumeId());
    1072             :   
    1073             : 
    1074             :     // register tracklet with the tracker and track
    1075             :     // Save inside the tracklet the track parameters BEFORE track update.
    1076             :     // Commented out their overwriting AFTER track update
    1077             :     // A.Bercuci 3.11.2011
    1078             :     //ptrTracklet->Update(&t); 
    1079         206 :     ptrTracklet = SetTracklet(ptrTracklet);
    1080         412 :     Int_t index(fTracklets->GetEntriesFast()-1);
    1081         206 :     t.SetTracklet(ptrTracklet, index);
    1082             :     // Register info to track
    1083         206 :     t.SetNumberOfClusters();
    1084         206 :     t.UpdateChi2(chi2);
    1085             : 
    1086         206 :     n += ptrTracklet->GetN();
    1087        1030 :     AliDebug(2, Form("Setting Tracklet[%d] @ Idx[%d]", ily, index));
    1088             : 
    1089             :     // Reset material budget if 2 consecutive gold
    1090             : //     if(ilayer>0 && t.GetTracklet(ilayer-1) && ptrTracklet->GetN() + t.GetTracklet(ilayer-1)->GetN() > 20) t.SetBudget(2, 0.);
    1091             : 
    1092             :     // Make backup of the track until is gold
    1093             :     Int_t failed(0);
    1094        1648 :     if(!kStandAlone && (failed = t.MakeBackupTrack())) AliDebug(2, Form("Failed backup on cut[%d]", failed));
    1095             : 
    1096         974 :   } // end layers loop
    1097             :   //printf("clusters[%d] chi2[%f] x[%f] status[%d ", n, t.GetChi2(), t.GetX(), t.GetStatusTRD());
    1098             :   //for(int i=0; i<6; i++) printf("%d ", t.GetStatusTRD(i)); printf("]\n");
    1099             : 
    1100         106 :   if(n && debugLevel > 1){
    1101             :     //Int_t eventNumber = AliTRDtrackerDebug::GetEventNumber();
    1102           0 :     AliTRDtrackV1 track(t);
    1103           0 :     track.SetOwner();
    1104           0 :     (*cstreamer) << "FollowBackProlongation2"
    1105           0 :         << "EventNumber=" << fEventInFile
    1106           0 :         << "track.="      << &track
    1107           0 :         << "\n";
    1108           0 :   }
    1109             :   
    1110             :   return n;
    1111         106 : }
    1112             : 
    1113             : //_________________________________________________________________________
    1114             : Float_t AliTRDtrackerV1::FitRieman(AliTRDseedV1 *tracklets, Double_t *chi2, Int_t *const planes){
    1115             :   //
    1116             :   // Fits a Riemann-circle to the given points without tilting pad correction.
    1117             :   // The fit is performed using an instance of the class AliRieman (equations 
    1118             :   // and transformations see documentation of this class)
    1119             :   // Afterwards all the tracklets are Updated
    1120             :   //
    1121             :   // Parameters: - Array of tracklets (AliTRDseedV1)
    1122             :   //             - Storage for the chi2 values (beginning with direction z)  
    1123             :   //             - Seeding configuration
    1124             :   // Output:     - The curvature
    1125             :   //
    1126           0 :   AliRieman *fitter = AliTRDtrackerV1::GetRiemanFitter();
    1127           0 :   fitter->Reset();
    1128           0 :   Int_t allplanes[] = {0, 1, 2, 3, 4, 5};
    1129           0 :   Int_t *ppl = &allplanes[0];
    1130             :   Int_t maxLayers = 6;
    1131           0 :   if(planes){
    1132             :     maxLayers = 4;
    1133             :     ppl = planes;
    1134           0 :   }
    1135           0 :   for(Int_t il = 0; il < maxLayers; il++){
    1136           0 :     if(!tracklets[ppl[il]].IsOK()) continue;
    1137           0 :     fitter->AddPoint(tracklets[ppl[il]].GetX0(), tracklets[ppl[il]].GetYfit(0), tracklets[ppl[il]].GetZfit(0),1,10);
    1138           0 :   }
    1139           0 :   fitter->Update();
    1140             :   // Set the reference position of the fit and calculate the chi2 values
    1141           0 :   memset(chi2, 0, sizeof(Double_t) * 2);
    1142           0 :   for(Int_t il = 0; il < maxLayers; il++){
    1143             :     // Reference positions
    1144           0 :     tracklets[ppl[il]].Init(fitter);
    1145             :     
    1146             :     // chi2
    1147           0 :     if((!tracklets[ppl[il]].IsOK()) && (!planes)) continue;
    1148           0 :     chi2[0] += tracklets[ppl[il]].GetChi2Y();
    1149           0 :     chi2[1] += tracklets[ppl[il]].GetChi2Z();
    1150           0 :   }
    1151           0 :   return fitter->GetC();
    1152           0 : }
    1153             : 
    1154             : //_________________________________________________________________________
    1155             : void AliTRDtrackerV1::FitRieman(AliTRDcluster **seedcl, Double_t chi2[2])
    1156             : {
    1157             :   //
    1158             :   // Performs a Riemann helix fit using the seedclusters as spacepoints
    1159             :   // Afterwards the chi2 values are calculated and the seeds are updated
    1160             :   //
    1161             :   // Parameters: - The four seedclusters
    1162             :   //             - The tracklet array (AliTRDseedV1)
    1163             :   //             - The seeding configuration
    1164             :   //             - Chi2 array
    1165             :   //
    1166             :   // debug level 2
    1167             :   //
    1168           0 :   AliRieman *fitter = AliTRDtrackerV1::GetRiemanFitter();
    1169           0 :   fitter->Reset();
    1170           0 :   for(Int_t i = 0; i < 4; i++){
    1171           0 :     fitter->AddPoint(seedcl[i]->GetX(), seedcl[i]->GetY(), seedcl[i]->GetZ(), 1., 10.);
    1172             :   }
    1173           0 :   fitter->Update();
    1174             :   
    1175             :   
    1176             :   // Update the seed and calculated the chi2 value
    1177           0 :   chi2[0] = 0; chi2[1] = 0;
    1178           0 :   for(Int_t ipl = 0; ipl < kNSeedPlanes; ipl++){
    1179             :     // chi2
    1180           0 :     chi2[0] += (seedcl[ipl]->GetZ() - fitter->GetZat(seedcl[ipl]->GetX())) * (seedcl[ipl]->GetZ() - fitter->GetZat(seedcl[ipl]->GetX()));
    1181           0 :     chi2[1] += (seedcl[ipl]->GetY() - fitter->GetYat(seedcl[ipl]->GetX())) * (seedcl[ipl]->GetY() - fitter->GetYat(seedcl[ipl]->GetX()));
    1182             :   }     
    1183           0 : }
    1184             : 
    1185             : 
    1186             : //_________________________________________________________________________
    1187             : Float_t AliTRDtrackerV1::FitTiltedRiemanConstraint(AliTRDseedV1 *tracklets, Double_t zVertex)
    1188             : {
    1189             :   //
    1190             :   // Fits a helix to the clusters. Pad tilting is considered. As constraint it is 
    1191             :   // assumed that the vertex position is set to 0.
    1192             :   // This method is very usefull for high-pt particles
    1193             :   // Basis for the fit: (x - x0)^2 + (y - y0)^2 - R^2 = 0
    1194             :   //      x0, y0: Center of the circle
    1195             :   // Measured y-position: ymeas = y - tan(phiT)(zc - zt)
    1196             :   //      zc: center of the pad row
    1197             :   // Equation which has to be fitted (after transformation):
    1198             :   // a + b * u + e * v + 2*(ymeas + tan(phiT)(z - zVertex))*t = 0
    1199             :   // Transformation:
    1200             :   // t = 1/(x^2 + y^2)
    1201             :   // u = 2 * x * t
    1202             :   // v = 2 * x * tan(phiT) * t
    1203             :   // Parameters in the equation: 
    1204             :   //    a = -1/y0, b = x0/y0, e = dz/dx
    1205             :   //
    1206             :   // The Curvature is calculated by the following equation:
    1207             :   //               - curv = a/Sqrt(b^2 + 1) = 1/R
    1208             :   // Parameters:   - the 6 tracklets
    1209             :   //               - the Vertex constraint
    1210             :   // Output:       - the Chi2 value of the track
    1211             :   //
    1212             :   // debug level 5
    1213             :   //
    1214             : 
    1215           0 :   TLinearFitter *fitter = GetTiltedRiemanFitterConstraint();
    1216           0 :   fitter->StoreData(kTRUE);
    1217           0 :   fitter->ClearPoints();
    1218             :   AliTRDcluster *cl = NULL;
    1219             :   
    1220             :   Float_t x, y, z, w, t, error, tilt;
    1221           0 :   Double_t uvt[2];
    1222             :   Int_t nPoints = 0;
    1223           0 :   for(Int_t ilr = 0; ilr < AliTRDgeometry::kNlayer; ilr++){
    1224           0 :     if(!tracklets[ilr].IsOK()) continue;
    1225           0 :     for(Int_t itb = 0; itb < AliTRDseedV1::kNclusters; itb++){
    1226           0 :       if(!tracklets[ilr].IsUsable(itb)) continue;
    1227           0 :       if(!(cl = tracklets[ilr].GetClusters(itb))) continue;
    1228           0 :       if(!cl->IsInChamber()) continue;
    1229           0 :       x = cl->GetX();
    1230           0 :       y = cl->GetY();
    1231           0 :       z = cl->GetZ();
    1232           0 :       tilt = tracklets[ilr].GetTilt();
    1233             :       // Transformation
    1234           0 :       t = 1./(x * x + y * y);
    1235           0 :       uvt[0] = 2. * x * t;
    1236           0 :       uvt[1] = 2. * x * t * tilt ;
    1237           0 :       w = 2. * (y + tilt * (z - zVertex)) * t;
    1238           0 :       error = 2. * TMath::Sqrt(cl->GetSigmaY2()+tilt*tilt*cl->GetSigmaZ2()) * t;
    1239           0 :       fitter->AddPoint(uvt, w, error);
    1240           0 :       nPoints++;
    1241           0 :     }
    1242           0 :   }
    1243           0 :   fitter->Eval();
    1244             : 
    1245             :   // Calculate curvature
    1246           0 :   Double_t a = fitter->GetParameter(0);
    1247           0 :   Double_t b = fitter->GetParameter(1);
    1248           0 :   Double_t curvature = a/TMath::Sqrt(b*b + 1);
    1249             : 
    1250             :   Float_t chi2track = 0.0;
    1251           0 :   if (nPoints > 0) {
    1252           0 :     chi2track = fitter->GetChisquare()/Double_t(nPoints);
    1253           0 :   }
    1254           0 :   for(Int_t ip = 0; ip < AliTRDtrackerV1::kNPlanes; ip++)
    1255           0 :     tracklets[ip].SetC(curvature, 1);
    1256             : 
    1257           0 :   if(AliLog::GetDebugLevel("TRD", "AliTRDtrackerV1")>3) printf("D-AliTRDtrackerV1::FitTiltedRiemanConstraint: Chi2[%f] C[%5.2e] pt[%8.3f]\n", chi2track, curvature, GetBz()*kB2C/curvature);
    1258             : 
    1259             : /*  if(fkReconstructor->GetRecoParam()->GetStreamLevel(AliTRDrecoParam::kTracker()) >= 5){
    1260             :     //Linear Model on z-direction
    1261             :     Double_t xref = CalculateReferenceX(tracklets);             // Relative to the middle of the stack
    1262             :     Double_t slope = fitter->GetParameter(2);
    1263             :     Double_t zref = slope * xref;
    1264             :     Float_t chi2Z = CalculateChi2Z(tracklets, zref, slope, xref);
    1265             :     Int_t eventNumber = AliTRDtrackerDebug::GetEventNumber();
    1266             :     Int_t candidateNumber = AliTRDtrackerDebug::GetCandidateNumber();
    1267             :     TTreeSRedirector &treeStreamer = *fkReconstructor->GetDebugStream(AliTRDReconstructor::kTracker);
    1268             :     treeStreamer << "FitTiltedRiemanConstraint"
    1269             :     << "EventNumber="           << eventNumber
    1270             :     << "CandidateNumber="       << candidateNumber
    1271             :     << "Curvature="                             << curvature
    1272             :     << "Chi2Track="                             << chi2track
    1273             :     << "Chi2Z="                                         << chi2Z
    1274             :     << "zref="                                          << zref
    1275             :     << "\n";
    1276             :   }*/
    1277           0 :   return chi2track;
    1278           0 : }
    1279             : 
    1280             : //_________________________________________________________________________
    1281             : Float_t AliTRDtrackerV1::FitTiltedRieman(AliTRDseedV1 *tracklets, Bool_t sigError)
    1282             : {
    1283             :   //
    1284             :   // Performs a Riemann fit taking tilting pad correction into account
    1285             :   // The equation of a Riemann circle, where the y position is substituted by the 
    1286             :   // measured y-position taking pad tilting into account, has to be transformed
    1287             :   // into a 4-dimensional hyperplane equation
    1288             :   // Riemann circle: (x-x0)^2 + (y-y0)^2 -R^2 = 0
    1289             :   // Measured y-Position: ymeas = y - tan(phiT)(zc - zt)
    1290             :   //          zc: center of the pad row
    1291             :   //          zt: z-position of the track
    1292             :   // The z-position of the track is assumed to be linear dependent on the x-position
    1293             :   // Transformed equation: a + b * u + c * t + d * v  + e * w - 2 * (ymeas + tan(phiT) * zc) * t = 0
    1294             :   // Transformation:       u = 2 * x * t
    1295             :   //                       v = 2 * tan(phiT) * t
    1296             :   //                       w = 2 * tan(phiT) * (x - xref) * t
    1297             :   //                       t = 1 / (x^2 + ymeas^2)
    1298             :   // Parameters:           a = -1/y0
    1299             :   //                       b = x0/y0
    1300             :   //                       c = (R^2 -x0^2 - y0^2)/y0
    1301             :   //                       d = offset
    1302             :   //                       e = dz/dx
    1303             :   // If the offset respectively the slope in z-position is impossible, the parameters are fixed using 
    1304             :   // results from the simple riemann fit. Afterwards the fit is redone.
    1305             :   // The curvature is calculated according to the formula:
    1306             :   //                       curv = a/(1 + b^2 + c*a) = 1/R
    1307             :   //
    1308             :   // Paramters:   - Array of tracklets (connected to the track candidate)
    1309             :   //              - Flag selecting the error definition
    1310             :   // Output:      - Chi2 values of the track (in Parameter list)
    1311             :   //
    1312           0 :   TLinearFitter *fitter = GetTiltedRiemanFitter();
    1313           0 :   fitter->StoreData(kTRUE);
    1314           0 :   fitter->ClearPoints();
    1315           0 :   AliTRDLeastSquare zfitter;
    1316             :   AliTRDcluster *cl = NULL;
    1317             : 
    1318           0 :   Double_t xref = CalculateReferenceX(tracklets);
    1319           0 :   Double_t x, y, z, t, tilt, dx, w, we, erry, errz;
    1320           0 :   Double_t uvt[4], sumPolY[5], sumPolZ[3];
    1321           0 :   memset(sumPolY, 0, sizeof(Double_t) * 5);
    1322           0 :   memset(sumPolZ, 0, sizeof(Double_t) * 3);
    1323             :   Int_t nPoints = 0;
    1324             :   // Containers for Least-square fitter
    1325           0 :   for(Int_t ipl = 0; ipl < kNPlanes; ipl++){
    1326           0 :     if(!tracklets[ipl].IsOK()) continue;
    1327           0 :     tilt = tracklets[ipl].GetTilt();
    1328           0 :     for(Int_t itb = 0; itb < AliTRDseedV1::kNclusters; itb++){
    1329           0 :       if(!(cl = tracklets[ipl].GetClusters(itb))) continue;
    1330           0 :       if(!cl->IsInChamber()) continue;
    1331           0 :       if (!tracklets[ipl].IsUsable(itb)) continue;
    1332           0 :       x = cl->GetX();
    1333           0 :       y = cl->GetY();
    1334           0 :       z = cl->GetZ();
    1335           0 :       dx = x - xref;
    1336             :       // Transformation
    1337           0 :       t = 1./(x*x + y*y);
    1338           0 :       uvt[0] = 2. * x * t;
    1339           0 :       uvt[1] = t;
    1340           0 :       uvt[2] = 2. * tilt * t;
    1341           0 :       uvt[3] = 2. * tilt * dx * t;
    1342           0 :       w = 2. * (y + tilt*z) * t;
    1343             :       // error definition changes for the different calls
    1344           0 :       we = 2. * t;
    1345           0 :       we *= sigError ? TMath::Sqrt(cl->GetSigmaY2()+tilt*tilt*cl->GetSigmaZ2()) : 0.2;
    1346           0 :       fitter->AddPoint(uvt, w, we);
    1347           0 :       zfitter.AddPoint(&x, z, static_cast<Double_t>(TMath::Sqrt(cl->GetSigmaZ2())));
    1348             :       // adding points for covariance matrix estimation
    1349           0 :       erry = 1./(TMath::Sqrt(cl->GetSigmaY2()) + 0.1);  // 0.1 is a systematic error (due to misalignment and miscalibration)
    1350           0 :       erry *= erry;
    1351           0 :       errz = 1./cl->GetSigmaZ2();
    1352           0 :       for(Int_t ipol = 0; ipol < 5; ipol++){
    1353           0 :         sumPolY[ipol] += erry;
    1354           0 :         erry *= x;
    1355           0 :         if(ipol < 3){
    1356           0 :           sumPolZ[ipol] += errz;
    1357           0 :           errz *= x;
    1358           0 :         }
    1359             :       }
    1360           0 :       nPoints++;
    1361           0 :     }
    1362           0 :   }
    1363           0 :   if (fitter->Eval()) return 1.e10;
    1364           0 :   zfitter.Eval();
    1365             : 
    1366           0 :   Double_t offset = fitter->GetParameter(3);
    1367           0 :   Double_t slope  = fitter->GetParameter(4);
    1368             : 
    1369             :   // Linear fitter  - not possible to make boundaries
    1370             :   // Do not accept non possible z and dzdx combinations
    1371             :   Bool_t acceptablez = kTRUE;
    1372             :   Double_t zref = 0.0;
    1373           0 :   for (Int_t iLayer = 0; iLayer < kNPlanes; iLayer++) {
    1374           0 :     if(!tracklets[iLayer].IsOK()) continue;
    1375           0 :     zref = offset + slope * (tracklets[iLayer].GetX0() - xref);
    1376           0 :     if (TMath::Abs(tracklets[iLayer].GetZfit(0) - zref) > tracklets[iLayer].GetPadLength() * 0.5 + 1.0) 
    1377           0 :       acceptablez = kFALSE;
    1378             :   }
    1379           0 :   if (!acceptablez) {
    1380           0 :     Double_t dzmf       = zfitter.GetFunctionParameter(1);
    1381           0 :     Double_t zmf        = zfitter.GetFunctionValue(&xref);
    1382           0 :     fgTiltedRieman->FixParameter(3, zmf);
    1383           0 :     fgTiltedRieman->FixParameter(4, dzmf);
    1384           0 :     fitter->Eval();
    1385           0 :     fitter->ReleaseParameter(3);
    1386           0 :     fitter->ReleaseParameter(4);
    1387           0 :     offset = fitter->GetParameter(3);
    1388           0 :     slope = fitter->GetParameter(4);
    1389           0 :   }
    1390             : 
    1391             :   // Calculate Curvarture
    1392           0 :   Double_t a     =  fitter->GetParameter(0);
    1393           0 :   Double_t b     =  fitter->GetParameter(1);
    1394           0 :   Double_t c     =  fitter->GetParameter(2);
    1395           0 :   Double_t curvature =  1.0 + b*b - c*a;
    1396           0 :   if (curvature > 0.0) curvature  =  a / TMath::Sqrt(curvature);
    1397             : 
    1398           0 :   Double_t chi2track = fitter->GetChisquare()/Double_t(nPoints);
    1399             : 
    1400             :   // Prepare error calculation
    1401           0 :   TMatrixD covarPolY(3,3);
    1402           0 :   covarPolY(0,0) = sumPolY[0]; covarPolY(1,1) = sumPolY[2]; covarPolY(2,2) = sumPolY[4];
    1403           0 :   covarPolY(0,1) = covarPolY(1,0) = sumPolY[1];
    1404           0 :   covarPolY(0,2) = covarPolY(2,0) = sumPolY[2];
    1405           0 :   covarPolY(2,1) = covarPolY(1,2) = sumPolY[3];
    1406           0 :   covarPolY.Invert();
    1407           0 :   TMatrixD covarPolZ(2,2);
    1408           0 :   covarPolZ(0,0) = sumPolZ[0]; covarPolZ(1,1) = sumPolZ[2];
    1409           0 :   covarPolZ(1,0) = covarPolZ(0,1) = sumPolZ[1];
    1410           0 :   covarPolZ.Invert();
    1411             : 
    1412             :   // Update the tracklets
    1413             :   Double_t dy, dz;
    1414           0 :   Double_t cov[15];
    1415           0 :   memset(cov, 0, sizeof(Double_t) * 15);
    1416           0 :   for(Int_t iLayer = 0; iLayer < AliTRDtrackerV1::kNPlanes; iLayer++) {
    1417             : 
    1418           0 :     x  = tracklets[iLayer].GetX0();
    1419             : //    x1 = x - xref;
    1420             :     y  = 0;
    1421             :     z  = 0;
    1422             :     dy = 0;
    1423             :     dz = 0;
    1424           0 :     memset(cov, 0, sizeof(Double_t) * 3);
    1425           0 :     TMatrixD transform(3,3);
    1426           0 :     transform(0,0) = 1;
    1427           0 :     transform(0,1) = x;
    1428           0 :     transform(0,2) = x*x;
    1429           0 :     transform(1,1) = 1;
    1430           0 :     transform(1,2) = x;
    1431           0 :     transform(2,2) = 1;
    1432           0 :     TMatrixD covariance(transform, TMatrixD::kMult, covarPolY);
    1433           0 :     covariance *= transform.T();
    1434           0 :     TMatrixD transformZ(2,2);
    1435           0 :     transformZ(0,0) = transformZ(1,1) = 1;
    1436           0 :     transformZ(0,1) = x;
    1437           0 :     TMatrixD covarZ(transformZ, TMatrixD::kMult, covarPolZ);
    1438           0 :     covarZ *= transformZ.T();
    1439             :     // y:     R^2 = (x - x0)^2 + (y - y0)^2
    1440             :     //     =>   y = y0 +/- Sqrt(R^2 - (x - x0)^2)
    1441             :     //          R = Sqrt() = 1/Curvature
    1442             :     //     =>   y = y0 +/- Sqrt(1/Curvature^2 - (x - x0)^2)  
    1443           0 :     Double_t res = (x * a + b);                                                         // = (x - x0)/y0
    1444           0 :     res *= res;
    1445           0 :     res  = 1.0 - c * a + b * b - res;                                   // = (R^2 - (x - x0)^2)/y0^2
    1446           0 :     if (res >= 0) {
    1447           0 :       res = TMath::Sqrt(res);
    1448           0 :       y    = (1.0 - res) / a;
    1449           0 :     }
    1450           0 :     cov[0] = covariance(0,0);
    1451           0 :     cov[2] = covarZ(0,0);
    1452           0 :     cov[1] = 0.;
    1453             : 
    1454             :     // dy:      R^2 = (x - x0)^2 + (y - y0)^2
    1455             :     //     =>     y = +/- Sqrt(R^2 - (x - x0)^2) + y0
    1456             :     //     => dy/dx = (x - x0)/Sqrt(R^2 - (x - x0)^2) 
    1457             :     // Curvature: cr = 1/R = a/Sqrt(1 + b^2 - c*a)
    1458             :     //     => dy/dx =  (x - x0)/(1/(cr^2) - (x - x0)^2) 
    1459           0 :     Double_t x0 = -b / a;
    1460           0 :     if (-c * a + b * b + 1 > 0) {
    1461           0 :       if (1.0/(curvature * curvature) - (x - x0) * (x - x0) > 0.0) {
    1462           0 :        Double_t yderiv = (x - x0) / TMath::Sqrt(1.0/(curvature * curvature) - (x - x0) * (x - x0));
    1463           0 :         if (a < 0) yderiv *= -1.0;
    1464             :         dy = yderiv;
    1465           0 :       }
    1466             :     }
    1467           0 :     z  = offset + slope * (x - xref);
    1468             :     dz = slope;
    1469           0 :     tracklets[iLayer].SetYref(0, y);
    1470           0 :     tracklets[iLayer].SetYref(1, dy);
    1471           0 :     tracklets[iLayer].SetZref(0, z);
    1472           0 :     tracklets[iLayer].SetZref(1, dz);
    1473           0 :     tracklets[iLayer].SetC(curvature);
    1474           0 :     tracklets[iLayer].SetCovRef(cov);
    1475           0 :     tracklets[iLayer].SetChi2(chi2track);
    1476           0 :   }
    1477           0 :   if(AliLog::GetDebugLevel("TRD", "AliTRDtrackerV1")>3) printf("D-AliTRDtrackerV1::FitTiltedRieman: Chi2[%f] C[%5.2e] pt[%8.3f]\n", chi2track, curvature, GetBz()*kB2C/curvature);
    1478             :   
    1479             : /*  if(fkReconstructor->GetRecoParam()->GetStreamLevel(AliTRDrecoParam::kTracker) >=5){
    1480             :     TTreeSRedirector &cstreamer = *fkReconstructor->GetDebugStream(AliTRDrecoParam::kTracker);
    1481             :     Int_t eventNumber                   = AliTRDtrackerDebug::GetEventNumber();
    1482             :     Int_t candidateNumber       = AliTRDtrackerDebug::GetCandidateNumber();
    1483             :     Double_t chi2z = CalculateChi2Z(tracklets, offset, slope, xref);
    1484             :     cstreamer << "FitTiltedRieman0"
    1485             :         << "EventNumber="                       << eventNumber
    1486             :         << "CandidateNumber="   << candidateNumber
    1487             :         << "xref="                                              << xref
    1488             :         << "Chi2Z="                                             << chi2z
    1489             :         << "\n";
    1490             :   }*/
    1491           0 :   return chi2track;
    1492           0 : }
    1493             : 
    1494             : 
    1495             : //____________________________________________________________________
    1496             : Double_t AliTRDtrackerV1::FitLine(const AliTRDtrackV1 *track, AliTRDseedV1 *tracklets, Bool_t err, Int_t np, AliTrackPoint *points)
    1497             : {
    1498             :   //
    1499             :   // Fit track with a staight line
    1500             :   // Fills an AliTrackPoint array with np points
    1501             :   // Function should be used to refit tracks when no magnetic field was on
    1502             :   //
    1503           0 :   AliTRDLeastSquare yfitter, zfitter;
    1504             :   AliTRDcluster *cl = NULL;
    1505             : 
    1506           0 :   AliTRDseedV1 work[kNPlanes], *tracklet = NULL;
    1507           0 :   if(!tracklets){
    1508           0 :     for(Int_t ipl = 0; ipl < kNPlanes; ipl++){
    1509           0 :       if(!(tracklet = track->GetTracklet(ipl))) continue;
    1510           0 :       if(!tracklet->IsOK()) continue;
    1511           0 :       new(&work[ipl]) AliTRDseedV1(*tracklet);
    1512             :     }
    1513           0 :     tracklets = &work[0];
    1514           0 :   }
    1515             : 
    1516           0 :   Double_t xref = CalculateReferenceX(tracklets);
    1517           0 :   Double_t x, y, z, dx, ye, yr, tilt;
    1518           0 :   for(Int_t ipl = 0; ipl < kNPlanes; ipl++){
    1519           0 :     if(!tracklets[ipl].IsOK()) continue;
    1520           0 :     for(Int_t itb = 0; itb < fgNTimeBins; itb++){
    1521           0 :       if(!(cl = tracklets[ipl].GetClusters(itb))) continue;
    1522           0 :       if (!tracklets[ipl].IsUsable(itb)) continue;
    1523           0 :       x = cl->GetX();
    1524           0 :       z = cl->GetZ();
    1525           0 :       dx = x - xref;
    1526           0 :       zfitter.AddPoint(&dx, z, static_cast<Double_t>(TMath::Sqrt(cl->GetSigmaZ2())));
    1527           0 :     }
    1528           0 :   }
    1529           0 :   zfitter.Eval();
    1530           0 :   Double_t z0    = zfitter.GetFunctionParameter(0);
    1531           0 :   Double_t dzdx  = zfitter.GetFunctionParameter(1);
    1532           0 :   for(Int_t ipl = 0; ipl < kNPlanes; ipl++){
    1533           0 :     if(!tracklets[ipl].IsOK()) continue;
    1534           0 :     for(Int_t itb = 0; itb < fgNTimeBins; itb++){
    1535           0 :       if(!(cl = tracklets[ipl].GetClusters(itb))) continue;
    1536           0 :       if (!tracklets[ipl].IsUsable(itb)) continue;
    1537           0 :       x = cl->GetX();
    1538           0 :       y = cl->GetY();
    1539           0 :       z = cl->GetZ();
    1540           0 :       tilt = tracklets[ipl].GetTilt();
    1541           0 :       dx = x - xref;
    1542           0 :       yr = y + tilt*(z - z0 - dzdx*dx); 
    1543             :       // error definition changes for the different calls
    1544           0 :       ye = tilt*TMath::Sqrt(cl->GetSigmaZ2());
    1545           0 :       ye += err ? tracklets[ipl].GetSigmaY() : 0.2;
    1546           0 :       yfitter.AddPoint(&dx, yr, ye);
    1547           0 :     }
    1548           0 :   }
    1549           0 :   yfitter.Eval();
    1550           0 :   Double_t y0   = yfitter.GetFunctionParameter(0);
    1551           0 :   Double_t dydx = yfitter.GetFunctionParameter(1);
    1552             :   Double_t chi2 = 0.;//yfitter.GetChisquare()/Double_t(nPoints);
    1553             : 
    1554             :   //update track points array
    1555           0 :   if(np && points){
    1556           0 :     Float_t xyz[3];
    1557           0 :     for(int ip=0; ip<np; ip++){
    1558           0 :       points[ip].GetXYZ(xyz);
    1559           0 :       xyz[1] = y0 + dydx * (xyz[0] - xref);
    1560           0 :       xyz[2] = z0 + dzdx * (xyz[0] - xref);
    1561           0 :       points[ip].SetXYZ(xyz);
    1562             :     }
    1563           0 :   }
    1564             :   return chi2;
    1565           0 : }
    1566             : 
    1567             : 
    1568             : //_________________________________________________________________________
    1569             : Double_t AliTRDtrackerV1::FitRiemanTilt(const AliTRDtrackV1 *track, AliTRDseedV1 *tracklets, Bool_t sigError, Int_t np, AliTrackPoint *points)
    1570             : {
    1571             : //
    1572             : // Performs a Riemann fit taking tilting pad correction into account
    1573             : //
    1574             : // Paramters:   - Array of tracklets (connected to the track candidate)
    1575             : //              - Flag selecting the error definition
    1576             : // Output:      - Chi2 values of the track (in Parameter list)
    1577             : //
    1578             : // The equations which has to be solved simultaneously are:
    1579             : // BEGIN_LATEX
    1580             : // R^{2} = (x-x_{0})^{2} + (y^{*}-y_{0})^{2}
    1581             : // y^{*} = y - tg(h)(z - z_{t})
    1582             : // z_{t} = z_{0}+dzdx*(x-x_{r})
    1583             : // END_LATEX
    1584             : // with (x, y, z) the coordinate of the cluster, (x_0, y_0, z_0) the coordinate of the center of the Riemann circle,
    1585             : // R its radius, x_r a constant refrence radial position in the middle of the TRD stack  and dzdx the slope of the 
    1586             : // track in the x-z plane. Using the following transformations
    1587             : // BEGIN_LATEX
    1588             : // t = 1 / (x^{2} + y^{2})
    1589             : // u = 2 * x * t
    1590             : // v = 2 * tan(h) * t
    1591             : // w = 2 * tan(h) * (x - x_{r}) * t
    1592             : // END_LATEX
    1593             : // One gets the following linear equation
    1594             : // BEGIN_LATEX
    1595             : // a + b * u + c * t + d * v  + e * w = 2 * (y + tg(h) * z) * t
    1596             : // END_LATEX
    1597             : // where the coefficients have the following meaning 
    1598             : // BEGIN_LATEX
    1599             : // a = -1/y_{0}
    1600             : // b = x_{0}/y_{0}
    1601             : // c = (R^{2} -x_{0}^{2} - y_{0}^{2})/y_{0}
    1602             : // d = z_{0}
    1603             : // e = dz/dx
    1604             : // END_LATEX
    1605             : // The error calculation for the free term is thus
    1606             : // BEGIN_LATEX
    1607             : // #sigma = 2 * #sqrt{#sigma^{2}_{y} + (tilt corr ...) + tg^{2}(h) * #sigma^{2}_{z}} * t
    1608             : // END_LATEX
    1609             : //
    1610             : // From this simple model one can compute chi^2 estimates and a rough approximation of pt from the curvature according 
    1611             : // to the formula:
    1612             : // BEGIN_LATEX
    1613             : // C = 1/R = a/(1 + b^{2} + c*a)
    1614             : // END_LATEX
    1615             : //
    1616             : // Authors
    1617             : //   M.Ivanov <M.Ivanov@gsi.de>
    1618             : //   A.Bercuci <A.Bercuci@gsi.de>
    1619             : //   M.Fasel <M.Fasel@gsi.de>
    1620             : 
    1621           0 :   TLinearFitter *fitter = GetTiltedRiemanFitter();
    1622           0 :   fitter->StoreData(kTRUE);
    1623           0 :   fitter->ClearPoints();
    1624           0 :   AliTRDLeastSquare zfitter;
    1625             :   AliTRDcluster *cl = NULL;
    1626             : 
    1627           0 :   AliTRDseedV1 work[kNPlanes], *tracklet = NULL;
    1628           0 :   if(!tracklets){
    1629           0 :     for(Int_t ipl = 0; ipl < kNPlanes; ipl++){
    1630           0 :       if(!(tracklet = track->GetTracklet(ipl))) continue;
    1631           0 :       if(!tracklet->IsOK()) continue;
    1632           0 :       new(&work[ipl]) AliTRDseedV1(*tracklet);
    1633             :     }
    1634           0 :     tracklets = &work[0];
    1635           0 :   }
    1636             : 
    1637           0 :   Double_t xref = CalculateReferenceX(tracklets);
    1638           0 :   if(AliLog::GetDebugLevel("TRD", "AliTRDtrackerV1")>3) printf("D-AliTRDtrackerV1::FitRiemanTilt:\nx0[(0)%6.2f (1)%6.2f (2)%6.2f (3)%6.2f (4)%6.2f (5)%6.2f] xref[%6.2f]", tracklets[0].GetX0(), tracklets[1].GetX0(), tracklets[2].GetX0(), tracklets[3].GetX0(), tracklets[4].GetX0(), tracklets[5].GetX0(), xref);
    1639           0 :   Double_t x, y, z, t, tilt, dx, w, we;
    1640           0 :   Double_t uvt[4];
    1641             :   Int_t nPoints = 0;
    1642             :   // Containers for Least-square fitter
    1643           0 :   for(Int_t ipl = 0; ipl < kNPlanes; ipl++){
    1644           0 :     if(!tracklets[ipl].IsOK()) continue;
    1645           0 :     for(Int_t itb = 0; itb < AliTRDseedV1::kNclusters; itb++){
    1646           0 :       if(!(cl = tracklets[ipl].GetClusters(itb))) continue;
    1647             :       //if (!tracklets[ipl].IsUsable(itb)) continue;
    1648           0 :       x = cl->GetX();
    1649           0 :       y = cl->GetY();
    1650           0 :       z = cl->GetZ();
    1651           0 :       tilt = tracklets[ipl].GetTilt();
    1652           0 :       dx = x - xref;
    1653             :       // Transformation
    1654           0 :       t = 1./(x*x + y*y);
    1655           0 :       uvt[0] = 2. * x * t;
    1656           0 :       uvt[1] = t;
    1657           0 :       uvt[2] = 2. * tilt * t;
    1658           0 :       uvt[3] = 2. * tilt * dx * t;
    1659           0 :       w = 2. * (y + tilt*z) * t;
    1660             :       // error definition changes for the different calls
    1661           0 :       we = 2. * t;
    1662           0 :       we *= sigError ? TMath::Sqrt(cl->GetSigmaY2()) : 0.2;
    1663           0 :       fitter->AddPoint(uvt, w, we);
    1664           0 :       zfitter.AddPoint(&x, z, static_cast<Double_t>(TMath::Sqrt(cl->GetSigmaZ2())));
    1665           0 :       nPoints++;
    1666           0 :     }
    1667           0 :   }
    1668           0 :   if(fitter->Eval()) return 1.E10;
    1669             : 
    1670           0 :   Double_t z0    = fitter->GetParameter(3);
    1671           0 :   Double_t dzdx  = fitter->GetParameter(4);
    1672             : 
    1673             : 
    1674             :   // Linear fitter  - not possible to make boundaries
    1675             :   // Do not accept non possible z and dzdx combinations
    1676             :   Bool_t accept = kTRUE;
    1677             :   Double_t zref = 0.0;
    1678           0 :   for (Int_t iLayer = 0; iLayer < kNPlanes; iLayer++) {
    1679           0 :     if(!tracklets[iLayer].IsOK()) continue;
    1680           0 :     zref = z0 + dzdx * (tracklets[iLayer].GetX0() - xref);
    1681           0 :     if (TMath::Abs(tracklets[iLayer].GetZfit(0) - zref) > tracklets[iLayer].GetPadLength() * 0.5 + 1.0) 
    1682           0 :       accept = kFALSE;
    1683             :   }
    1684           0 :   if (!accept) {
    1685           0 :     zfitter.Eval();
    1686           0 :     Double_t dzmf       = zfitter.GetFunctionParameter(1);
    1687           0 :     Double_t zmf        = zfitter.GetFunctionValue(&xref);
    1688           0 :     fitter->FixParameter(3, zmf);
    1689           0 :     fitter->FixParameter(4, dzmf);
    1690           0 :     fitter->Eval();
    1691           0 :     fitter->ReleaseParameter(3);
    1692           0 :     fitter->ReleaseParameter(4);
    1693           0 :     z0   = fitter->GetParameter(3); // = zmf ?
    1694           0 :     dzdx = fitter->GetParameter(4); // = dzmf ?
    1695           0 :   }
    1696             : 
    1697             :   // Calculate Curvature
    1698           0 :   Double_t a    =  fitter->GetParameter(0);
    1699           0 :   Double_t b    =  fitter->GetParameter(1);
    1700           0 :   Double_t c    =  fitter->GetParameter(2);
    1701           0 :   Double_t y0   = 1. / a;
    1702           0 :   Double_t x0   = -b * y0;
    1703           0 :   Double_t tmp  = y0*y0 + x0*x0 - c*y0;
    1704           0 :   if(tmp<=0.) return 1.E10;
    1705           0 :   Double_t radius    = TMath::Sqrt(tmp);
    1706           0 :   Double_t curvature    =  1.0 + b*b - c*a;
    1707           0 :   if (curvature > 0.0)  curvature  =  a / TMath::Sqrt(curvature);
    1708             : 
    1709             :   // Calculate chi2 of the fit 
    1710           0 :   Double_t chi2 = fitter->GetChisquare()/Double_t(nPoints);
    1711           0 :   if(AliLog::GetDebugLevel("TRD", "AliTRDtrackerV1")>3) printf("D-AliTRDtrackerV1::FitRiemanTilt:x0[%6.2f] y0[%6.2f] R[%6.2f] chi2[%f]\n", x0, y0, radius, chi2);
    1712             : 
    1713             :   // Update the tracklets
    1714           0 :   if(!track){
    1715           0 :     for(Int_t ip = 0; ip < kNPlanes; ip++) {
    1716           0 :       x = tracklets[ip].GetX0();
    1717           0 :       tmp = radius*radius-(x-x0)*(x-x0);  
    1718           0 :       if(tmp <= 0.) continue;
    1719           0 :       tmp = TMath::Sqrt(tmp);  
    1720             : 
    1721             :       // y:     R^2 = (x - x0)^2 + (y - y0)^2
    1722             :       //     =>   y = y0 +/- Sqrt(R^2 - (x - x0)^2)
    1723           0 :       tracklets[ip].SetYref(0, y0 - (y0>0.?1.:-1)*tmp);
    1724             :       //     => dy/dx = (x - x0)/Sqrt(R^2 - (x - x0)^2) 
    1725           0 :       tracklets[ip].SetYref(1, (x - x0) / tmp);
    1726           0 :       tracklets[ip].SetZref(0, z0 + dzdx * (x - xref));
    1727           0 :       tracklets[ip].SetZref(1, dzdx);
    1728           0 :       tracklets[ip].SetC(curvature);
    1729           0 :       tracklets[ip].SetChi2(chi2);
    1730           0 :     }
    1731           0 :   }
    1732             :   //update track points array
    1733           0 :   if(np && points){
    1734           0 :     Float_t xyz[3];
    1735           0 :     for(int ip=0; ip<np; ip++){
    1736           0 :       points[ip].GetXYZ(xyz);
    1737           0 :       xyz[1] = TMath::Abs(xyz[0] - x0) > radius ? 100. : y0 - (y0>0.?1.:-1.)*TMath::Sqrt((radius-(xyz[0]-x0))*(radius+(xyz[0]-x0)));
    1738           0 :       xyz[2] = z0 + dzdx * (xyz[0] - xref);
    1739           0 :       points[ip].SetXYZ(xyz);
    1740             :     }
    1741           0 :   }
    1742             :   
    1743             :   return chi2;
    1744           0 : }
    1745             : 
    1746             : 
    1747             : //____________________________________________________________________
    1748             : Double_t AliTRDtrackerV1::FitKalman(AliTRDtrackV1 *track, AliTRDseedV1 * const tracklets, Bool_t up, Int_t np, AliTrackPoint *points)
    1749             : {
    1750             : //   Kalman filter implementation for the TRD.
    1751             : //   It returns the positions of the fit in the array "points"
    1752             : // 
    1753             : //   Author : A.Bercuci@gsi.de
    1754             : 
    1755             :   // printf("Start track @ x[%f]\n", track->GetX());
    1756             :         
    1757             :   //prepare marker points along the track
    1758           0 :   Int_t ip = np ? 0 : 1;
    1759           0 :   while(ip<np){
    1760           0 :     if((up?-1:1) * (track->GetX() - points[ip].GetX()) > 0.) break;
    1761             :     //printf("AliTRDtrackerV1::FitKalman() : Skip track marker x[%d] = %7.3f. Before track start ( %7.3f ).\n", ip, points[ip].GetX(), track->GetX());
    1762           0 :     ip++;
    1763             :   }
    1764             :   //if(points) printf("First marker point @ x[%d] = %f\n", ip, points[ip].GetX());
    1765             : 
    1766             : 
    1767           0 :   AliTRDseedV1 tracklet;
    1768             :   AliTRDseedV1 *ptrTracklet = NULL;
    1769             : 
    1770             :   //Loop through the TRD planes
    1771           0 :   for (Int_t jplane = 0; jplane < kNPlanes; jplane++) {
    1772             :     // GET TRACKLET OR BUILT IT         
    1773           0 :     Int_t iplane = up ? jplane : kNPlanes - 1 - jplane;
    1774           0 :     if(tracklets){ 
    1775           0 :       if(!(ptrTracklet = &tracklets[iplane])) continue;
    1776             :     }else{
    1777           0 :       if(!(ptrTracklet  = track->GetTracklet(iplane))){ 
    1778             :       /*AliTRDtrackerV1 *tracker = NULL;
    1779             :         if(!(tracker = dynamic_cast<AliTRDtrackerV1*>( AliTRDrecoParam:Tracker()))) continue;
    1780             :         ptrTracklet = new(&tracklet) AliTRDseedV1(iplane);
    1781             :         if(!tracker->MakeTracklet(ptrTracklet, track)) */
    1782           0 :         continue;
    1783             :       }
    1784             :     }
    1785           0 :     if(!ptrTracklet->IsOK()) continue;
    1786             : 
    1787           0 :     Double_t x = ptrTracklet->GetX0();
    1788             : 
    1789           0 :     while(ip < np){
    1790             :       //don't do anything if next marker is after next update point.
    1791           0 :       if((up?-1:1) * (points[ip].GetX() - x) - AliTRDReconstructor::GetMaxStep() < 0) break;
    1792           0 :       if(((up?-1:1) * (points[ip].GetX() - track->GetX()) < 0) && !PropagateToX(*track, points[ip].GetX(), AliTRDReconstructor::GetMaxStep())) return -1.;
    1793             :       
    1794           0 :       Double_t xyz[3]; // should also get the covariance
    1795           0 :       track->GetXYZ(xyz);
    1796           0 :       track->Global2LocalPosition(xyz, track->GetAlpha());
    1797           0 :       points[ip].SetXYZ(xyz[0], xyz[1], xyz[2]);
    1798           0 :       ip++;
    1799           0 :     }
    1800             :     // printf("plane[%d] tracklet[%p] x[%f]\n", iplane, ptrTracklet, x);
    1801             : 
    1802             :     // Propagate closer to the next update point 
    1803           0 :     if(((up?-1:1) * (x - track->GetX()) + AliTRDReconstructor::GetMaxStep() < 0) && !PropagateToX(*track, x + (up?-1:1)*AliTRDReconstructor::GetMaxStep(), AliTRDReconstructor::GetMaxStep())) return -1.;
    1804             : 
    1805           0 :     if(!AdjustSector(track)) return -1;
    1806           0 :     if(TMath::Abs(track->GetSnp()) > AliTRDReconstructor::GetMaxSnp()) return -1;
    1807             :     
    1808             :     //load tracklet to the tracker and the track
    1809             : /*    Int_t index;
    1810             :     if((index = FindTracklet(ptrTracklet)) < 0){
    1811             :       ptrTracklet = SetTracklet(&tracklet);
    1812             :       index = fTracklets->GetEntriesFast()-1;
    1813             :     }
    1814             :     track->SetTracklet(ptrTracklet, index);*/
    1815             : 
    1816             : 
    1817             :     // register tracklet to track with tracklet creation !!
    1818             :     // PropagateBack : loaded tracklet to the tracker and update index 
    1819             :     // RefitInward : update index 
    1820             :     // MakeTrack   : loaded tracklet to the tracker and update index 
    1821           0 :     if(!tracklets) track->SetTracklet(ptrTracklet, -1);
    1822             :     
    1823             :   
    1824             :     //Calculate the mean material budget along the path inside the chamber
    1825           0 :     Double_t xyz0[3]; track->GetXYZ(xyz0);
    1826           0 :     Double_t alpha = track->GetAlpha();
    1827           0 :     Double_t xyz1[3], y, z;
    1828           0 :     if(!track->GetProlongation(x, y, z)) return -1;
    1829           0 :     xyz1[0] =  x * TMath::Cos(alpha) - y * TMath::Sin(alpha); 
    1830           0 :     xyz1[1] = +x * TMath::Sin(alpha) + y * TMath::Cos(alpha);
    1831           0 :     xyz1[2] =  z;
    1832           0 :     if(TMath::Abs(xyz0[0] - xyz1[0]) < 1e-3 && TMath::Abs(xyz0[1] - xyz1[1]) < 1e-3) continue; // check wheter we are at the same global x position
    1833           0 :     Double_t param[7];
    1834           0 :     if(AliTracker::MeanMaterialBudget(xyz0, xyz1, param) <=0.) break;        
    1835           0 :     Double_t xrho = param[0]*param[4]; // density*length
    1836           0 :     Double_t xx0  = param[1]; // radiation length
    1837             :     
    1838             :     //Propagate the track
    1839           0 :     track->PropagateTo(x, xx0, xrho);
    1840           0 :     if (!AdjustSector(track)) break;
    1841             :   
    1842             :     //Update track
    1843           0 :     Double_t cov[3]; ptrTracklet->GetCovAt(x, cov);
    1844           0 :     Double_t p[2] = { ptrTracklet->GetY(), ptrTracklet->GetZ()};
    1845           0 :     Double_t chi2 = ((AliExternalTrackParam*)track)->GetPredictedChi2(p, cov);
    1846           0 :     if(chi2<1e+10) ((AliExternalTrackParam*)track)->Update(p, cov);
    1847           0 :     if(!up) continue;
    1848             : 
    1849             :                 //Reset material budget if 2 consecutive gold
    1850           0 :                 if(iplane>0 && track->GetTracklet(iplane-1) && ptrTracklet->GetN() + track->GetTracklet(iplane-1)->GetN() > 20) track->SetBudget(2, 0.);
    1851           0 :         } // end planes loop
    1852             : 
    1853             :   // extrapolation
    1854           0 :   while(ip < np){
    1855           0 :     if(((up?-1:1) * (points[ip].GetX() - track->GetX()) < 0) && !PropagateToX(*track, points[ip].GetX(), AliTRDReconstructor::GetMaxStep())) return -1.;
    1856             :     
    1857           0 :     Double_t xyz[3]; // should also get the covariance
    1858           0 :     track->GetXYZ(xyz); 
    1859           0 :     track->Global2LocalPosition(xyz, track->GetAlpha());
    1860           0 :     points[ip].SetXYZ(xyz[0], xyz[1], xyz[2]);
    1861           0 :     ip++;
    1862           0 :   }
    1863             : 
    1864           0 :         return track->GetChi2();
    1865           0 : }
    1866             : 
    1867             : //_________________________________________________________________________
    1868             : Float_t AliTRDtrackerV1::CalculateChi2Z(const AliTRDseedV1 *tracklets, Double_t offset, Double_t slope, Double_t xref)
    1869             : {
    1870             :   //
    1871             :   // Calculates the chi2-value of the track in z-Direction including tilting pad correction.
    1872             :   // A linear dependence on the x-value serves as a model.
    1873             :   // The parameters are related to the tilted Riemann fit.
    1874             :   // Parameters: - Array of tracklets (AliTRDseedV1) related to the track candidate
    1875             :   //             - the offset for the reference x
    1876             :   //             - the slope
    1877             :   //             - the reference x position
    1878             :   // Output:     - The Chi2 value of the track in z-Direction
    1879             :   //
    1880             :   Float_t chi2Z = 0, nLayers = 0;
    1881           0 :   for (Int_t iLayer = 0; iLayer < AliTRDgeometry::kNlayer; iLayer++) {
    1882           0 :     if(!tracklets[iLayer].IsOK()) continue;
    1883           0 :     Double_t z = offset + slope * (tracklets[iLayer].GetX0() - xref);
    1884           0 :     chi2Z += TMath::Abs(tracklets[iLayer].GetZfit(0) - z);
    1885           0 :     nLayers++;
    1886           0 :   }
    1887           0 :   chi2Z /= TMath::Max((nLayers - 3.0),1.0);
    1888           0 :   return chi2Z;
    1889             : }
    1890             : 
    1891             : //_____________________________________________________________________________
    1892             : Int_t AliTRDtrackerV1::PropagateToX(AliTRDtrackV1 &t, Double_t xToGo, Double_t maxStep)
    1893             : {
    1894             :   //
    1895             :   // Starting from current X-position of track <t> this function
    1896             :   // extrapolates the track up to radial position <xToGo> in steps of <maxStep>. 
    1897             :   // Returns 1 if track reaches the plane, and 0 otherwise 
    1898             :   //
    1899             : 
    1900             :   // Current track X-position
    1901        2680 :   Double_t xpos = t.GetX()/*,
    1902             :            mass = t.GetMass()*/;
    1903             : 
    1904             :   // Direction: inward or outward
    1905        1340 :   Double_t dir  = (xpos < xToGo) ? 1.0 : -1.0;
    1906             : 
    1907       12610 :   while (((xToGo - xpos) * dir) > AliTRDReconstructor::GetEpsilon()) {
    1908             : //    printf("to go %f\n", (xToGo - xpos) * dir);
    1909        9959 :     Double_t xyz0[3];
    1910        9959 :     Double_t xyz1[3];
    1911        9959 :     Double_t param[7];
    1912             :     Double_t x;
    1913        9959 :     Double_t y;
    1914        9959 :     Double_t z;
    1915             : 
    1916             :     // The next step size
    1917        9959 :     Double_t step = dir * TMath::Min(TMath::Abs(xToGo-xpos),maxStep);
    1918             : 
    1919             :     // Get the global position of the starting point
    1920        9959 :     t.GetXYZ(xyz0);
    1921             : 
    1922             :     // X-position after next step
    1923        9959 :     x = xpos + step;
    1924             : 
    1925             :     // Get local Y and Z at the X-position of the next step
    1926        9985 :     if(t.GetProlongation(x,y,z)<0) return 0; // No prolongation possible
    1927             : 
    1928             :     // The global position of the end point of this prolongation step
    1929        9933 :     xyz1[0] =  x * TMath::Cos(t.GetAlpha()) - y * TMath::Sin(t.GetAlpha()); 
    1930        9933 :     xyz1[1] = +x * TMath::Sin(t.GetAlpha()) + y * TMath::Cos(t.GetAlpha());
    1931        9933 :     xyz1[2] =  z;
    1932             : 
    1933             :     // Calculate the mean material budget between start and
    1934             :     // end point of this prolongation step
    1935        9933 :     if(AliTracker::MeanMaterialBudget(xyz0, xyz1, param)<=0.) return 0;
    1936             :     
    1937             :     // Propagate the track to the X-position after the next step
    1938        9936 :     if (!t.PropagateTo(x, param[1], param[0]*param[4])) return 0;
    1939             : 
    1940             : /*    // Correct for mean material budget
    1941             :     Double_t dEdx(0.),
    1942             :              bg(TMath::Abs(t.GetP()/mass));
    1943             :     if(AliLog::GetDebugLevel("TRD", "AliTRDtrackerV1")>=3){
    1944             :       const char *pn[] = {"rho", "x/X0", "<A>", "<Z>", "L", "<Z/A>", "Nb"};
    1945             :       printf("D-AliTRDtrackerV1::PropagateTo(): x[%6.2f] bg[%6.2f]\n", xpos, bg);
    1946             :       printf("     param :: %s[%e] %s[%e] %s[%e] %s[%e] %s[%e] %s[%e] %s[%e]\n"
    1947             :           , pn[0], param[0]
    1948             :           , pn[1], param[1]
    1949             :           , pn[2], param[2]
    1950             :           , pn[3], param[3]
    1951             :           , pn[4], param[4]
    1952             :           , pn[5], param[5]
    1953             :           , pn[6], param[6]);
    1954             :     }  
    1955             :     switch(fgBB){
    1956             :     case kSolid:
    1957             :       dEdx = AliExternalTrackParam::BetheBlochSolid(bg);
    1958             :       break;
    1959             :     case kGas:
    1960             :       dEdx = AliExternalTrackParam::BetheBlochGas(bg);
    1961             :       break;
    1962             :     case kGeant:
    1963             :       { // mean exitation energy (GeV)
    1964             :         Double_t mee = ((param[3] < 13.) ? (12. * param[3] + 7.) : (9.76 * param[3] + 58.8 * TMath::Power(param[3],-0.19))) * 1.e-9;
    1965             :         Double_t mZA = param[5]>1.e-5?param[5]:(param[3]/param[2]);
    1966             :         if(AliLog::GetDebugLevel("TRD", "AliTRDtrackerV1")>=3) printf("D-AliTRDtrackerV1::PropagateTo(): Mee[%e] <Z/A>[%e]\n", mee, mZA);
    1967             :         // protect against failed calculation of rho in MeanMaterialBudget()
    1968             :         dEdx = AliExternalTrackParam::BetheBlochGeant(bg, param[0]>1.e-6?param[0]:2.33, 0.2, 3., mee, mZA);
    1969             :       }
    1970             :       break;
    1971             :     }
    1972             :     if(AliLog::GetDebugLevel("TRD", "AliTRDtrackerV1")>=2) printf("D-AliTRDtrackerV1::PropagateTo(): dEdx(bg=%e, m=%e)= %e[GeV/cm]\n", bg, mass, dEdx);
    1973             :     if (!t.CorrectForMeanMaterialdEdx(param[1], dir*param[0]*param[4], mass, dEdx)) return 0;
    1974             : */
    1975             :     // Rotate the track if necessary
    1976        9930 :     if(!AdjustSector(&t)) return 0;
    1977             : 
    1978             :     // New track X-position
    1979        9930 :     xpos = t.GetX();
    1980             : 
    1981       19889 :   }
    1982             : 
    1983        1311 :   return 1;
    1984             : 
    1985        1340 : }
    1986             : 
    1987             : //_____________________________________________________________________________
    1988             : Bool_t AliTRDtrackerV1::ReadClusters(TTree *clusterTree)
    1989             : {
    1990             :   //
    1991             :   // Reads AliTRDclusters from the file. 
    1992             :   // The names of the cluster tree and branches 
    1993             :   // should match the ones used in AliTRDclusterizer::WriteClusters()
    1994             :   //
    1995             : 
    1996          16 :   Int_t nsize = Int_t(clusterTree->GetTotBytes() / (sizeof(AliTRDcluster))); 
    1997             :   static TObjArray* clusterArray=0;// = new TObjArray(nsize+1000); 
    1998             :   
    1999           8 :   TBranch *branch = clusterTree->GetBranch("TRDcluster");
    2000           8 :   if (!branch) {
    2001           0 :     AliError("Can't get the branch !");
    2002           0 :     return kFALSE;
    2003             :   }
    2004           8 :   branch->SetAddress(&clusterArray); 
    2005             : 
    2006           8 :   if(!fClusters){ 
    2007           0 :     Float_t nclusters =  fkRecoParam->GetNClusters();
    2008           0 :     if(fkReconstructor->IsHLT()) nclusters /= AliTRDgeometry::kNsector;
    2009           0 :     fClusters = new TClonesArray("AliTRDcluster", Int_t(nclusters));
    2010           0 :     fClusters->SetOwner(kTRUE);
    2011           0 :     SetClustersOwner();
    2012           0 :     AliInfo(Form("Tracker owning clusters @ %p", (void*)fClusters));
    2013           0 :   }
    2014             :   
    2015             :   // Loop through all entries in the tree
    2016           8 :   Int_t nEntries   = (Int_t) clusterTree->GetEntries();
    2017             :   Int_t nbytes     = 0;
    2018             :   Int_t ncl        = 0;
    2019             :   AliTRDcluster *c = NULL;
    2020         714 :   for (Int_t iEntry = 0; iEntry < nEntries; iEntry++) {
    2021             :     // Import the tree
    2022         349 :     nbytes += clusterTree->GetEvent(iEntry);  
    2023             :     
    2024             :     // Get the number of points in the detector
    2025         349 :     Int_t nCluster = clusterArray->GetEntriesFast();  
    2026       37602 :     for (Int_t iCluster = 0; iCluster < nCluster; iCluster++) { 
    2027       18452 :       if(!(c = (AliTRDcluster *) clusterArray->UncheckedAt(iCluster))) continue;
    2028       18452 :       new((*fClusters)[ncl++]) AliTRDcluster(*c);
    2029       36904 :       delete (clusterArray->RemoveAt(iCluster)); 
    2030             :     }
    2031             :   }
    2032             :   //  delete clusterArray;
    2033           8 :   clusterArray->Delete(); //RS normally should not contain clusters anymore
    2034             : 
    2035             :   return kTRUE;
    2036           8 : }
    2037             : 
    2038             : //_____________________________________________________________________________
    2039             : Int_t AliTRDtrackerV1::LoadClusters(TTree *cTree)
    2040             : {
    2041             :   //
    2042             :   // Fills clusters into TRD tracking sectors
    2043             :   //
    2044             :   
    2045          16 :   fkRecoParam = fkReconstructor->GetRecoParam(); // load reco param for this event
    2046             : 
    2047             : //  if(!fkReconstructor->IsWritingClusters()) AliInfo(Form("IsWritingClusters[%c]", fkReconstructor->IsWritingClusters()?'y':'n'));
    2048           8 :   if(!(fClusters = AliTRDReconstructor::GetClusters())){
    2049           0 :     AliWarning("Clusters unavailable from TRD reconstructor. Trying reading from tree ...");
    2050           0 :   } else {
    2051           8 :     if(!ReadClusters(cTree)) {
    2052           0 :       AliError("Reading clusters from tree failed.");
    2053           0 :       return 1;
    2054             :     }
    2055             :   }
    2056             : 
    2057          16 :   if(!fClusters || !fClusters->GetEntriesFast()){ 
    2058           0 :     AliInfo("No TRD clusters");
    2059           0 :     return 1;
    2060          56 :   } else AliInfo(Form("Using :: clusters[%d] onl.tracklets[%d] onl.tracks[%d]",
    2061             :     fClusters?fClusters->GetEntriesFast():0,
    2062             :     AliTRDReconstructor::GetTracklets()?AliTRDReconstructor::GetTracklets()->GetEntriesFast():0,
    2063             :     AliTRDReconstructor::GetTracks()?AliTRDReconstructor::GetTracks()->GetEntriesFast():0));
    2064             : 
    2065           8 :   BuildTrackingContainers();  
    2066             : 
    2067           8 :   return 0;
    2068           8 : }
    2069             : 
    2070             : //_____________________________________________________________________________
    2071             : Int_t AliTRDtrackerV1::LoadClusters(TClonesArray * const clusters)
    2072             : {
    2073             :   //
    2074             :   // Fills clusters into TRD tracking sectors
    2075             :   // Function for use in the HLT
    2076             :   
    2077           0 :   if(!clusters || !clusters->GetEntriesFast()){ 
    2078           0 :     AliInfo("No TRD clusters");
    2079           0 :     return 1;
    2080           0 :   } else AliInfo(Form("Using :: external.clusters[%d]", clusters->GetEntriesFast()));
    2081             : 
    2082             : 
    2083           0 :   fClusters = clusters;
    2084             : 
    2085           0 :   fkRecoParam = fkReconstructor->GetRecoParam(); // load reco param for this event
    2086           0 :   BuildTrackingContainers();  
    2087             : 
    2088           0 :   return 0;
    2089           0 : }
    2090             : 
    2091             : 
    2092             : //____________________________________________________________________
    2093             : Int_t AliTRDtrackerV1::BuildTrackingContainers()
    2094             : {
    2095             : // Building tracking containers for clusters
    2096             : 
    2097          16 :   Int_t nin(0), ncl(fClusters->GetEntriesFast());
    2098       36920 :   while (ncl--) {
    2099       18452 :     AliTRDcluster *c = (AliTRDcluster *) fClusters->UncheckedAt(ncl);
    2100       35343 :     if(c->IsInChamber()) nin++;
    2101       18452 :     if(fkReconstructor->IsHLT()) c->SetRPhiMethod(AliTRDcluster::kCOG);
    2102       18452 :     Int_t detector       = c->GetDetector();
    2103       18452 :     Int_t sector         = fGeom->GetSector(detector);
    2104       18452 :     Int_t stack          = fGeom->GetStack(detector);
    2105       18452 :     Int_t layer          = fGeom->GetLayer(detector);
    2106             :     
    2107       18452 :     fTrSec[sector].GetChamber(stack, layer, kTRUE)->InsertCluster(c, ncl);
    2108             :   }
    2109             : 
    2110         304 :   for(int isector =0; isector<AliTRDgeometry::kNsector; isector++){ 
    2111         144 :     if(!fTrSec[isector].GetNChambers()) continue;
    2112          42 :     fTrSec[isector].Init(fkReconstructor);
    2113          42 :   }
    2114             : 
    2115           8 :   return nin;
    2116             : }
    2117             : 
    2118             : 
    2119             : 
    2120             : //____________________________________________________________________
    2121             : void AliTRDtrackerV1::UnloadClusters() 
    2122             : { 
    2123             : //
    2124             : // Clears the arrays of clusters and tracks. Resets sectors and timebins 
    2125             : // If option "force" is also set the containers are also deleted. This is useful 
    2126             : // in case of HLT
    2127             : 
    2128          16 :   if(fTracks){ 
    2129           0 :     fTracks->Delete(); 
    2130           0 :     if(HasRemoveContainers()){delete fTracks; fTracks = NULL;}
    2131             :   }
    2132           8 :   if(fTracklets){ 
    2133           8 :     fTracklets->Delete();
    2134           8 :     if(HasRemoveContainers()){delete fTracklets; fTracklets = NULL;}
    2135             :   }
    2136          16 :   if(fClusters && IsClustersOwner()){
    2137           0 :     AliInfo(Form("tracker[%p] clearing %d own clusters @ %p", (void*)this, fClusters->GetEntries(), (void*)fClusters));
    2138           0 :     fClusters->Delete();
    2139             : //     
    2140             : //     // save clusters array in the reconstructor for further use.
    2141             : //     if(!fkReconstructor->IsWritingClusters()){
    2142             : //       AliTRDReconstructor::SetClusters(fClusters);
    2143             : //       SetClustersOwner(kFALSE);
    2144             : //     } else AliTRDReconstructor::SetClusters(NULL);
    2145           0 :   }
    2146             : 
    2147         304 :   for (int i = 0; i < AliTRDgeometry::kNsector; i++) fTrSec[i].Clear();
    2148             : 
    2149             :   // Increment the Event Number
    2150           8 :   AliTRDtrackerDebug::SetEventNumber(AliTRDtrackerDebug::GetEventNumber()  + 1);
    2151           8 : }
    2152             : 
    2153             : // //____________________________________________________________________
    2154             : // void AliTRDtrackerV1::UseClusters(const AliKalmanTrack *t, Int_t) const
    2155             : // {
    2156             : //   const AliTRDtrackV1 *track = dynamic_cast<const AliTRDtrackV1*>(t);
    2157             : //   if(!track) return;
    2158             : // 
    2159             : //   AliTRDseedV1 *tracklet = NULL;
    2160             : //   for(Int_t ily=AliTRDgeometry::kNlayer; ily--;){
    2161             : //     if(!(tracklet = track->GetTracklet(ily))) continue;
    2162             : //     AliTRDcluster *c = NULL;
    2163             : //     for(Int_t ic=AliTRDseed::kNclusters; ic--;){
    2164             : //       if(!(c=tracklet->GetClusters(ic))) continue;
    2165             : //       c->Use();
    2166             : //     }
    2167             : //   }
    2168             : // }
    2169             : // 
    2170             : 
    2171             : //_____________________________________________________________________________
    2172             : Bool_t AliTRDtrackerV1::AdjustSector(AliTRDtrackV1 *const track) 
    2173             : {
    2174             :   //
    2175             :   // Rotates the track when necessary
    2176             :   //
    2177             : 
    2178       22810 :   Double_t alpha = AliTRDgeometry::GetAlpha(); 
    2179       11405 :   Double_t y     = track->GetY();
    2180       11405 :   Double_t ymax  = track->GetX()*TMath::Tan(0.5*alpha);
    2181             :   
    2182       11405 :   if      (y >  ymax) {
    2183          20 :     if (!track->Rotate( alpha)) {
    2184           0 :       return kFALSE;
    2185             :     }
    2186             :   } 
    2187       11385 :   else if (y < -ymax) {
    2188          26 :     if (!track->Rotate(-alpha)) {
    2189           0 :       return kFALSE;   
    2190             :     }
    2191             :   } 
    2192             : 
    2193       11405 :   return kTRUE;
    2194             : 
    2195       11405 : }
    2196             : 
    2197             : 
    2198             : //____________________________________________________________________
    2199             : AliTRDseedV1* AliTRDtrackerV1::GetTracklet(const AliTRDtrackV1 *const track, Int_t p, Int_t &idx)
    2200             : {
    2201             :   // Find tracklet for TRD track <track>
    2202             :   // Parameters
    2203             :   // - track
    2204             :   // - sector
    2205             :   // - plane
    2206             :   // - index
    2207             :   // Output
    2208             :   // tracklet
    2209             :   // index
    2210             :   // Detailed description
    2211             :   //
    2212         504 :   idx = track->GetTrackletIndex(p);
    2213         710 :   AliTRDseedV1 *tracklet = (idx<0) ? NULL : (AliTRDseedV1*)fTracklets->UncheckedAt(idx);
    2214             : 
    2215         252 :   return tracklet;
    2216             : }
    2217             : 
    2218             : //____________________________________________________________________
    2219             : AliTRDseedV1* AliTRDtrackerV1::SetTracklet(const AliTRDseedV1 * const tracklet)
    2220             : {
    2221             :   // Add this tracklet to the list of tracklets stored in the tracker
    2222             :   //
    2223             :   // Parameters
    2224             :   //   - tracklet : pointer to the tracklet to be added to the list
    2225             :   //
    2226             :   // Output
    2227             :   //   - the index of the new tracklet in the tracker tracklets list
    2228             :   //
    2229             :   // Detailed description
    2230             :   // Build the tracklets list if it is not yet created (late initialization)
    2231             :   // and adds the new tracklet to the list.
    2232             :   //
    2233         412 :   if(!fTracklets){
    2234           4 :     fTracklets = new TClonesArray("AliTRDseedV1", AliTRDgeometry::Nsector()*kMaxTracksStack);
    2235           2 :     fTracklets->SetOwner(kTRUE);
    2236           2 :   }
    2237         206 :   Int_t nentries = fTracklets->GetEntriesFast();
    2238         412 :   return new ((*fTracklets)[nentries]) AliTRDseedV1(*tracklet);
    2239           0 : }
    2240             : 
    2241             : //____________________________________________________________________
    2242             : AliTRDtrackV1* AliTRDtrackerV1::SetTrack(const AliTRDtrackV1 * const track)
    2243             : {
    2244             :   // Add this track to the list of tracks stored in the tracker
    2245             :   //
    2246             :   // Parameters
    2247             :   //   - track : pointer to the track to be added to the list
    2248             :   //
    2249             :   // Output
    2250             :   //   - the pointer added
    2251             :   //
    2252             :   // Detailed description
    2253             :   // Build the tracks list if it is not yet created (late initialization)
    2254             :   // and adds the new track to the list.
    2255             :   //
    2256           0 :   if(!fTracks){
    2257           0 :     fTracks = new TClonesArray("AliTRDtrackV1", AliTRDgeometry::Nsector()*kMaxTracksStack);
    2258           0 :     fTracks->SetOwner(kTRUE);
    2259           0 :   }
    2260           0 :   Int_t nentries = fTracks->GetEntriesFast();
    2261           0 :   return new ((*fTracks)[nentries]) AliTRDtrackV1(*track);
    2262           0 : }
    2263             : 
    2264             : 
    2265             : 
    2266             : //____________________________________________________________________
    2267             : Int_t AliTRDtrackerV1::Clusters2TracksSM(Int_t sector, AliESDEvent *esd)
    2268             : {
    2269             :   //
    2270             :   // Steer tracking for one SM.
    2271             :   //
    2272             :   // Parameters :
    2273             :   //   sector  : Array of (SM) propagation layers containing clusters
    2274             :   //   esd     : The current ESD event. On output it contains the also
    2275             :   //             the ESD (TRD) tracks found in this SM. 
    2276             :   //
    2277             :   // Output :
    2278             :   //   Number of tracks found in this TRD supermodule.
    2279             :   // 
    2280             :   // Detailed description
    2281             :   //
    2282             :   // 1. Unpack AliTRDpropagationLayers objects for each stack.
    2283             :   // 2. Launch stack tracking. 
    2284             :   //    See AliTRDtrackerV1::Clusters2TracksStack() for details.
    2285             :   // 3. Pack results in the ESD event.
    2286             :   //
    2287             :   
    2288             :   Int_t nTracks   = 0;
    2289             :   Int_t nChambers = 0;
    2290             :   AliTRDtrackingChamber **stack = NULL, *chamber = NULL;
    2291           0 :   for(int istack = 0; istack<AliTRDgeometry::kNstack; istack++){
    2292           0 :     if(!(stack = fTrSec[sector].GetStack(istack))) continue;
    2293             :     nChambers = 0;
    2294           0 :     for(int ilayer=0; ilayer<AliTRDgeometry::kNlayer; ilayer++){
    2295           0 :       if(!(chamber = stack[ilayer])) continue;
    2296           0 :       if(chamber->GetNClusters() < fgNTimeBins * fkRecoParam->GetFindableClusters()) continue;
    2297           0 :       nChambers++;
    2298             :       //AliInfo(Form("sector %d stack %d layer %d clusters %d", sector, istack, ilayer, chamber->GetNClusters()));
    2299           0 :     }
    2300           0 :     if(nChambers < 4) continue;
    2301             :     //AliInfo(Form("Doing stack %d", istack));
    2302           0 :     nTracks += Clusters2TracksStack(stack, fTracksESD);
    2303           0 :   }
    2304           0 :   if(nTracks) AliDebug(2, Form("Number of tracks: SM_%02d[%d]", sector, nTracks));
    2305             : 
    2306           0 :   for(int itrack=0; itrack<nTracks; itrack++){
    2307           0 :     AliESDtrack *esdTrack((AliESDtrack*)(fTracksESD->operator[](itrack)));
    2308           0 :     Int_t id = esd->AddTrack(esdTrack);
    2309             : 
    2310             :     // set ESD id to stand alone TRD tracks
    2311           0 :     if (fkRecoParam->GetStreamLevel(AliTRDrecoParam::kTracker) > 0 || AliTRDReconstructor::GetStreamLevel()>0 ){ 
    2312           0 :       esdTrack=esd->GetTrack(id);
    2313             :       TObject *o(NULL); Int_t ic(0);
    2314             :       AliTRDtrackV1 *calibTrack(NULL); 
    2315           0 :       while((o = esdTrack->GetCalibObject(ic++))){
    2316           0 :         if(!(calibTrack = dynamic_cast<AliTRDtrackV1*>(o))) continue;
    2317           0 :         calibTrack->SetESDid(esdTrack->GetID());
    2318           0 :         break;
    2319             :       }
    2320           0 :     }
    2321             :   }
    2322             : 
    2323             :   // Reset Track and Candidate Number
    2324           0 :   AliTRDtrackerDebug::SetCandidateNumber(0);
    2325           0 :   AliTRDtrackerDebug::SetTrackNumber(0);
    2326             : 
    2327             :   // delete ESD tracks in the array
    2328           0 :   fTracksESD->Delete();
    2329           0 :   return nTracks;
    2330             : }
    2331             : 
    2332             : //____________________________________________________________________
    2333             : Int_t AliTRDtrackerV1::Clusters2TracksStack(AliTRDtrackingChamber **stack, TClonesArray * const esdTrackList)
    2334             : {
    2335             :   //
    2336             :   // Make tracks in one TRD stack.
    2337             :   //
    2338             :   // Parameters :
    2339             :   //   layer  : Array of stack propagation layers containing clusters
    2340             :   //   esdTrackList  : Array of ESD tracks found by the stand alone tracker. 
    2341             :   //                   On exit the tracks found in this stack are appended.
    2342             :   //
    2343             :   // Output :
    2344             :   //   Number of tracks found in this stack.
    2345             :   // 
    2346             :   // Detailed description
    2347             :   //
    2348             :   // 1. Find the 3 most useful seeding chambers. See BuildSeedingConfigs() for details.
    2349             :   // 2. Steer AliTRDtrackerV1::MakeSeeds() for 3 seeding layer configurations. 
    2350             :   //    See AliTRDtrackerV1::MakeSeeds() for more details.
    2351             :   // 3. Arrange track candidates in decreasing order of their quality
    2352             :   // 4. Classify tracks in 5 categories according to:
    2353             :   //    a) number of layers crossed
    2354             :   //    b) track quality 
    2355             :   // 5. Sign clusters by tracks in decreasing order of track quality
    2356             :   // 6. Build AliTRDtrack out of seeding tracklets
    2357             :   // 7. Cook MC label
    2358             :   // 8. Build ESD track and register it to the output list
    2359             :   //
    2360             : 
    2361             :   AliTRDtrackingChamber *chamber = NULL;
    2362             :   AliTRDtrackingChamber **ci = NULL;
    2363           0 :   AliTRDseedV1 sseed[kMaxTracksStack*6]; // to be initialized
    2364           0 :   Int_t pars[4]; // MakeSeeds parameters
    2365             : 
    2366             :   //Double_t alpha = AliTRDgeometry::GetAlpha();
    2367             :   //Double_t shift = .5 * alpha;
    2368           0 :   Int_t configs[kNConfigs];
    2369             :   
    2370             :   // Purge used clusters from the containers
    2371             :   ci = &stack[0];
    2372           0 :   for(Int_t ic = kNPlanes; ic--; ci++){
    2373           0 :     if(!(*ci)) continue;
    2374           0 :     (*ci)->Update();
    2375             :   }
    2376             : 
    2377             :   // Build initial seeding configurations
    2378           0 :   Double_t quality = BuildSeedingConfigs(stack, configs);
    2379           0 :   if(fkRecoParam->GetStreamLevel(AliTRDrecoParam::kTracker) > 10  || AliTRDReconstructor::GetStreamLevel()>10){
    2380           0 :     AliInfo(Form("Plane config %d %d %d Quality %f"
    2381             :     , configs[0], configs[1], configs[2], quality));
    2382             :   }
    2383             : 
    2384             :   
    2385             :   // Initialize contors
    2386             :   Int_t ntracks,      // number of TRD track candidates
    2387             :     ntracks1,     // number of registered TRD tracks/iter
    2388             :     ntracks2 = 0; // number of all registered TRD tracks in stack
    2389           0 :   fSieveSeeding = 0;
    2390             : 
    2391             :   // Get stack index
    2392             :   Int_t ic = 0; ci = &stack[0];
    2393           0 :   while(ic<kNPlanes && !(*ci)){ic++; ci++;}
    2394           0 :   if(!(*ci)) return ntracks2;
    2395           0 :   Int_t istack = fGeom->GetStack((*ci)->GetDetector());
    2396             : 
    2397           0 :   do{
    2398             :     // Loop over seeding configurations
    2399             :     ntracks = 0; ntracks1 = 0;
    2400           0 :     for (Int_t iconf = 0; iconf<fkRecoParam->GetNumberOfSeedConfigs(); iconf++) {
    2401           0 :       pars[0] = configs[iconf];
    2402           0 :       pars[1] = ntracks;
    2403           0 :       pars[2] = istack;
    2404           0 :       ntracks = MakeSeeds(stack, &sseed[6*ntracks], pars);
    2405             :       //AliInfo(Form("Number of Tracks after iteration step %d: %d\n", iconf, ntracks));
    2406           0 :       if(ntracks == kMaxTracksStack) break;
    2407             :     }
    2408           0 :     AliDebug(2, Form("Candidate TRD tracks %d in iteration %d.", ntracks, fSieveSeeding));
    2409           0 :     if(!ntracks) break;
    2410             :     
    2411             :     // Sort the seeds according to their quality
    2412           0 :     Int_t sort[kMaxTracksStack+1];
    2413           0 :     TMath::Sort(ntracks, fTrackQuality, sort, kTRUE);
    2414           0 :     if(AliLog::GetDebugLevel("TRD", "AliTRDtrackerV1") > 2){
    2415           0 :       AliDebug(3, "Track candidates classification:");
    2416           0 :       for (Int_t it(0); it < ntracks; it++) {
    2417           0 :         Int_t jt(sort[it]);
    2418           0 :         printf("   %2d idx[%d] Quality[%e]\n", it, jt, fTrackQuality[jt]);
    2419             :       }
    2420           0 :     }
    2421             :   
    2422             :     // Initialize number of tracks so far and logic switches
    2423           0 :     Int_t ntracks0 = esdTrackList->GetEntriesFast();
    2424           0 :     Bool_t signedTrack[kMaxTracksStack];
    2425           0 :     Bool_t fakeTrack[kMaxTracksStack];
    2426           0 :     for (Int_t i=0; i<ntracks; i++){
    2427           0 :       signedTrack[i] = kFALSE;
    2428           0 :       fakeTrack[i] = kFALSE;
    2429             :     }
    2430             :     //AliInfo("Selecting track candidates ...");
    2431             :     
    2432             :     // Sieve clusters in decreasing order of track quality
    2433             :     Int_t jSieve(0), rejectedCandidates(0);
    2434           0 :     do{
    2435             :       // Check track candidates
    2436             :       rejectedCandidates=0;
    2437           0 :       for (Int_t itrack = 0; itrack < ntracks; itrack++) {
    2438           0 :         Int_t trackIndex = sort[itrack];
    2439           0 :         if (signedTrack[trackIndex] || fakeTrack[trackIndex]) continue;
    2440             :         
    2441             :         // Calculate track parameters from tracklets seeds
    2442           0 :         Int_t ncl        = 0;
    2443           0 :         Int_t nused      = 0;
    2444           0 :         Int_t nlayers    = 0;
    2445           0 :         Int_t findable   = 0;
    2446           0 :         for (Int_t jLayer = 0; jLayer < kNPlanes; jLayer++) {
    2447           0 :           Int_t jseed = kNPlanes*trackIndex+jLayer;
    2448           0 :           sseed[jseed].UpdateUsed();
    2449           0 :           if(!sseed[jseed].IsOK()) continue;
    2450             :           // check if primary candidate
    2451           0 :           if (TMath::Abs(sseed[jseed].GetYref(0) / sseed[jseed].GetX0()) < 0.158) findable++;
    2452           0 :           ncl   += sseed[jseed].GetN();
    2453           0 :           nused += sseed[jseed].GetNUsed();
    2454           0 :           nlayers++;
    2455           0 :         }
    2456             : 
    2457             :         // Filter duplicated tracks
    2458           0 :         if (nused > 30){
    2459           0 :           AliDebug(4, Form("REJECTED : %d idx[%d] quality[%e] tracklets[%d] usedClusters[%d]", itrack, trackIndex, fTrackQuality[trackIndex], nlayers, nused));
    2460           0 :           fakeTrack[trackIndex] = kTRUE;
    2461           0 :           continue;
    2462             :         }
    2463           0 :         if (ncl>0 && Float_t(nused)/ncl >= .25){
    2464           0 :           AliDebug(4, Form("REJECTED : %d idx[%d] quality[%e] tracklets[%d] usedClusters[%d] used/ncl[%f]", itrack, trackIndex, fTrackQuality[trackIndex], nlayers, nused, Float_t(nused)/ncl));
    2465           0 :           fakeTrack[trackIndex] = kTRUE;
    2466           0 :           continue;
    2467             :         }
    2468             : 
    2469           0 :         AliDebug(4, Form("Candidate[%d] Quality[%e] Tracklets[%d] Findable[%d] Ncl[%d] Nused[%d]", trackIndex, fTrackQuality[trackIndex], nlayers, findable, ncl, nused));
    2470             : 
    2471             :         // Classify tracks
    2472             :         Bool_t skip = kFALSE;
    2473           0 :         switch(jSieve){
    2474             :           case 0: // select 6 tracklets primary tracks, good quality
    2475           0 :             if(nlayers > findable || nlayers < kNPlanes) {skip = kTRUE; break;}
    2476           0 :             if(TMath::Log(1.E-9+fTrackQuality[trackIndex]) < -5.){skip = kTRUE; break;}
    2477             :             break;
    2478             : 
    2479             :           case 1: // select shorter primary tracks, good quality
    2480             :             //if(findable<4){skip = kTRUE; break;}
    2481           0 :             if(nlayers < findable){skip = kTRUE; break;}
    2482           0 :             if(TMath::Log(1.E-9+fTrackQuality[trackIndex]) < -4.){skip = kTRUE; break;}
    2483             :             break;
    2484             : 
    2485             :           case 2: // select 6 tracklets secondary tracks
    2486           0 :             if(nlayers < kNPlanes) { skip = kTRUE; break;}
    2487           0 :             if (TMath::Log(1.E-9+fTrackQuality[trackIndex]) < -6.0){skip = kTRUE; break;}
    2488             :             break;
    2489             : 
    2490             :           case 3: // select shorter tracks, good quality
    2491           0 :             if (nlayers<4){skip = kTRUE; break;}
    2492           0 :             if (TMath::Log(1.E-9+fTrackQuality[trackIndex]) < -5.){skip = kTRUE; break;}
    2493             :             break;
    2494             : 
    2495             :           case 4: // select anything with at least 4 tracklets
    2496           0 :             if (nlayers<4){skip = kTRUE; break;}
    2497             :             //if (TMath::Log(1.E-9+fTrackQuality[trackIndex]) - nused/(nlayers-3.0) < -15.0){skip = kTRUE; break;}
    2498             :             break;
    2499             :         }
    2500           0 :         if(skip){
    2501           0 :           rejectedCandidates++;
    2502           0 :           AliDebug(4, Form("REJECTED : %d idx[%d] quality[%e] tracklets[%d] usedClusters[%d]", itrack, trackIndex, fTrackQuality[trackIndex], nlayers, nused));
    2503           0 :           continue;
    2504           0 :         } else AliDebug(4, Form("ACCEPTED : %d idx[%d] quality[%e] tracklets[%d] usedClusters[%d]", itrack, trackIndex, fTrackQuality[trackIndex], nlayers, nused));
    2505             : 
    2506           0 :         signedTrack[trackIndex] = kTRUE;
    2507             : 
    2508           0 :         AliTRDseedV1 *lseed =&sseed[trackIndex*kNPlanes];
    2509           0 :         AliTRDtrackV1 *track = MakeTrack(lseed);
    2510           0 :         if(!track){
    2511           0 :           AliDebug(1, "Track building failed.");
    2512           0 :           continue;
    2513             :         } else { 
    2514           0 :           if(AliLog::GetDebugLevel("TRD", "AliTRDtrackerV1") > 1){
    2515           0 :             Int_t ich = 0; while(!(chamber = stack[ich])) ich++;
    2516           0 :             AliDebug(2, Form("Track pt=%7.2fGeV/c SM[%2d] Done.", track->Pt(), fGeom->GetSector(chamber->GetDetector())));
    2517           0 :           }
    2518             :         }
    2519             : 
    2520           0 :         if(fkRecoParam->GetStreamLevel(AliTRDrecoParam::kTracker) > 1 && fkReconstructor->IsDebugStreaming()){
    2521             :           //AliInfo(Form("Track %d [%d] nlayers %d trackQuality = %e nused %d, yref = %3.3f", itrack, trackIndex, nlayers, fTrackQuality[trackIndex], nused, trackParams[1]));
    2522             : 
    2523           0 :           AliTRDseedV1 *dseed[6];
    2524           0 :           for(Int_t iseed = AliTRDgeometry::kNlayer; iseed--;) dseed[iseed] = new AliTRDseedV1(lseed[iseed]);
    2525             : 
    2526             :           //Int_t eventNrInFile = esd->GetEventNumberInFile();
    2527           0 :           Int_t eventNumber = AliTRDtrackerDebug::GetEventNumber();
    2528           0 :           Int_t trackNumber = AliTRDtrackerDebug::GetTrackNumber();
    2529           0 :           Int_t candidateNumber = AliTRDtrackerDebug::GetCandidateNumber();
    2530           0 :           TTreeSRedirector &cstreamer = *fkReconstructor->GetDebugStream(AliTRDrecoParam::kTracker);
    2531           0 :           cstreamer << "Clusters2TracksStack"
    2532           0 :               << "EventNumber="   << eventNumber
    2533           0 :               << "TrackNumber="   << trackNumber
    2534           0 :               << "CandidateNumber=" << candidateNumber
    2535           0 :               << "Iter="        << fSieveSeeding
    2536           0 :               << "Like="        << fTrackQuality[trackIndex]
    2537           0 :               << "S0.="       << dseed[0]
    2538           0 :               << "S1.="       << dseed[1]
    2539           0 :               << "S2.="       << dseed[2]
    2540           0 :               << "S3.="       << dseed[3]
    2541           0 :               << "S4.="       << dseed[4]
    2542           0 :               << "S5.="       << dseed[5]
    2543           0 :               << "Ncl="       << ncl
    2544           0 :               << "NLayers="   << nlayers
    2545           0 :               << "Findable="  << findable
    2546           0 :               << "NUsed="     << nused
    2547           0 :               << "\n";
    2548           0 :         }
    2549             : 
    2550             : 
    2551           0 :         AliESDtrack *esdTrack = new ((*esdTrackList)[ntracks0++]) AliESDtrack();
    2552           0 :         esdTrack->UpdateTrackParams(track, AliESDtrack::kTRDout);
    2553           0 :         esdTrack->SetLabel(track->GetLabel());
    2554           0 :         track->UpdateESDtrack(esdTrack);
    2555             :         // write ESD-friends if neccessary
    2556           0 :         if (fkRecoParam->GetStreamLevel(AliTRDrecoParam::kTracker) > 0 || AliTRDReconstructor::GetStreamLevel()>0 ){
    2557           0 :           AliTRDtrackV1 *calibTrack = new AliTRDtrackV1(*track);
    2558           0 :           calibTrack->SetOwner();
    2559           0 :           esdTrack->AddCalibObject(calibTrack);
    2560           0 :         }
    2561           0 :         ntracks1++;
    2562           0 :         AliTRDtrackerDebug::SetTrackNumber(AliTRDtrackerDebug::GetTrackNumber() + 1);
    2563           0 :       }
    2564             : 
    2565           0 :       jSieve++;
    2566           0 :     } while(jSieve<5 && rejectedCandidates); // end track candidates sieve
    2567           0 :     if(!ntracks1) break;
    2568             : 
    2569             :     // increment counters
    2570           0 :     ntracks2 += ntracks1;
    2571             : 
    2572           0 :     if(fkReconstructor->IsHLT()) break;
    2573           0 :     fSieveSeeding++;
    2574             : 
    2575             :     // Rebuild plane configurations and indices taking only unused clusters into account
    2576           0 :     quality = BuildSeedingConfigs(stack, configs);
    2577           0 :     if(quality < 1.E-7) break; //fkReconstructor->GetRecoParam() ->GetPlaneQualityThreshold()) break;
    2578             :     
    2579           0 :     for(Int_t ip = 0; ip < kNPlanes; ip++){ 
    2580           0 :       if(!(chamber = stack[ip])) continue;
    2581           0 :       chamber->Build(fGeom);//Indices(fSieveSeeding);
    2582             :     }
    2583             : 
    2584           0 :     if(fkRecoParam->GetStreamLevel(AliTRDrecoParam::kTracker) > 10 || AliTRDReconstructor::GetStreamLevel()>10){ 
    2585           0 :       AliInfo(Form("Sieve level %d Plane config %d %d %d Quality %f", fSieveSeeding, configs[0], configs[1], configs[2], quality));
    2586             :     }
    2587           0 :   } while(fSieveSeeding<10); // end stack clusters sieve
    2588             :   
    2589             : 
    2590             : 
    2591             :   //AliInfo(Form("Registered TRD tracks %d in stack %d.", ntracks2, pars[1]));
    2592             : 
    2593             :   return ntracks2;
    2594           0 : }
    2595             : 
    2596             : //___________________________________________________________________
    2597             : Double_t AliTRDtrackerV1::BuildSeedingConfigs(AliTRDtrackingChamber **stack, Int_t *configs)
    2598             : {
    2599             :   //
    2600             :   // Assign probabilities to chambers according to their
    2601             :   // capability of producing seeds.
    2602             :   // 
    2603             :   // Parameters :
    2604             :   //
    2605             :   //   layers : Array of stack propagation layers for all 6 chambers in one stack
    2606             :   //   configs : On exit array of configuration indexes (see GetSeedingConfig()
    2607             :   // for details) in the decreasing order of their seeding probabilities. 
    2608             :   //
    2609             :   // Output :
    2610             :   //
    2611             :   //  Return top configuration quality 
    2612             :   //
    2613             :   // Detailed description:
    2614             :   //
    2615             :   // To each chamber seeding configuration (see GetSeedingConfig() for
    2616             :   // the list of all configurations) one defines 2 quality factors:
    2617             :   //  - an apriori topological quality (see GetSeedingConfig() for details) and
    2618             :   //  - a data quality based on the uniformity of the distribution of
    2619             :   //    clusters over the x range (time bins population). See CookChamberQA() for details.
    2620             :   // The overall chamber quality is given by the product of this 2 contributions.
    2621             :   // 
    2622             : 
    2623           0 :   Double_t chamberQ[kNPlanes];memset(chamberQ, 0, kNPlanes*sizeof(Double_t));
    2624             :   AliTRDtrackingChamber *chamber = NULL;
    2625           0 :   for(int iplane=0; iplane<kNPlanes; iplane++){
    2626           0 :     if(!(chamber = stack[iplane])) continue;
    2627           0 :     chamberQ[iplane] = (chamber = stack[iplane]) ?  chamber->GetQuality() : 0.;
    2628           0 :   }
    2629             : 
    2630           0 :   Double_t tconfig[kNConfigs];memset(tconfig, 0, kNConfigs*sizeof(Double_t));
    2631           0 :   Int_t planes[] = {0, 0, 0, 0};
    2632           0 :   for(int iconf=0; iconf<kNConfigs; iconf++){
    2633           0 :     GetSeedingConfig(iconf, planes);
    2634           0 :     tconfig[iconf] = fgTopologicQA[iconf];
    2635           0 :     for(int iplane=0; iplane<4; iplane++) tconfig[iconf] *= chamberQ[planes[iplane]]; 
    2636             :   }
    2637             :   
    2638           0 :   TMath::Sort((Int_t)kNConfigs, tconfig, configs, kTRUE);
    2639             :   //    AliInfo(Form("q[%d] = %f", configs[0], tconfig[configs[0]]));
    2640             :   //    AliInfo(Form("q[%d] = %f", configs[1], tconfig[configs[1]]));
    2641             :   //    AliInfo(Form("q[%d] = %f", configs[2], tconfig[configs[2]]));
    2642             :   
    2643           0 :   return tconfig[configs[0]];
    2644           0 : }
    2645             : 
    2646             : //____________________________________________________________________
    2647             : Int_t AliTRDtrackerV1::MakeSeeds(AliTRDtrackingChamber **stack, AliTRDseedV1 * const sseed, const Int_t * const ipar)
    2648             : {
    2649             : //
    2650             : // Seed tracklets and build candidate TRD tracks. The procedure is used during barrel tracking to account for tracks which are 
    2651             : // either missed by TPC prolongation or conversions inside the TRD volume. 
    2652             : // For stand alone tracking the procedure is used to estimate all tracks measured by TRD. 
    2653             : //
    2654             : // Parameters :
    2655             : //   layers : Array of stack propagation layers containing clusters
    2656             : //   sseed  : Array of empty tracklet seeds. On exit they are filled.
    2657             : //   ipar   : Control parameters:
    2658             : //       ipar[0] -> seeding chambers configuration
    2659             : //       ipar[1] -> stack index
    2660             : //       ipar[2] -> number of track candidates found so far
    2661             : //
    2662             : // Output :
    2663             : //   Number of tracks candidates found.
    2664             : // 
    2665             : // The following steps are performed:
    2666             : // 1. Build seeding layers by collapsing all time bins from each of the four seeding chambers along the 
    2667             : // radial coordinate. See AliTRDtrackingChamber::GetSeedingLayer() for details. The chambers selection for seeding
    2668             : // is described in AliTRDtrackerV1::Clusters2TracksStack().
    2669             : // 2. Using the seeding clusters from the seeding layer (step 1) build combinatorics using the following algorithm:
    2670             : // - for each seeding cluster in the lower seeding layer find
    2671             : // - all seeding clusters in the upper seeding layer inside a road defined by a given phi angle. The angle 
    2672             : //   is calculated on the minimum pt of tracks from vertex accesible to the stand alone tracker.
    2673             : // - for each pair of two extreme seeding clusters select middle upper cluster using roads defined externally by the 
    2674             : //   reco params
    2675             : // - select last seeding cluster as the nearest to the linear approximation of the track described by the first three
    2676             : //   seeding clusters.
    2677             : //   The implementation of road calculation and cluster selection can be found in the functions AliTRDchamberTimeBin::BuildCond()
    2678             : //   and AliTRDchamberTimeBin::GetClusters().   
    2679             : // 3. Helix fit of the seeding clusters set. (see AliTRDtrackerFitter::FitRieman(AliTRDcluster**)). No tilt correction is 
    2680             : //    performed at this level 
    2681             : // 4. Initialize seeding tracklets in the seeding chambers.
    2682             : // 5. *Filter 0* Chi2 cut on the Y and Z directions. The threshold is set externally by the reco params.
    2683             : // 6. Attach (true) clusters to seeding tracklets (see AliTRDseedV1::AttachClusters()) and fit tracklet (see 
    2684             : //    AliTRDseedV1::Fit()). The number of used clusters used by current seeds should not exceed ... (25).
    2685             : // 7. *Filter 1* Check if all 4 seeding tracklets are correctly constructed.
    2686             : // 8. Helix fit of the clusters from the seeding tracklets with tilt correction. Refit tracklets using the new 
    2687             : //    approximation of the track.
    2688             : // 9. *Filter 2* Calculate likelihood of the track. (See AliTRDtrackerV1::CookLikelihood()). The following quantities are
    2689             : //    checked against the Riemann fit:
    2690             : //      - position resolution in y
    2691             : //      - angular resolution in the bending plane
    2692             : //      - likelihood of the number of clusters attached to the tracklet
    2693             : // 10. Extrapolation of the helix fit to the other 2 chambers *non seeding* chambers:
    2694             : //      - Initialization of extrapolation tracklets with the fit parameters
    2695             : //      - Attach clusters to extrapolated tracklets
    2696             : //      - Helix fit of tracklets
    2697             : // 11. Improve seeding tracklets quality by reassigning clusters based on the last parameters of the track
    2698             : //      See AliTRDtrackerV1::ImproveSeedQuality() for details.
    2699             : // 12. Helix fit of all 6 seeding tracklets and chi2 calculation
    2700             : // 13. Hyperplane fit and track quality calculation. See AliTRDtrackerFitter::FitHyperplane() for details.
    2701             : // 14. Cooking labels for tracklets. Should be done only for MC
    2702             : // 15. Register seeds.
    2703             : //
    2704             : // Authors:
    2705             : //   Marian Ivanov <M.Ivanov@gsi.de>
    2706             : //   Alexandru Bercuci <A.Bercuci@gsi.de>
    2707             : //   Markus Fasel <M.Fasel@gsi.de>
    2708             : 
    2709             :   AliTRDtrackingChamber *chamber = NULL;
    2710           0 :   AliTRDcluster *c[kNSeedPlanes] = {NULL, NULL, NULL, NULL}; // initilize seeding clusters
    2711             :   AliTRDseedV1 *cseed = &sseed[0]; // initialize tracklets for first track
    2712           0 :   Int_t ncl, mcl; // working variable for looping over clusters
    2713           0 :   Int_t index[AliTRDchamberTimeBin::kMaxClustersLayer], jndex[AliTRDchamberTimeBin::kMaxClustersLayer];
    2714             :   // chi2 storage
    2715             :   // chi2[0] = tracklet chi2 on the Z direction
    2716             :   // chi2[1] = tracklet chi2 on the R direction
    2717           0 :   Double_t chi2[4];
    2718             : 
    2719             :   // this should be data member of AliTRDtrack TODO
    2720             : //  Double_t seedQuality[kMaxTracksStack];
    2721             :   
    2722             :   // unpack control parameters
    2723           0 :   Int_t config  = ipar[0];
    2724           0 :   Int_t ntracks = ipar[1];
    2725           0 :   Int_t istack  = ipar[2];
    2726           0 :   Int_t planes[kNSeedPlanes]; GetSeedingConfig(config, planes); 
    2727           0 :   Int_t planesExt[kNPlanes-kNSeedPlanes]; GetExtrapolationConfig(config, planesExt);
    2728             : 
    2729             : 
    2730             :   // Init chambers geometry
    2731           0 :   Double_t hL[kNPlanes];       // Tilting angle
    2732           0 :   Float_t padlength[kNPlanes]; // pad lenghts
    2733           0 :   Float_t padwidth[kNPlanes];  // pad widths
    2734             :   AliTRDpadPlane *pp = NULL;
    2735           0 :   for(int iplane=0; iplane<kNPlanes; iplane++){
    2736           0 :     pp                = fGeom->GetPadPlane(iplane, istack);
    2737           0 :     hL[iplane]        = TMath::Tan(TMath::DegToRad()*pp->GetTiltingAngle());
    2738           0 :     padlength[iplane] = pp->GetLengthIPad();
    2739           0 :     padwidth[iplane] = pp->GetWidthIPad();
    2740             :   }
    2741             :   
    2742             :   // Init anode wire position for chambers
    2743           0 :   Double_t x0[kNPlanes],       // anode wire position
    2744           0 :            driftLength = .5*AliTRDgeometry::AmThick() - AliTRDgeometry::DrThick(); // drift length
    2745             :   TGeoHMatrix *matrix = NULL;
    2746           0 :   Double_t loc[] = {AliTRDgeometry::AnodePos(), 0., 0.};
    2747           0 :   Double_t glb[] = {0., 0., 0.};
    2748             :   AliTRDtrackingChamber **cIter = &stack[0];
    2749           0 :   for(int iLayer=0; iLayer<kNPlanes; iLayer++,cIter++){
    2750           0 :     if(!(*cIter)) continue;
    2751           0 :     if(!(matrix = fGeom->GetClusterMatrix((*cIter)->GetDetector()))){ 
    2752           0 :       x0[iLayer] = fgkX0[iLayer];
    2753           0 :       continue;
    2754             :     }
    2755           0 :     matrix->LocalToMaster(loc, glb);
    2756           0 :     x0[iLayer] = glb[0];
    2757           0 :   }
    2758             : 
    2759           0 :   AliDebug(2, Form("Making seeds Stack[%d] Config[%d] Tracks[%d]...", istack, config, ntracks));
    2760             : 
    2761             :   // Build seeding layers
    2762           0 :   ResetSeedTB();
    2763             :   Int_t nlayers = 0;
    2764           0 :   for(int isl=0; isl<kNSeedPlanes; isl++){ 
    2765           0 :     if(!(chamber = stack[planes[isl]])) continue;
    2766           0 :     if(!chamber->GetSeedingLayer(fSeedTB[isl], fGeom, fkReconstructor)) continue;
    2767           0 :     nlayers++;
    2768           0 :   }
    2769           0 :   if(nlayers < kNSeedPlanes) return ntracks;
    2770             :   
    2771             :   
    2772             :   // Start finding seeds
    2773           0 :   Double_t cond0[4], cond1[4], cond2[4];
    2774             :   Int_t icl = 0;
    2775           0 :   while((c[3] = (*fSeedTB[3])[icl++])){
    2776           0 :     if(!c[3]) continue;
    2777           0 :     fSeedTB[0]->BuildCond(c[3], cond0, 0);
    2778           0 :     fSeedTB[0]->GetClusters(cond0, index, ncl);
    2779             :     //printf("Found c[3] candidates 0 %d\n", ncl);
    2780             :     Int_t jcl = 0;
    2781           0 :     while(jcl<ncl) {
    2782           0 :       c[0] = (*fSeedTB[0])[index[jcl++]];
    2783           0 :       if(!c[0]) continue;
    2784           0 :       Double_t dx    = c[3]->GetX() - c[0]->GetX();
    2785           0 :       Double_t dzdx = (c[3]->GetZ() - c[0]->GetZ())/dx;
    2786           0 :       Double_t dydx   = (c[3]->GetY() - c[0]->GetY())/dx;
    2787           0 :       fSeedTB[1]->BuildCond(c[0], cond1, 1, dzdx, dydx);
    2788           0 :       fSeedTB[1]->GetClusters(cond1, jndex, mcl);
    2789             :       //printf("Found c[0] candidates 1 %d\n", mcl);
    2790             : 
    2791             :       Int_t kcl = 0;
    2792           0 :       while(kcl<mcl) {
    2793           0 :         c[1] = (*fSeedTB[1])[jndex[kcl++]];
    2794           0 :         if(!c[1]) continue;
    2795           0 :         fSeedTB[2]->BuildCond(c[1], cond2, 2, dzdx, dydx);
    2796           0 :         c[2] = fSeedTB[2]->GetNearestCluster(cond2);
    2797             :         //printf("Found c[1] candidate 2 %p\n", c[2]);
    2798           0 :         if(!c[2]) continue;
    2799             : 
    2800           0 :         AliDebug(3, Form("Seeding clusters\n 0[%6.3f %6.3f %6.3f]\n 1[%6.3f %6.3f %6.3f]\n 2[%6.3f %6.3f %6.3f]\n 3[%6.3f %6.3f %6.3f].",
    2801             :           c[0]->GetX(), c[0]->GetY(), c[0]->GetZ(),
    2802             :           c[1]->GetX(), c[1]->GetY(), c[1]->GetZ(),
    2803             :           c[2]->GetX(), c[2]->GetY(), c[2]->GetZ(),
    2804             :           c[3]->GetX(), c[3]->GetY(), c[3]->GetZ()));
    2805             :               
    2806           0 :         for (Int_t il = 0; il < kNPlanes; il++) cseed[il].Reset();
    2807             :       
    2808           0 :         FitRieman(c, chi2);
    2809             :       
    2810             :         AliTRDseedV1 *tseed = &cseed[0];
    2811             :         cIter = &stack[0];
    2812           0 :         for(int iLayer=0; iLayer<kNPlanes; iLayer++, tseed++, cIter++){
    2813           0 :           Int_t det = (*cIter) ? (*cIter)->GetDetector() : -1;
    2814           0 :           tseed->SetDetector(det);
    2815           0 :           tseed->SetTilt(hL[iLayer]);
    2816           0 :           tseed->SetPadLength(padlength[iLayer]);
    2817           0 :           tseed->SetPadWidth(padwidth[iLayer]);
    2818           0 :           tseed->SetReconstructor(fkReconstructor);
    2819           0 :           tseed->SetX0(det<0 ? fR[iLayer]+driftLength : x0[iLayer]);
    2820           0 :           tseed->Init(GetRiemanFitter());
    2821           0 :           tseed->SetStandAlone(kTRUE);
    2822             :         }
    2823             :       
    2824           0 :         Bool_t isFake = kFALSE;
    2825           0 :         if((fkRecoParam->GetStreamLevel(AliTRDrecoParam::kTracker) >= 2 && fkReconstructor->IsDebugStreaming()) 
    2826           0 :            ||AliTRDReconstructor::GetStreamLevel()>=2 ){
    2827           0 :           if (c[0]->GetLabel(0) != c[3]->GetLabel(0)) isFake = kTRUE;
    2828           0 :           if (c[1]->GetLabel(0) != c[3]->GetLabel(0)) isFake = kTRUE;
    2829           0 :           if (c[2]->GetLabel(0) != c[3]->GetLabel(0)) isFake = kTRUE;
    2830             :       
    2831           0 :           Double_t xpos[4];
    2832           0 :           for(Int_t l = 0; l < kNSeedPlanes; l++) xpos[l] = fSeedTB[l]->GetX();
    2833           0 :           Float_t yref[4];
    2834           0 :           for(int il=0; il<4; il++) yref[il] = cseed[planes[il]].GetYref(0);
    2835           0 :           Int_t ll = c[3]->GetLabel(0);
    2836           0 :           Int_t eventNumber = AliTRDtrackerDebug::GetEventNumber();
    2837           0 :           Int_t candidateNumber = AliTRDtrackerDebug::GetCandidateNumber();
    2838           0 :           AliRieman *rim = GetRiemanFitter();
    2839           0 :           TTreeSRedirector &cs0 = *fkReconstructor->GetDebugStream(AliTRDrecoParam::kTracker);
    2840           0 :           cs0 << "MakeSeeds0"
    2841           0 :               <<"EventNumber="          << eventNumber
    2842           0 :               <<"CandidateNumber="      << candidateNumber
    2843           0 :               <<"isFake="                               << isFake
    2844           0 :               <<"config="                               << config
    2845           0 :               <<"label="                                << ll
    2846           0 :               <<"chi2z="                                << chi2[0]
    2847           0 :               <<"chi2y="                                << chi2[1]
    2848           0 :               <<"Y2exp="                                << cond2[0]       
    2849           0 :               <<"Z2exp="                                << cond2[1]
    2850           0 :               <<"X0="                                   << xpos[0] //layer[sLayer]->GetX()
    2851           0 :               <<"X1="                                   << xpos[1] //layer[sLayer + 1]->GetX()
    2852           0 :               <<"X2="                                   << xpos[2] //layer[sLayer + 2]->GetX()
    2853           0 :               <<"X3="                                   << xpos[3] //layer[sLayer + 3]->GetX()
    2854           0 :               <<"yref0="                                << yref[0]
    2855           0 :               <<"yref1="                                << yref[1]
    2856           0 :               <<"yref2="                                << yref[2]
    2857           0 :               <<"yref3="                                << yref[3]
    2858           0 :               <<"c0.="                          << c[0]
    2859           0 :               <<"c1.="                          << c[1]
    2860           0 :               <<"c2.="                          << c[2]
    2861           0 :               <<"c3.="                          << c[3]
    2862           0 :               <<"Seed0.="                               << &cseed[planes[0]]
    2863           0 :               <<"Seed1.="                               << &cseed[planes[1]]
    2864           0 :               <<"Seed2.="                               << &cseed[planes[2]]
    2865           0 :               <<"Seed3.="                               << &cseed[planes[3]]
    2866           0 :               <<"RiemanFitter.="                << rim
    2867           0 :               <<"\n";
    2868           0 :         }
    2869           0 :         if(chi2[0] > fkRecoParam->GetChi2Z()/*7./(3. - sLayer)*//*iter*/){
    2870           0 :           AliDebug(3, Form("Filter on chi2Z [%f].", chi2[0]));
    2871           0 :           AliTRDtrackerDebug::SetCandidateNumber(AliTRDtrackerDebug::GetCandidateNumber() + 1);
    2872           0 :           continue;
    2873             :         }
    2874           0 :         if(chi2[1] > fkRecoParam->GetChi2Y()/*1./(3. - sLayer)*//*iter*/){
    2875           0 :           AliDebug(3, Form("Filter on chi2Y [%f].", chi2[1]));
    2876           0 :           AliTRDtrackerDebug::SetCandidateNumber(AliTRDtrackerDebug::GetCandidateNumber() + 1);
    2877           0 :           continue;
    2878             :         }
    2879             :         //AliInfo("Passed chi2 filter.");
    2880             :       
    2881             :         // try attaching clusters to tracklets
    2882           0 :         Int_t mlayers = 0; 
    2883             :         AliTRDcluster *cl = NULL;
    2884           0 :         for(int iLayer=0; iLayer<kNSeedPlanes; iLayer++){
    2885           0 :           Int_t jLayer = planes[iLayer];
    2886             :           Int_t nNotInChamber = 0;
    2887           0 :           if(!cseed[jLayer].AttachClusters(stack[jLayer], kTRUE)) continue;
    2888             :           if(/*fkReconstructor->IsHLT()*/kFALSE){ 
    2889             :             cseed[jLayer].UpdateUsed();
    2890             :             if(!cseed[jLayer].IsOK()) continue;
    2891             :           }else{
    2892           0 :             cseed[jLayer].Fit();
    2893           0 :             cseed[jLayer].UpdateUsed();
    2894           0 :             cseed[jLayer].ResetClusterIter();
    2895           0 :             while((cl = cseed[jLayer].NextCluster())){
    2896           0 :               if(!cl->IsInChamber()) nNotInChamber++;
    2897             :             }
    2898             :             //printf("clusters[%d], used[%d], not in chamber[%d]\n", cseed[jLayer].GetN(), cseed[jLayer].GetNUsed(), nNotInChamber);
    2899           0 :             if(cseed[jLayer].GetN() - (cseed[jLayer].GetNUsed() + nNotInChamber) < 5) continue; // checking for Cluster which are not in chamber is a much stronger restriction on real data
    2900             :           }
    2901           0 :           mlayers++;
    2902           0 :         }
    2903             : 
    2904           0 :         if(mlayers < kNSeedPlanes){ 
    2905           0 :           AliDebug(2, Form("Found only %d tracklets out of %d. Skip.", mlayers, kNSeedPlanes));
    2906           0 :           AliTRDtrackerDebug::SetCandidateNumber(AliTRDtrackerDebug::GetCandidateNumber() + 1);
    2907           0 :           continue;
    2908             :         }
    2909             : 
    2910             :         // temporary exit door for the HLT
    2911           0 :         if(fkReconstructor->IsHLT()){ 
    2912             :           // attach clusters to extrapolation chambers
    2913           0 :           for(int iLayer=0; iLayer<kNPlanes-kNSeedPlanes; iLayer++){
    2914           0 :             Int_t jLayer = planesExt[iLayer];
    2915           0 :             if(!(chamber = stack[jLayer])) continue;
    2916           0 :             if(!cseed[jLayer].AttachClusters(chamber, kTRUE)) continue;
    2917           0 :             cseed[jLayer].Fit();
    2918           0 :           }
    2919             :           //FitTiltedRiemanConstraint(&cseed[0], GetZ());
    2920           0 :           fTrackQuality[ntracks] = 1.; // dummy value
    2921           0 :           ntracks++;
    2922           0 :           if(ntracks == kMaxTracksStack) return ntracks;
    2923           0 :           cseed += 6; 
    2924           0 :           continue;
    2925             :         }
    2926             : 
    2927             : 
    2928             :         // Update Seeds and calculate Likelihood
    2929             :         // fit tracklets and cook likelihood
    2930           0 :         Double_t chi2Vals[4];
    2931           0 :         chi2Vals[0] = FitTiltedRieman(&cseed[0], kTRUE);
    2932           0 :         for(int iLayer=0; iLayer<kNSeedPlanes; iLayer++){
    2933           0 :           Int_t jLayer = planes[iLayer];
    2934           0 :           cseed[jLayer].Fit(1);
    2935             :         }
    2936           0 :         Double_t like = CookLikelihood(&cseed[0], planes); // to be checked
    2937             :       
    2938           0 :         if (TMath::Log(1.E-9 + like) < fkRecoParam->GetTrackLikelihood()){
    2939           0 :           AliDebug(3, Form("Filter on likelihood %f[%e].", TMath::Log(1.E-9 + like), like));
    2940           0 :           AliTRDtrackerDebug::SetCandidateNumber(AliTRDtrackerDebug::GetCandidateNumber() + 1);
    2941           0 :           continue;
    2942             :         }
    2943             :         //AliInfo(Form("Passed likelihood %f[%e].", TMath::Log(1.E-9 + like), like));
    2944             :       
    2945             :         // book preliminry results
    2946             :         //seedQuality[ntracks] = like;
    2947           0 :         fSeedLayer[ntracks]  = config;/*sLayer;*/
    2948             :       
    2949             :         // attach clusters to the extrapolation seeds
    2950             :         Int_t elayers(0);
    2951           0 :         for(int iLayer=0; iLayer<kNPlanes-kNSeedPlanes; iLayer++){
    2952           0 :           Int_t jLayer = planesExt[iLayer];
    2953           0 :           if(!(chamber = stack[jLayer])) continue;
    2954             :       
    2955             :           // fit extrapolated seed
    2956           0 :           if ((jLayer == 0) && !(cseed[1].IsOK())) continue;
    2957           0 :           if ((jLayer == 5) && !(cseed[4].IsOK())) continue;
    2958           0 :           AliTRDseedV1 pseed = cseed[jLayer];
    2959           0 :           if(!pseed.AttachClusters(chamber, kTRUE)) continue;
    2960           0 :           pseed.Fit(1);
    2961           0 :           cseed[jLayer] = pseed;
    2962           0 :           chi2Vals[0] = FitTiltedRieman(cseed,  kTRUE);
    2963           0 :           cseed[jLayer].Fit(1);
    2964           0 :           elayers++;
    2965           0 :         }
    2966             :       
    2967             :         // AliInfo("Extrapolation done.");
    2968             :         // Debug Stream containing all the 6 tracklets
    2969           0 :         if((fkRecoParam->GetStreamLevel(AliTRDrecoParam::kTracker) >= 2 && fkReconstructor->IsDebugStreaming())
    2970           0 :            ||AliTRDReconstructor::GetStreamLevel()>=2){
    2971           0 :           TTreeSRedirector &cstreamer = *fkReconstructor->GetDebugStream(AliTRDrecoParam::kTracker);
    2972           0 :           TLinearFitter *tiltedRieman = GetTiltedRiemanFitter();
    2973           0 :           Int_t eventNumber             = AliTRDtrackerDebug::GetEventNumber();
    2974           0 :           Int_t candidateNumber = AliTRDtrackerDebug::GetCandidateNumber();
    2975           0 :           cstreamer << "MakeSeeds1"
    2976           0 :               << "EventNumber="         << eventNumber
    2977           0 :               << "CandidateNumber="     << candidateNumber
    2978           0 :               << "S0.="                                 << &cseed[0]
    2979           0 :               << "S1.="                                 << &cseed[1]
    2980           0 :               << "S2.="                                 << &cseed[2]
    2981           0 :               << "S3.="                                 << &cseed[3]
    2982           0 :               << "S4.="                                 << &cseed[4]
    2983           0 :               << "S5.="                                 << &cseed[5]
    2984           0 :               << "FitterT.="                    << tiltedRieman
    2985           0 :               << "\n";
    2986           0 :         }
    2987             :               
    2988           0 :         if(fkRecoParam->HasImproveTracklets()){ 
    2989           0 :           if(!ImproveSeedQuality(stack, cseed, chi2Vals[0])){
    2990           0 :             AliTRDtrackerDebug::SetCandidateNumber(AliTRDtrackerDebug::GetCandidateNumber() + 1);
    2991           0 :             AliDebug(3, "ImproveSeedQuality() failed.");
    2992             :           }
    2993             :         }
    2994             :       
    2995             :         // do track fitting with vertex constraint
    2996           0 :         if(fkRecoParam->IsVertexConstrained()) chi2Vals[1] = FitTiltedRiemanConstraint(&cseed[0], GetZ());
    2997           0 :         else chi2Vals[1] = -1.;
    2998           0 :         chi2Vals[2] = GetChi2Z(&cseed[0]);
    2999           0 :         chi2Vals[3] = GetChi2Phi(&cseed[0]);
    3000             : 
    3001             :         // calculate track quality
    3002           0 :         fTrackQuality[ntracks] = CalculateTrackLikelihood(&chi2Vals[0]);
    3003             :                   
    3004           0 :         if((fkRecoParam->GetStreamLevel(AliTRDrecoParam::kTracker) >= 2 && fkReconstructor->IsDebugStreaming()) 
    3005           0 :            ||AliTRDReconstructor::GetStreamLevel()>=2){
    3006           0 :           TTreeSRedirector &cstreamer = *fkReconstructor->GetDebugStream(AliTRDrecoParam::kTracker);
    3007           0 :           Int_t eventNumber = AliTRDtrackerDebug::GetEventNumber();
    3008           0 :           Int_t candidateNumber = AliTRDtrackerDebug::GetCandidateNumber();
    3009           0 :           TLinearFitter *fitterTC = GetTiltedRiemanFitterConstraint();
    3010           0 :           TLinearFitter *fitterT = GetTiltedRiemanFitter();
    3011           0 :           Int_t ncls = 0; 
    3012           0 :           for(Int_t iseed = 0; iseed < kNPlanes; iseed++){
    3013           0 :                 ncls += cseed[iseed].IsOK() ? cseed[iseed].GetN2() : 0;
    3014             :           }
    3015           0 :           cstreamer << "MakeSeeds2"
    3016           0 :               << "EventNumber="                 << eventNumber
    3017           0 :               << "CandidateNumber="     << candidateNumber
    3018           0 :               << "Chi2TR="                      << chi2Vals[0]
    3019           0 :               << "Chi2TC="                      << chi2Vals[1]
    3020           0 :               << "Nlayers="                     << mlayers
    3021           0 :               << "NClusters="   << ncls
    3022           0 :               << "Like="                                << like
    3023           0 :               << "S0.="                         << &cseed[0]
    3024           0 :               << "S1.="                         << &cseed[1]
    3025           0 :               << "S2.="                         << &cseed[2]
    3026           0 :               << "S3.="                         << &cseed[3]
    3027           0 :               << "S4.="                         << &cseed[4]
    3028           0 :               << "S5.="                         << &cseed[5]
    3029           0 :               << "FitterT.="                    << fitterT
    3030           0 :               << "FitterTC.="                   << fitterTC
    3031           0 :               << "\n";
    3032           0 :         }
    3033           0 :         if(AliLog::GetDebugLevel("TRD", "AliTRDtrackerV1")){  
    3034             :           Double_t pt[]={0., 0.};
    3035           0 :           for(Int_t il(0); il<kNPlanes; il++){
    3036           0 :             if(!cseed[il].IsOK()) continue;
    3037           0 :             pt[0] = GetBz()*kB2C/cseed[il].GetC();
    3038           0 :             pt[1] = GetBz()*kB2C/cseed[il].GetC(1);
    3039           0 :             break;
    3040             :           }
    3041           0 :           AliDebug(2, Form("Candidate[%2d] pt[%7.3f %7.3f] Q[%e]\n"
    3042             :             "  [0] x[%6.2f] n[%2d] nu[%d] OK[%c]\n"
    3043             :             "  [1] x[%6.2f] n[%2d] nu[%d] OK[%c]\n"
    3044             :             "  [2] x[%6.2f] n[%2d] nu[%d] OK[%c]\n"
    3045             :             "  [3] x[%6.2f] n[%2d] nu[%d] OK[%c]\n"
    3046             :             "  [4] x[%6.2f] n[%2d] nu[%d] OK[%c]\n"
    3047             :             "  [5] x[%6.2f] n[%2d] nu[%d] OK[%c]"
    3048             :             , ntracks, pt[0], pt[1], fTrackQuality[ntracks]
    3049             :             ,cseed[0].GetX(), cseed[0].GetN(), cseed[0].GetNUsed(), cseed[0].IsOK()?'y':'n'
    3050             :             ,cseed[1].GetX(), cseed[1].GetN(), cseed[1].GetNUsed(), cseed[1].IsOK()?'y':'n'
    3051             :             ,cseed[2].GetX(), cseed[2].GetN(), cseed[2].GetNUsed(), cseed[2].IsOK()?'y':'n'
    3052             :             ,cseed[3].GetX(), cseed[3].GetN(), cseed[3].GetNUsed(), cseed[3].IsOK()?'y':'n'
    3053             :             ,cseed[4].GetX(), cseed[4].GetN(), cseed[4].GetNUsed(), cseed[4].IsOK()?'y':'n'
    3054             :             ,cseed[5].GetX(), cseed[5].GetN(), cseed[5].GetNUsed(), cseed[5].IsOK()?'y':'n'));
    3055           0 :         }
    3056           0 :         ntracks++;
    3057           0 :         AliTRDtrackerDebug::SetCandidateNumber(AliTRDtrackerDebug::GetCandidateNumber() + 1);
    3058           0 :         if(ntracks == kMaxTracksStack){
    3059           0 :           AliWarning(Form("Number of seeds reached maximum allowed (%d) in stack.", kMaxTracksStack));
    3060           0 :           return ntracks;
    3061             :         }
    3062           0 :         cseed += 6;
    3063           0 :       }
    3064           0 :     }
    3065           0 :   }
    3066             :   
    3067           0 :   return ntracks;
    3068           0 : }
    3069             : 
    3070             : //_____________________________________________________________________________
    3071             : AliTRDtrackV1* AliTRDtrackerV1::MakeTrack(AliTRDseedV1 * const tracklet)
    3072             : {
    3073             : //
    3074             : // Build a TRD track out of tracklet candidates
    3075             : //
    3076             : // Parameters :
    3077             : //   seeds  : array of tracklets
    3078             : //   params : array of track parameters as they are estimated by stand alone tracker. 7 elements.
    3079             : //     [0] - radial position of the track at reference point
    3080             : //     [1] - y position of the fit at [0]
    3081             : //     [2] - z position of the fit at [0]
    3082             : //     [3] - snp of the first tracklet
    3083             : //     [4] - tgl of the first tracklet
    3084             : //     [5] - curvature of the Riemann fit - 1/pt
    3085             : //     [6] - sector rotation angle
    3086             : //
    3087             : // Output :
    3088             : //   The TRD track.
    3089             : //
    3090             : // Initialize the TRD track based on the parameters of the fit and a parametric covariance matrix 
    3091             : // (diagonal with constant variance terms TODO - correct parameterization) 
    3092             : // 
    3093             : // In case of HLT just register the tracklets in the tracker and return values of the Riemann fit. For the
    3094             : // offline case perform a full Kalman filter on the already found tracklets (see AliTRDtrackerV1::FollowBackProlongation() 
    3095             : // for details). Do also MC label calculation and PID if propagation successfully.
    3096             : 
    3097           0 :   if(fkReconstructor->IsHLT()) FitTiltedRiemanConstraint(tracklet, 0);
    3098           0 :   Double_t alpha = AliTRDgeometry::GetAlpha();
    3099           0 :   Double_t shift = AliTRDgeometry::GetAlpha()/2.0;
    3100             : 
    3101             :   // find first good tracklet
    3102           0 :   Int_t idx(0); while(idx<kNPlanes && !tracklet[idx].IsOK()) idx++;
    3103           0 :   if(idx>2){ AliDebug(1, Form("Found suspect track start @ layer idx[%d]\n"
    3104             :     "  %c[0] x0[%f] n[%d] nu[%d] OK[%c]\n"
    3105             :     "  %c[1] x0[%f] n[%d] nu[%d] OK[%c]\n"
    3106             :     "  %c[2] x0[%f] n[%d] nu[%d] OK[%c]\n"
    3107             :     "  %c[3] x0[%f] n[%d] nu[%d] OK[%c]\n"
    3108             :     "  %c[4] x0[%f] n[%d] nu[%d] OK[%c]\n"
    3109             :     "  %c[5] x0[%f] n[%d] nu[%d] OK[%c]"
    3110             :     ,idx
    3111             :     ,idx==0?'*':' ', tracklet[0].GetX0(), tracklet[0].GetN(), tracklet[0].GetNUsed(), tracklet[0].IsOK()?'y':'n'
    3112             :     ,idx==1?'*':' ', tracklet[1].GetX0(), tracklet[1].GetN(), tracklet[1].GetNUsed(), tracklet[1].IsOK()?'y':'n'
    3113             :     ,idx==2?'*':' ', tracklet[2].GetX0(), tracklet[2].GetN(), tracklet[2].GetNUsed(), tracklet[2].IsOK()?'y':'n'
    3114             :     ,idx==3?'*':' ', tracklet[3].GetX0(), tracklet[3].GetN(), tracklet[3].GetNUsed(), tracklet[3].IsOK()?'y':'n'
    3115             :     ,idx==4?'*':' ', tracklet[4].GetX0(), tracklet[4].GetN(), tracklet[4].GetNUsed(), tracklet[4].IsOK()?'y':'n'
    3116             :     ,idx==5?'*':' ', tracklet[5].GetX0(), tracklet[5].GetN(), tracklet[5].GetNUsed(), tracklet[5].IsOK()?'y':'n'));
    3117           0 :     return NULL;
    3118             :   }
    3119             : 
    3120             :   Double_t dx(5.);
    3121           0 :   Double_t x(tracklet[idx].GetX0() - dx);
    3122             :   // Build track parameters
    3123           0 :   Double_t params[] = {
    3124           0 :     tracklet[idx].GetYref(0) - dx*tracklet[idx].GetYref(1) // y
    3125           0 :    ,tracklet[idx].GetZref(0) - dx*tracklet[idx].GetZref(1) // z
    3126           0 :    ,TMath::Sin(TMath::ATan(tracklet[idx].GetYref(1)))      // snp
    3127           0 :    ,tracklet[idx].GetZref(1) / TMath::Sqrt(1. + tracklet[idx].GetYref(1) * tracklet[idx].GetYref(1))   // tgl
    3128           0 :    ,tracklet[idx].GetC(fkReconstructor->IsHLT()?1:0)                                   // curvature -> 1/pt
    3129             :   };
    3130           0 :   Int_t sector(fGeom->GetSector(tracklet[idx].GetDetector()));
    3131             : 
    3132           0 :   Double_t c[15];
    3133           0 :   c[ 0] = 0.2; // s^2_y
    3134           0 :   c[ 1] = 0.0; c[ 2] = 2.0; // s^2_z
    3135           0 :   c[ 3] = 0.0; c[ 4] = 0.0; c[ 5] = 0.02; // s^2_snp
    3136           0 :   c[ 6] = 0.0; c[ 7] = 0.0; c[ 8] = 0.0;  c[ 9] = 0.1; // s^2_tgl
    3137           0 :   c[10] = 0.0; c[11] = 0.0; c[12] = 0.0;  c[13] = 0.0; c[14] = params[4]*params[4]*0.01; // s^2_1/pt
    3138             : 
    3139           0 :   AliTRDtrackV1 track(tracklet, params, c, x, sector*alpha+shift);
    3140             : 
    3141             :   AliTRDseedV1 *ptrTracklet = NULL;
    3142             : 
    3143             :   // skip Kalman filter for HLT
    3144             :   if(/*fkReconstructor->IsHLT()*/kFALSE){ 
    3145             :     for (Int_t jLayer = 0; jLayer < AliTRDgeometry::kNlayer; jLayer++) {
    3146             :       track.UnsetTracklet(jLayer);
    3147             :       ptrTracklet = &tracklet[jLayer];
    3148             :       if(!ptrTracklet->IsOK()) continue;
    3149             :       if(TMath::Abs(ptrTracklet->GetYref(1) - ptrTracklet->GetYfit(1)) >= .2) continue; // check this condition with Marian
    3150             :       ptrTracklet = SetTracklet(ptrTracklet);
    3151             :       ptrTracklet->UseClusters();
    3152             :       track.SetTracklet(ptrTracklet, fTracklets->GetEntriesFast()-1);
    3153             :     }
    3154             :     AliTRDtrackV1 *ptrTrack = SetTrack(&track);
    3155             :     ptrTrack->CookPID();
    3156             :     ptrTrack->CookLabel(.9);
    3157             :     ptrTrack->SetReconstructor(fkReconstructor);
    3158             :     return ptrTrack;
    3159             :   }
    3160             : 
    3161             :   // prevent the error message in AliTracker::MeanMaterialBudget: "start point out of geometry"
    3162           0 :   if(TMath::Abs(track.GetX()) + TMath::Abs(track.GetY()) + TMath::Abs(track.GetZ()) > 10000) return NULL;
    3163             : 
    3164           0 :   track.ResetCovariance(1);
    3165           0 :   Int_t nc = TMath::Abs(FollowBackProlongation(track));
    3166           0 :   if((fkRecoParam->GetStreamLevel(AliTRDrecoParam::kTracker) > 5 && fkReconstructor->IsDebugStreaming()) 
    3167           0 :      ||AliTRDReconstructor::GetStreamLevel()>5){
    3168           0 :     Int_t eventNumber           = AliTRDtrackerDebug::GetEventNumber();
    3169           0 :     Int_t candidateNumber = AliTRDtrackerDebug::GetCandidateNumber();
    3170           0 :     Double_t p[5]; // Track Params for the Debug Stream
    3171           0 :     track.GetExternalParameters(x, p);
    3172           0 :     TTreeSRedirector &cs = *fkReconstructor->GetDebugStream(AliTRDrecoParam::kTracker);
    3173           0 :     cs << "MakeTrack"
    3174           0 :     << "EventNumber="     << eventNumber
    3175           0 :     << "CandidateNumber=" << candidateNumber
    3176           0 :     << "nc="     << nc
    3177           0 :     << "X="      << x
    3178           0 :     << "Y="      << p[0]
    3179           0 :     << "Z="      << p[1]
    3180           0 :     << "snp="    << p[2]
    3181           0 :     << "tnd="    << p[3]
    3182           0 :     << "crv="    << p[4]
    3183           0 :     << "Yin="    << params[0]
    3184           0 :     << "Zin="    << params[1]
    3185           0 :     << "snpin="  << params[2]
    3186           0 :     << "tndin="  << params[3]
    3187           0 :     << "crvin="  << params[4]
    3188           0 :     << "track.=" << &track
    3189           0 :     << "\n";
    3190           0 :   }
    3191           0 :   if (nc < 30){ 
    3192           0 :     UnsetTrackletsTrack(&track);
    3193           0 :     return NULL;
    3194             :   }
    3195           0 :   AliTRDtrackV1 *ptrTrack = SetTrack(&track);
    3196           0 :   ptrTrack->SetReconstructor(fkReconstructor);
    3197           0 :   ptrTrack->CookLabel(.9);
    3198           0 :   for(Int_t il(kNPlanes); il--;){
    3199           0 :     if(!(ptrTracklet = ptrTrack->GetTracklet(il))) continue;
    3200           0 :     ptrTracklet->UseClusters();
    3201             :   }
    3202             : 
    3203             :   // computes PID for track
    3204           0 :   ptrTrack->CookPID();
    3205             :   // update calibration references using this track
    3206           0 :   AliTRDCalibraFillHisto *calibra = AliTRDCalibraFillHisto::Instance();
    3207           0 :   if(!calibra){
    3208           0 :     AliInfo("Could not get Calibra instance.");
    3209           0 :   } else if(calibra->GetHisto2d()){
    3210           0 :     calibra->UpdateHistogramsV1(ptrTrack);
    3211             :   }
    3212             :   return ptrTrack;
    3213           0 : }
    3214             : 
    3215             : 
    3216             : //____________________________________________________________________
    3217             : Bool_t AliTRDtrackerV1::ImproveSeedQuality(AliTRDtrackingChamber **stack, AliTRDseedV1 *cseed, Double_t &chi2)
    3218             : {
    3219             :   //
    3220             :   // Sort tracklets according to "quality" and try to "improve" the first 4 worst
    3221             :   //
    3222             :   // Parameters :
    3223             :   //  layers : Array of propagation layers for a stack/supermodule
    3224             :   //  cseed  : Array of 6 seeding tracklets which has to be improved
    3225             :   // 
    3226             :   // Output : 
    3227             :   //   cssed : Improved seeds
    3228             :   // 
    3229             :   // Detailed description
    3230             :   //
    3231             :   // Iterative procedure in which new clusters are searched for each
    3232             :   // tracklet seed such that the seed quality (see AliTRDseed::GetQuality())
    3233             :   // can be maximized. If some optimization is found the old seeds are replaced.
    3234             :   //
    3235             :   // debug level: 7
    3236             :   //
    3237             :   
    3238             :   // make a local working copy
    3239             :   AliTRDtrackingChamber *chamber = NULL;
    3240           0 :   AliTRDseedV1 bseed[AliTRDgeometry::kNlayer];
    3241             : 
    3242           0 :   Float_t quality(1.e3), 
    3243           0 :           lQuality[AliTRDgeometry::kNlayer] = {1.e3, 1.e3, 1.e3, 1.e3, 1.e3, 1.e3};
    3244             :   Int_t rLayers(0);
    3245           0 :   for(Int_t jLayer=AliTRDgeometry::kNlayer; jLayer--;){ 
    3246           0 :     bseed[jLayer] = cseed[jLayer];
    3247           0 :     if(!bseed[jLayer].IsOK()) continue;
    3248           0 :     rLayers++;
    3249           0 :     lQuality[jLayer] = bseed[jLayer].GetQuality(kTRUE);
    3250           0 :     quality    += lQuality[jLayer];
    3251             :   }
    3252           0 :   if (rLayers > 0) {
    3253           0 :     quality /= rLayers;
    3254           0 :   }
    3255           0 :   AliDebug(2, Form("Start N[%d] Q[%f] chi2[%f]", rLayers, quality, chi2));
    3256             : 
    3257           0 :   for (Int_t iter = 0; iter < 4; iter++) {
    3258             :     // Try better cluster set
    3259             :     Int_t nLayers(0); Float_t qualitynew(0.);
    3260           0 :     Int_t  indexes[4*AliTRDgeometry::kNlayer];
    3261           0 :     TMath::Sort(Int_t(AliTRDgeometry::kNlayer), lQuality, indexes, kFALSE);
    3262           0 :     for(Int_t jLayer=AliTRDgeometry::kNlayer; jLayer--;) {
    3263           0 :       Int_t bLayer = indexes[jLayer];
    3264           0 :       bseed[bLayer].Reset("c");
    3265           0 :       if(!(chamber = stack[bLayer])) continue;
    3266           0 :       if(!bseed[bLayer].AttachClusters(chamber, kTRUE)) continue;
    3267           0 :       bseed[bLayer].Fit(1);
    3268           0 :       if(!bseed[bLayer].IsOK()) continue;
    3269           0 :       nLayers++;
    3270           0 :       lQuality[jLayer] = bseed[jLayer].GetQuality(kTRUE);
    3271           0 :       qualitynew    += lQuality[jLayer];
    3272           0 :     }
    3273           0 :     if(rLayers > nLayers){
    3274           0 :       AliDebug(1, Form("Lost %d tracklets while improving.", rLayers-nLayers));
    3275           0 :       return iter>0?kTRUE:kFALSE;
    3276             :     } else rLayers=nLayers;
    3277           0 :     qualitynew /= rLayers;
    3278             : 
    3279           0 :     if(qualitynew > quality){ 
    3280           0 :       AliDebug(4, Form("Quality[%f] worsen in iter[%d] to ref[%f].", qualitynew, iter, quality));
    3281           0 :       return iter>0?kTRUE:kFALSE;
    3282             :     } else quality = qualitynew;
    3283             : 
    3284             :     // try improve track parameters
    3285           0 :     Float_t chi2new = FitTiltedRieman(bseed, kTRUE);
    3286           0 :     if(chi2new > chi2){ 
    3287           0 :       AliDebug(4, Form("Chi2[%f] worsen in iter[%d] to ref[%f].", chi2new, iter, chi2));
    3288           0 :       return iter>0?kTRUE:kFALSE;
    3289           0 :     } else chi2 = chi2new;
    3290             : 
    3291             :     // store better tracklets
    3292           0 :     for(Int_t jLayer=AliTRDgeometry::kNlayer; jLayer--;) cseed[jLayer]=bseed[jLayer];
    3293           0 :     AliDebug(2, Form("Iter[%d] Q[%f] chi2[%f]", iter, quality, chi2));
    3294             : 
    3295             : 
    3296           0 :     if((fkRecoParam->GetStreamLevel(AliTRDrecoParam::kTracker) >= 7 && fkReconstructor->IsDebugStreaming())
    3297           0 :        ||AliTRDReconstructor::GetStreamLevel()>=7){
    3298           0 :       Int_t eventNumber                 = AliTRDtrackerDebug::GetEventNumber();
    3299           0 :       Int_t candidateNumber = AliTRDtrackerDebug::GetCandidateNumber();
    3300           0 :       TLinearFitter *tiltedRieman = GetTiltedRiemanFitter();
    3301           0 :       TTreeSRedirector &cstreamer = *fkReconstructor->GetDebugStream(AliTRDrecoParam::kTracker);
    3302           0 :       cstreamer << "ImproveSeedQuality"
    3303           0 :         << "EventNumber="               << eventNumber
    3304           0 :         << "CandidateNumber="   << candidateNumber
    3305           0 :         << "Iteration="                         << iter
    3306           0 :         << "S0.="                                                       << &cseed[0]
    3307           0 :         << "S1.="                                                       << &cseed[1]
    3308           0 :         << "S2.="                                                       << &cseed[2]
    3309           0 :         << "S3.="                                                       << &cseed[3]
    3310           0 :         << "S4.="                                                       << &cseed[4]
    3311           0 :         << "S5.="                                                       << &cseed[5]
    3312           0 :         << "FitterT.="                          << tiltedRieman
    3313           0 :         << "\n";
    3314           0 :     }
    3315           0 :   } // Loop: iter
    3316             : 
    3317             :   // we are sure that at least 4 tracklets are OK !
    3318           0 :   return kTRUE;
    3319           0 : }
    3320             : 
    3321             : //_________________________________________________________________________
    3322             : Double_t AliTRDtrackerV1::CalculateTrackLikelihood(Double_t *chi2){
    3323             :   //
    3324             :   // Calculates the Track Likelihood value. This parameter serves as main quality criterion for 
    3325             :   // the track selection
    3326             :   // The likelihood value containes:
    3327             :   //    - The chi2 values from the both fitters and the chi2 values in z-direction from a linear fit
    3328             :   //    - The Sum of the Parameter  |slope_ref - slope_fit|/Sigma of the tracklets
    3329             :   // For all Parameters an exponential dependency is used
    3330             :   //
    3331             :   // Parameters: - Array of tracklets (AliTRDseedV1) related to the track candidate
    3332             :   //             - Array of chi2 values: 
    3333             :   //                 * Non-Constrained Tilted Riemann fit
    3334             :   //                 * Vertex-Constrained Tilted Riemann fit
    3335             :   //                 * z-Direction from Linear fit
    3336             :   // Output:     - The calculated track likelihood
    3337             :   //
    3338             :   // debug level 2
    3339             :   //
    3340             :   
    3341             :   // Non-constrained Tilted Riemann
    3342           0 :   Double_t likeChi2TR = TMath::Exp(-chi2[0] * 0.0078);
    3343             :   // Constrained Tilted Riemann
    3344           0 :   Double_t likeChi2TC(1.);
    3345           0 :   if(chi2[1]>0.){
    3346           0 :     likeChi2TC = TMath::Exp(-chi2[1] * 0.677);
    3347           0 :     Double_t r = likeChi2TC/likeChi2TR;
    3348           0 :     if(r>1.e2){;}   // -> a primary track use TC
    3349           0 :     else if(r<1.e2) // -> a secondary track use TR
    3350           0 :       likeChi2TC =1.;
    3351             :     else{;}         // -> test not conclusive
    3352           0 :   }
    3353             :   // Chi2 only on Z direction
    3354           0 :   Double_t likeChi2Z  = TMath::Exp(-chi2[2] * 0.14);
    3355             :   // Chi2 angular resolution
    3356           0 :   Double_t likeChi2Phi= TMath::Exp(-chi2[3] * 3.23);
    3357             : 
    3358           0 :   Double_t trackLikelihood     = likeChi2Z * likeChi2TR * likeChi2TC * likeChi2Phi;
    3359             : 
    3360           0 :   AliDebug(2, Form("Likelihood [%e]\n"
    3361             :     "  Rieman : chi2[%f] likelihood[%6.2e]\n"
    3362             :     "  Vertex : chi2[%f] likelihood[%6.2e]\n"
    3363             :     "  Z      : chi2[%f] likelihood[%6.2e]\n"
    3364             :     "  Phi    : chi2[%f] likelihood[%6.2e]"
    3365             :     , trackLikelihood
    3366             :     , chi2[0], likeChi2TR
    3367             :     , chi2[1], likeChi2TC
    3368             :     , chi2[2], likeChi2Z
    3369             :     , chi2[3], likeChi2Phi
    3370             :   ));
    3371             : 
    3372           0 :   if((fkRecoParam->GetStreamLevel(AliTRDrecoParam::kTracker) >= 2 && fkReconstructor->IsDebugStreaming())
    3373           0 :      ||AliTRDReconstructor::GetStreamLevel()>=2){
    3374           0 :     Int_t eventNumber = AliTRDtrackerDebug::GetEventNumber();
    3375           0 :     Int_t candidateNumber = AliTRDtrackerDebug::GetCandidateNumber();
    3376           0 :     TTreeSRedirector &cstreamer = *fkReconstructor->GetDebugStream(AliTRDrecoParam::kTracker);
    3377           0 :     cstreamer << "CalculateTrackLikelihood0"
    3378           0 :         << "EventNumber="                       << eventNumber
    3379           0 :         << "CandidateNumber="   << candidateNumber
    3380           0 :         << "LikeChi2Z="                         << likeChi2Z
    3381           0 :         << "LikeChi2TR="                        << likeChi2TR
    3382           0 :         << "LikeChi2TC="                        << likeChi2TC
    3383           0 :         << "LikeChi2Phi="               << likeChi2Phi
    3384           0 :         << "TrackLikelihood=" << trackLikelihood
    3385           0 :         << "\n";
    3386           0 :   }
    3387             :   
    3388           0 :   return trackLikelihood;
    3389           0 : }
    3390             : 
    3391             : //____________________________________________________________________
    3392             : Double_t AliTRDtrackerV1::CookLikelihood(AliTRDseedV1 *cseed, Int_t planes[4])
    3393             : {
    3394             :   //
    3395             :   // Calculate the probability of this track candidate.
    3396             :   //
    3397             :   // Parameters :
    3398             :   //   cseeds : array of candidate tracklets
    3399             :   //   planes : array of seeding planes (see seeding configuration)
    3400             :   //   chi2   : chi2 values (on the Z and Y direction) from the rieman fit of the track.
    3401             :   //
    3402             :   // Output :
    3403             :   //   likelihood value
    3404             :   // 
    3405             :   // Detailed description
    3406             :   //
    3407             :   // The track quality is estimated based on the following 4 criteria:
    3408             :   //  1. precision of the rieman fit on the Y direction (likea)
    3409             :   //  2. chi2 on the Y direction (likechi2y)
    3410             :   //  3. chi2 on the Z direction (likechi2z)
    3411             :   //  4. number of attached clusters compared to a reference value 
    3412             :   //     (see AliTRDrecoParam::fkFindable) (likeN)
    3413             :   //
    3414             :   // The distributions for each type of probabilities are given below as of
    3415             :   // (date). They have to be checked to assure consistency of estimation.
    3416             :   //
    3417             : 
    3418             :   // ratio of the total number of clusters/track which are expected to be found by the tracker.
    3419           0 :         Double_t chi2y = GetChi2Y(&cseed[0]);
    3420           0 :   Double_t chi2z = GetChi2Z(&cseed[0]);
    3421             : 
    3422           0 :   Float_t nclusters = 0.;
    3423           0 :   Double_t sumda = 0.;
    3424           0 :   for(UChar_t ilayer = 0; ilayer < 4; ilayer++){
    3425           0 :     Int_t jlayer = planes[ilayer];
    3426           0 :     nclusters += cseed[jlayer].GetN2();
    3427           0 :     sumda += TMath::Abs(cseed[jlayer].GetYfit(1) - cseed[jlayer].GetYref(1));
    3428             :   }
    3429           0 :   nclusters *= .25;
    3430             : 
    3431           0 :   Double_t likea     = TMath::Exp(-sumda * fkRecoParam->GetPhiSlope());
    3432           0 :   Double_t likechi2y  = 0.0000000001;
    3433           0 :   if (fkReconstructor->IsCosmic() || chi2y < fkRecoParam->GetChi2YCut()) likechi2y += TMath::Exp(-TMath::Sqrt(chi2y) * fkRecoParam->GetChi2YSlope());
    3434           0 :   Double_t likechi2z = TMath::Exp(-chi2z * fkRecoParam->GetChi2ZSlope());
    3435           0 :   Double_t likeN     = TMath::Exp(-(fkRecoParam->GetNMeanClusters() - nclusters) / fkRecoParam->GetNSigmaClusters());
    3436           0 :   Double_t like      = likea * likechi2y * likechi2z * likeN;
    3437             : 
    3438           0 :   if((fkRecoParam->GetStreamLevel(AliTRDrecoParam::kTracker) >= 2 && fkReconstructor->IsDebugStreaming())
    3439           0 :      ||AliTRDReconstructor::GetStreamLevel()>=2){
    3440           0 :     Int_t eventNumber = AliTRDtrackerDebug::GetEventNumber();
    3441           0 :     Int_t candidateNumber = AliTRDtrackerDebug::GetCandidateNumber();
    3442           0 :     Int_t nTracklets = 0; Float_t meanNcls = 0;
    3443           0 :     for(Int_t iseed=0; iseed < kNPlanes; iseed++){
    3444           0 :         if(!cseed[iseed].IsOK()) continue;
    3445           0 :         nTracklets++;
    3446           0 :         meanNcls += cseed[iseed].GetN2();
    3447           0 :     }
    3448           0 :     if(nTracklets) meanNcls /= nTracklets;
    3449             :     // The Debug Stream contains the seed 
    3450           0 :     TTreeSRedirector &cstreamer = *fkReconstructor->GetDebugStream(AliTRDrecoParam::kTracker);
    3451           0 :     cstreamer << "CookLikelihood"
    3452           0 :         << "EventNumber="                       << eventNumber
    3453           0 :         << "CandidateNumber=" << candidateNumber
    3454           0 :         << "tracklet0.="                        << &cseed[0]
    3455           0 :         << "tracklet1.="                        << &cseed[1]
    3456           0 :         << "tracklet2.="                        << &cseed[2]
    3457           0 :         << "tracklet3.="                        << &cseed[3]
    3458           0 :         << "tracklet4.="                        << &cseed[4]
    3459           0 :         << "tracklet5.="                        << &cseed[5]
    3460           0 :         << "sumda="                                             << sumda
    3461           0 :         << "chi2y="                                             << chi2y
    3462           0 :         << "chi2z="                                             << chi2z
    3463           0 :         << "likea="                                             << likea
    3464           0 :         << "likechi2y="                         << likechi2y
    3465           0 :         << "likechi2z="                         << likechi2z
    3466           0 :         << "nclusters="                         << nclusters
    3467           0 :         << "likeN="                                             << likeN
    3468           0 :         << "like="                                              << like
    3469           0 :         << "meanncls="        << meanNcls
    3470           0 :         << "\n";
    3471           0 :   }
    3472             : 
    3473           0 :   return like;
    3474           0 : }
    3475             : 
    3476             : //____________________________________________________________________
    3477             : void AliTRDtrackerV1::GetSeedingConfig(Int_t iconfig, Int_t planes[4])
    3478             : {
    3479             :   //
    3480             :   // Map seeding configurations to detector planes.
    3481             :   //
    3482             :   // Parameters :
    3483             :   //   iconfig : configuration index
    3484             :   //   planes  : member planes of this configuration. On input empty.
    3485             :   //
    3486             :   // Output :
    3487             :   //   planes : contains the planes which are defining the configuration
    3488             :   // 
    3489             :   // Detailed description
    3490             :   //
    3491             :   // Here is the list of seeding planes configurations together with
    3492             :   // their topological classification:
    3493             :   //
    3494             :   //  0 - 5432 TQ 0
    3495             :   //  1 - 4321 TQ 0
    3496             :   //  2 - 3210 TQ 0
    3497             :   //  3 - 5321 TQ 1
    3498             :   //  4 - 4210 TQ 1
    3499             :   //  5 - 5431 TQ 1
    3500             :   //  6 - 4320 TQ 1
    3501             :   //  7 - 5430 TQ 2
    3502             :   //  8 - 5210 TQ 2
    3503             :   //  9 - 5421 TQ 3
    3504             :   // 10 - 4310 TQ 3
    3505             :   // 11 - 5410 TQ 4
    3506             :   // 12 - 5420 TQ 5
    3507             :   // 13 - 5320 TQ 5
    3508             :   // 14 - 5310 TQ 5
    3509             :   //
    3510             :   // The topologic quality is modeled as follows:
    3511             :   // 1. The general model is define by the equation:
    3512             :   //  p(conf) = exp(-conf/2)
    3513             :   // 2. According to the topologic classification, configurations from the same
    3514             :   //    class are assigned the agerage value over the model values.
    3515             :   // 3. Quality values are normalized.
    3516             :   // 
    3517             :   // The topologic quality distribution as function of configuration is given below:
    3518             :   //Begin_Html
    3519             :   // <img src="gif/topologicQA.gif">
    3520             :   //End_Html
    3521             :   //
    3522             : 
    3523           0 :   switch(iconfig){
    3524             :   case 0: // 5432 TQ 0
    3525           0 :     planes[0] = 2;
    3526           0 :     planes[1] = 3;
    3527           0 :     planes[2] = 4;
    3528           0 :     planes[3] = 5;
    3529           0 :     break;
    3530             :   case 1: // 4321 TQ 0
    3531           0 :     planes[0] = 1;
    3532           0 :     planes[1] = 2;
    3533           0 :     planes[2] = 3;
    3534           0 :     planes[3] = 4;
    3535           0 :     break;
    3536             :   case 2: // 3210 TQ 0
    3537           0 :     planes[0] = 0;
    3538           0 :     planes[1] = 1;
    3539           0 :     planes[2] = 2;
    3540           0 :     planes[3] = 3;
    3541           0 :     break;
    3542             :   case 3: // 5321 TQ 1
    3543           0 :     planes[0] = 1;
    3544           0 :     planes[1] = 2;
    3545           0 :     planes[2] = 3;
    3546           0 :     planes[3] = 5;
    3547           0 :     break;
    3548             :   case 4: // 4210 TQ 1
    3549           0 :     planes[0] = 0;
    3550           0 :     planes[1] = 1;
    3551           0 :     planes[2] = 2;
    3552           0 :     planes[3] = 4;
    3553           0 :     break;
    3554             :   case 5: // 5431 TQ 1
    3555           0 :     planes[0] = 1;
    3556           0 :     planes[1] = 3;
    3557           0 :     planes[2] = 4;
    3558           0 :     planes[3] = 5;
    3559           0 :     break;
    3560             :   case 6: // 4320 TQ 1
    3561           0 :     planes[0] = 0;
    3562           0 :     planes[1] = 2;
    3563           0 :     planes[2] = 3;
    3564           0 :     planes[3] = 4;
    3565           0 :     break;
    3566             :   case 7: // 5430 TQ 2
    3567           0 :     planes[0] = 0;
    3568           0 :     planes[1] = 3;
    3569           0 :     planes[2] = 4;
    3570           0 :     planes[3] = 5;
    3571           0 :     break;
    3572             :   case 8: // 5210 TQ 2
    3573           0 :     planes[0] = 0;
    3574           0 :     planes[1] = 1;
    3575           0 :     planes[2] = 2;
    3576           0 :     planes[3] = 5;
    3577           0 :     break;
    3578             :   case 9: // 5421 TQ 3
    3579           0 :     planes[0] = 1;
    3580           0 :     planes[1] = 2;
    3581           0 :     planes[2] = 4;
    3582           0 :     planes[3] = 5;
    3583           0 :     break;
    3584             :   case 10: // 4310 TQ 3
    3585           0 :     planes[0] = 0;
    3586           0 :     planes[1] = 1;
    3587           0 :     planes[2] = 3;
    3588           0 :     planes[3] = 4;
    3589           0 :     break;
    3590             :   case 11: // 5410 TQ 4
    3591           0 :     planes[0] = 0;
    3592           0 :     planes[1] = 1;
    3593           0 :     planes[2] = 4;
    3594           0 :     planes[3] = 5;
    3595           0 :     break;
    3596             :   case 12: // 5420 TQ 5
    3597           0 :     planes[0] = 0;
    3598           0 :     planes[1] = 2;
    3599           0 :     planes[2] = 4;
    3600           0 :     planes[3] = 5;
    3601           0 :     break;
    3602             :   case 13: // 5320 TQ 5
    3603           0 :     planes[0] = 0;
    3604           0 :     planes[1] = 2;
    3605           0 :     planes[2] = 3;
    3606           0 :     planes[3] = 5;
    3607           0 :     break;
    3608             :   case 14: // 5310 TQ 5
    3609           0 :     planes[0] = 0;
    3610           0 :     planes[1] = 1;
    3611           0 :     planes[2] = 3;
    3612           0 :     planes[3] = 5;
    3613           0 :     break;
    3614             :   }
    3615           0 : }
    3616             : 
    3617             : //____________________________________________________________________
    3618             : void AliTRDtrackerV1::GetExtrapolationConfig(Int_t iconfig, Int_t planes[2])
    3619             : {
    3620             :   //
    3621             :   // Returns the extrapolation planes for a seeding configuration.
    3622             :   //
    3623             :   // Parameters :
    3624             :   //   iconfig : configuration index
    3625             :   //   planes  : planes which are not in this configuration. On input empty.
    3626             :   //
    3627             :   // Output :
    3628             :   //   planes : contains the planes which are not in the configuration
    3629             :   // 
    3630             :   // Detailed description
    3631             :   //
    3632             : 
    3633           0 :   switch(iconfig){
    3634             :   case 0: // 5432 TQ 0
    3635           0 :     planes[0] = 1;
    3636           0 :     planes[1] = 0;
    3637           0 :     break;
    3638             :   case 1: // 4321 TQ 0
    3639           0 :     planes[0] = 5;
    3640           0 :     planes[1] = 0;
    3641           0 :     break;
    3642             :   case 2: // 3210 TQ 0
    3643           0 :     planes[0] = 4;
    3644           0 :     planes[1] = 5;
    3645           0 :     break;
    3646             :   case 3: // 5321 TQ 1
    3647           0 :     planes[0] = 4;
    3648           0 :     planes[1] = 0;
    3649           0 :     break;
    3650             :   case 4: // 4210 TQ 1
    3651           0 :     planes[0] = 5;
    3652           0 :     planes[1] = 3;
    3653           0 :     break;
    3654             :   case 5: // 5431 TQ 1
    3655           0 :     planes[0] = 2;
    3656           0 :     planes[1] = 0;
    3657           0 :     break;
    3658             :   case 6: // 4320 TQ 1
    3659           0 :     planes[0] = 5;
    3660           0 :     planes[1] = 1;
    3661           0 :     break;
    3662             :   case 7: // 5430 TQ 2
    3663           0 :     planes[0] = 2;
    3664           0 :     planes[1] = 1;
    3665           0 :     break;
    3666             :   case 8: // 5210 TQ 2
    3667           0 :     planes[0] = 4;
    3668           0 :     planes[1] = 3;
    3669           0 :     break;
    3670             :   case 9: // 5421 TQ 3
    3671           0 :     planes[0] = 3;
    3672           0 :     planes[1] = 0;
    3673           0 :     break;
    3674             :   case 10: // 4310 TQ 3
    3675           0 :     planes[0] = 5;
    3676           0 :     planes[1] = 2;
    3677           0 :     break;
    3678             :   case 11: // 5410 TQ 4
    3679           0 :     planes[0] = 3;
    3680           0 :     planes[1] = 2;
    3681           0 :     break;
    3682             :   case 12: // 5420 TQ 5
    3683           0 :     planes[0] = 3;
    3684           0 :     planes[1] = 1;
    3685           0 :     break;
    3686             :   case 13: // 5320 TQ 5
    3687           0 :     planes[0] = 4;
    3688           0 :     planes[1] = 1;
    3689           0 :     break;
    3690             :   case 14: // 5310 TQ 5
    3691           0 :     planes[0] = 4;
    3692           0 :     planes[1] = 2;
    3693           0 :     break;
    3694             :   }
    3695           0 : }
    3696             : 
    3697             : //____________________________________________________________________
    3698             : AliCluster* AliTRDtrackerV1::GetCluster(Int_t idx) const
    3699             : {
    3700           0 :   if(!fClusters) return NULL;
    3701           0 :   Int_t ncls = fClusters->GetEntriesFast();
    3702           0 :   return idx >= 0 && idx < ncls ? (AliCluster*)fClusters->UncheckedAt(idx) : NULL;
    3703           0 : }
    3704             : 
    3705             : //____________________________________________________________________
    3706             : AliTRDseedV1* AliTRDtrackerV1::GetTracklet(Int_t idx) const
    3707             : {
    3708         230 :   if(!fTracklets) return NULL;
    3709         115 :   Int_t ntrklt = fTracklets->GetEntriesFast();
    3710         460 :   return idx >= 0 && idx < ntrklt ? (AliTRDseedV1*)fTracklets->UncheckedAt(idx) : NULL;
    3711         115 : }
    3712             : 
    3713             : //____________________________________________________________________
    3714             : AliKalmanTrack* AliTRDtrackerV1::GetTrack(Int_t idx) const
    3715             : {
    3716           0 :   if(!fTracks) return NULL;
    3717           0 :   Int_t ntrk = fTracks->GetEntriesFast();
    3718           0 :   return idx >= 0 && idx < ntrk ? (AliKalmanTrack*)fTracks->UncheckedAt(idx) : NULL;
    3719           0 : }
    3720             : 
    3721             : 
    3722             : 
    3723             : // //_____________________________________________________________________________
    3724             : // Int_t AliTRDtrackerV1::Freq(Int_t n, const Int_t *inlist
    3725             : //           , Int_t *outlist, Bool_t down)
    3726             : // {    
    3727             : //   //
    3728             : //   // Sort eleements according occurancy 
    3729             : //   // The size of output array has is 2*n 
    3730             : //   //
    3731             : // 
    3732             : //   if (n <= 0) {
    3733             : //     return 0;
    3734             : //   }
    3735             : // 
    3736             : //   Int_t *sindexS = new Int_t[n];   // Temporary array for sorting
    3737             : //   Int_t *sindexF = new Int_t[2*n];   
    3738             : //   for (Int_t i = 0; i < n; i++) {
    3739             : //     sindexF[i] = 0;
    3740             : //   }
    3741             : // 
    3742             : //   TMath::Sort(n,inlist,sindexS,down); 
    3743             : // 
    3744             : //   Int_t last     = inlist[sindexS[0]];
    3745             : //   Int_t val      = last;
    3746             : //   sindexF[0]     = 1;
    3747             : //   sindexF[0+n]   = last;
    3748             : //   Int_t countPos = 0;
    3749             : // 
    3750             : //   // Find frequency
    3751             : //   for (Int_t i = 1; i < n; i++) {
    3752             : //     val = inlist[sindexS[i]];
    3753             : //     if (last == val) {
    3754             : //       sindexF[countPos]++;
    3755             : //     }
    3756             : //     else {      
    3757             : //       countPos++;
    3758             : //       sindexF[countPos+n] = val;
    3759             : //       sindexF[countPos]++;
    3760             : //       last                = val;
    3761             : //     }
    3762             : //   }
    3763             : //   if (last == val) {
    3764             : //     countPos++;
    3765             : //   }
    3766             : // 
    3767             : //   // Sort according frequency
    3768             : //   TMath::Sort(countPos,sindexF,sindexS,kTRUE);
    3769             : // 
    3770             : //   for (Int_t i = 0; i < countPos; i++) {
    3771             : //     outlist[2*i  ] = sindexF[sindexS[i]+n];
    3772             : //     outlist[2*i+1] = sindexF[sindexS[i]];
    3773             : //   }
    3774             : // 
    3775             : //   delete [] sindexS;
    3776             : //   delete [] sindexF;
    3777             : //   
    3778             : //   return countPos;
    3779             : // 
    3780             : // }
    3781             : 
    3782             : 
    3783             : //____________________________________________________________________
    3784             : void AliTRDtrackerV1::ResetSeedTB()
    3785             : {
    3786             : // reset buffer for seeding time bin layers. If the time bin 
    3787             : // layers are not allocated this function allocates them  
    3788             : 
    3789           0 :   for(Int_t isl=0; isl<kNSeedPlanes; isl++){
    3790           0 :     if(!fSeedTB[isl]) fSeedTB[isl] = new AliTRDchamberTimeBin();
    3791           0 :     else fSeedTB[isl]->Clear();
    3792             :   }
    3793           0 : }
    3794             : 
    3795             : 
    3796             : //_____________________________________________________________________________
    3797             : Float_t AliTRDtrackerV1::GetChi2Y(const AliTRDseedV1 * const tracklets) const
    3798             : {
    3799             :   //    Calculates normalized chi2 in y-direction
    3800             :   // chi2 = Sum chi2 / n_tracklets
    3801             : 
    3802             :   Double_t chi2 = 0.; Int_t n = 0;
    3803           0 :   for(Int_t ipl = kNPlanes; ipl--;){
    3804           0 :     if(!tracklets[ipl].IsOK()) continue;
    3805           0 :     chi2 += tracklets[ipl].GetChi2Y();
    3806           0 :     n++;
    3807             :   }
    3808           0 :   return n ? chi2/n : 0.;
    3809             : }
    3810             : 
    3811             : //_____________________________________________________________________________
    3812             : Float_t AliTRDtrackerV1::GetChi2Z(const AliTRDseedV1 *const tracklets) const 
    3813             : {
    3814             :   //    Calculates normalized chi2 in z-direction
    3815             :   // chi2 = Sum chi2 / n_tracklets
    3816             : 
    3817             :   Double_t chi2 = 0; Int_t n = 0;
    3818           0 :   for(Int_t ipl = kNPlanes; ipl--;){
    3819           0 :     if(!tracklets[ipl].IsOK()) continue;
    3820           0 :     chi2 += tracklets[ipl].GetChi2Z();
    3821           0 :     n++;
    3822             :   }
    3823           0 :   return n ? chi2/n : 0.;
    3824             : }
    3825             : 
    3826             : //_____________________________________________________________________________
    3827             : Float_t AliTRDtrackerV1::GetChi2Phi(const AliTRDseedV1 *const tracklets) const 
    3828             : {
    3829             :   //  Calculates normalized chi2 for angular resolution
    3830             :   // chi2 = Sum chi2 / n_tracklets
    3831             : 
    3832             :   Double_t chi2 = 0; Int_t n = 0;
    3833           0 :   for (Int_t iLayer = 0; iLayer < kNPlanes; iLayer++) {
    3834           0 :     if(!tracklets[iLayer].IsOK()) continue;
    3835           0 :     chi2 += tracklets[iLayer].GetChi2Phi();
    3836           0 :     n++;
    3837           0 :   }
    3838           0 :   return n ? chi2/n: 0.;
    3839             : }
    3840             : 
    3841             : //____________________________________________________________________
    3842             : Float_t AliTRDtrackerV1::CalculateReferenceX(const AliTRDseedV1 *const tracklets){
    3843             :         //
    3844             :         // Calculates the reference x-position for the tilted Rieman fit defined as middle
    3845             :         // of the stack (middle between layers 2 and 3). For the calculation all the tracklets
    3846             :         // are taken into account
    3847             :         //
    3848             :         // Parameters: - Array of tracklets(AliTRDseedV1)
    3849             :         //
    3850             :         // Output: - The reference x-position(Float_t)
    3851             :   // Only kept for compatibility with the old code
    3852             :         //
    3853             :         Int_t nDistances = 0;
    3854             :         Float_t meanDistance = 0.;
    3855             :         Int_t startIndex = 5;
    3856           0 :         for(Int_t il =5; il > 0; il--){
    3857           0 :         if(tracklets[il].IsOK() && tracklets[il -1].IsOK()){
    3858           0 :         Float_t xdiff = tracklets[il].GetX0() - tracklets[il -1].GetX0();
    3859           0 :             meanDistance += xdiff;
    3860           0 :             nDistances++;
    3861           0 :           }
    3862           0 :           if(tracklets[il].IsOK()) startIndex = il;
    3863             :         }
    3864           0 :         if(tracklets[0].IsOK()) startIndex = 0;
    3865           0 :         if(!nDistances){
    3866             :           // We should normally never get here
    3867           0 :           Float_t xpos[2]; memset(xpos, 0, sizeof(Float_t) * 2);
    3868             :           Int_t iok = 0, idiff = 0;
    3869             :           // This attempt is worse and should be avoided:
    3870             :           // check for two chambers which are OK and repeat this without taking the mean value
    3871             :           // Strategy avoids a division by 0;
    3872           0 :           for(Int_t il = 5; il >= 0; il--){
    3873           0 :             if(tracklets[il].IsOK()){
    3874           0 :               xpos[iok] = tracklets[il].GetX0();
    3875           0 :               iok++;
    3876             :               startIndex = il;
    3877           0 :             }
    3878           0 :             if(iok) idiff++; // to get the right difference;
    3879           0 :             if(iok > 1) break;
    3880             :           }
    3881           0 :           if(iok > 1){
    3882           0 :             meanDistance = (xpos[0] - xpos[1])/idiff;
    3883             :           }
    3884             :           else{
    3885             :             // we have do not even have 2 layers which are OK? The we do not need to fit at all
    3886           0 :             return 331.;
    3887             :         }
    3888           0 :         }
    3889             :         else{
    3890           0 :           meanDistance /= nDistances;
    3891             :         }
    3892           0 :         return tracklets[startIndex].GetX0() + (2.5 - startIndex) * meanDistance - 0.5 * (AliTRDgeometry::AmThick() + AliTRDgeometry::DrThick());
    3893           0 : }
    3894             : 
    3895             : //_____________________________________________________________________________
    3896             : Double_t AliTRDtrackerV1::FitTiltedRiemanV1(AliTRDseedV1 *const tracklets){
    3897             :   //
    3898             :   // Track Fitter Function using the new class implementation of 
    3899             :   // the Rieman fit
    3900             :   //
    3901           0 :   AliTRDtrackFitterRieman fitter;
    3902           0 :   fitter.SetRiemanFitter(GetTiltedRiemanFitter());
    3903           0 :   fitter.Reset();
    3904           0 :   for(Int_t il = 0; il < AliTRDgeometry::kNlayer; il++) fitter.SetTracklet(il, &tracklets[il]);
    3905           0 :   Double_t chi2 = fitter.Eval();
    3906             :   // Update the tracklets
    3907           0 :   Double_t cov[15]; Double_t x0;
    3908           0 :   memset(cov, 0, sizeof(Double_t) * 15);
    3909           0 :   for(Int_t il = 0; il < AliTRDgeometry::kNlayer; il++){
    3910           0 :     x0 = tracklets[il].GetX0();
    3911           0 :     tracklets[il].SetYref(0, fitter.GetYat(x0));
    3912           0 :     tracklets[il].SetZref(0, fitter.GetZat(x0));
    3913           0 :     tracklets[il].SetYref(1, fitter.GetDyDxAt(x0));
    3914           0 :     tracklets[il].SetZref(1, fitter.GetDzDx());
    3915           0 :     tracklets[il].SetC(fitter.GetCurvature());
    3916           0 :     fitter.GetCovAt(x0, cov);
    3917           0 :     tracklets[il].SetCovRef(cov);
    3918           0 :     tracklets[il].SetChi2(chi2);
    3919             :   }
    3920             :   return chi2;
    3921           0 : }
    3922             : 
    3923             : //____________________________________________________________________
    3924             : void AliTRDtrackerV1::UnsetTrackletsTrack(const AliTRDtrackV1 * const track)
    3925             : {
    3926             : //  Remove tracklets from tracker list attached to "track"
    3927             :   Int_t idx(-1);
    3928           0 :   for(Int_t il(0); il<kNPlanes; il++){
    3929           0 :     if((idx = track->GetTrackletIndex(il)) < 0) continue;
    3930           0 :     delete (fTracklets->RemoveAt(idx));
    3931             :   }
    3932           0 : }
    3933             : 
    3934             : 
    3935             : ///////////////////////////////////////////////////////
    3936             : //                                                   //
    3937             : // Resources of class AliTRDLeastSquare              //
    3938             : //                                                   //
    3939             : ///////////////////////////////////////////////////////
    3940             : 
    3941             : //_____________________________________________________________________________
    3942           4 : AliTRDtrackerV1::AliTRDLeastSquare::AliTRDLeastSquare(){
    3943             : //
    3944             : // Constructor of the nested class AliTRDtrackFitterLeastSquare
    3945             : //
    3946             : // Fast solving linear regresion in 2D
    3947             : //         y=a + bx
    3948             : // The data members have the following meaning
    3949             : // fParams[0] : a
    3950             : // fParams[1] : b
    3951             : // 
    3952             : // fSums[0] : S
    3953             : // fSums[1] : Sx
    3954             : // fSums[2] : Sy
    3955             : // fSums[3] : Sxy
    3956             : // fSums[4] : Sxx
    3957             : // fSums[5] : Syy
    3958             : // 
    3959             : // fCovarianceMatrix[0] : s2a
    3960             : // fCovarianceMatrix[1] : s2b
    3961             : // fCovarianceMatrix[2] : cov(ab)
    3962             : 
    3963           4 :   memset(fParams, 0, sizeof(Double_t) * 2);
    3964           2 :   memset(fSums, 0, sizeof(Double_t) * 6);
    3965           2 :   memset(fCovarianceMatrix, 0, sizeof(Double_t) * 3);
    3966             : 
    3967           4 : }
    3968             : 
    3969             : //_____________________________________________________________________________
    3970             : void AliTRDtrackerV1::AliTRDLeastSquare::AddPoint(const Double_t *const x, Double_t y, Double_t sigmaY){
    3971             :   //
    3972             :   // Adding Point to the fitter
    3973             :   //
    3974             :   
    3975       53814 :   Double_t weight = 1/(sigmaY > 1e-9 ? sigmaY : 1e-9);
    3976       26907 :   weight *= weight;
    3977             :   const Double_t &xpt = *x;
    3978             :   //    printf("Adding point x = %f, y = %f, sigma = %f\n", xpt, y, sigmaY);
    3979       26907 :   fSums[0] += weight;
    3980       26907 :   fSums[1] += weight * xpt;
    3981       26907 :   fSums[2] += weight * y;
    3982       26907 :   fSums[3] += weight * xpt * y;
    3983       26907 :   fSums[4] += weight * xpt * xpt;
    3984       26907 :   fSums[5] += weight * y * y;
    3985       26907 : }
    3986             : 
    3987             : //_____________________________________________________________________________
    3988             : void AliTRDtrackerV1::AliTRDLeastSquare::RemovePoint(const Double_t *const x, Double_t y, Double_t sigmaY){
    3989             :   //
    3990             :   // Remove Point from the sample
    3991             :   //
    3992             : 
    3993           0 :   Double_t weight = 1/(sigmaY > 1e-9 ? sigmaY : 1e-9);
    3994           0 :   weight *= weight;
    3995             :   const Double_t &xpt = *x; 
    3996           0 :   fSums[0] -= weight;
    3997           0 :   fSums[1] -= weight * xpt;
    3998           0 :   fSums[2] -= weight * y;
    3999           0 :   fSums[3] -= weight * xpt * y;
    4000           0 :   fSums[4] -= weight * xpt * xpt;
    4001           0 :   fSums[5] -= weight * y * y;
    4002           0 : }
    4003             : 
    4004             : //_____________________________________________________________________________
    4005             : Bool_t AliTRDtrackerV1::AliTRDLeastSquare::Eval(){
    4006             :   //
    4007             :   // Evaluation of the fit:
    4008             :   // Calculation of the parameters
    4009             :   // Calculation of the covariance matrix
    4010             :   //
    4011             :   
    4012        3110 :   Double_t det = fSums[0] * fSums[4] - fSums[1] *fSums[1];
    4013        1555 :   if(TMath::Abs(det)<1.e-30) return kFALSE;
    4014             : 
    4015             :   //    for(Int_t isum = 0; isum < 5; isum++)
    4016             :   //            printf("fSums[%d] = %f\n", isum, fSums[isum]);
    4017             :   //    printf("denominator = %f\n", denominator);
    4018        1555 :   fParams[0] = (fSums[2] * fSums[4] - fSums[1] * fSums[3])/det;
    4019        1555 :   fParams[1] = (fSums[0] * fSums[3] - fSums[1] * fSums[2])/det;
    4020             :   //    printf("fParams[0] = %f, fParams[1] = %f\n", fParams[0], fParams[1]);
    4021             :   
    4022             :   // Covariance matrix
    4023        1555 :   Double_t den = fSums[0]*fSums[4] - fSums[1]*fSums[1];
    4024        1555 :   fCovarianceMatrix[0] = fSums[4] / den;
    4025        1555 :   fCovarianceMatrix[1] = fSums[0] / den;
    4026        1555 :   fCovarianceMatrix[2] = -fSums[1] / den;
    4027             : /*  fCovarianceMatrix[0] = fSums[4] / fSums[0] - fSums[1] * fSums[1] / (fSums[0] * fSums[0]);
    4028             :   fCovarianceMatrix[1] = fSums[5] / fSums[0] - fSums[2] * fSums[2] / (fSums[0] * fSums[0]);
    4029             :   fCovarianceMatrix[2] = fSums[3] / fSums[0] - fSums[1] * fSums[2] / (fSums[0] * fSums[0]);*/
    4030             : 
    4031             : 
    4032             : 
    4033             :   return kTRUE;
    4034        1555 : }
    4035             : 
    4036             : //_____________________________________________________________________________
    4037             : Double_t AliTRDtrackerV1::AliTRDLeastSquare::GetFunctionValue(const Double_t *const xpos) const {
    4038             :   //
    4039             :   // Returns the Function value of the fitted function at a given x-position
    4040             :   //
    4041           0 :   return fParams[0] + fParams[1] * (*xpos);
    4042             : }
    4043             : 
    4044             : //_____________________________________________________________________________
    4045             : void AliTRDtrackerV1::AliTRDLeastSquare::GetCovarianceMatrix(Double_t *storage) const {
    4046             :   //
    4047             :   // Copies the values of the covariance matrix into the storage
    4048             :   //
    4049        1352 :   memcpy(storage, fCovarianceMatrix, sizeof(Double_t) * 3);
    4050         676 : }
    4051             : 
    4052             : //_____________________________________________________________________________
    4053             : void AliTRDtrackerV1::AliTRDLeastSquare::Reset(){
    4054             :   //
    4055             :   // Reset the fitter
    4056             :   //
    4057        3342 :   memset(fParams, 0, sizeof(Double_t) * 2);
    4058        1671 :   memset(fCovarianceMatrix, 0, sizeof(Double_t) * 3);
    4059        1671 :   memset(fSums, 0, sizeof(Double_t) * 6);
    4060        1671 : }
    4061             : 
    4062             : ///////////////////////////////////////////////////////
    4063             : //                                                   //
    4064             : // Resources of class AliTRDtrackFitterRieman        //
    4065             : //                                                   //
    4066             : ///////////////////////////////////////////////////////
    4067             : 
    4068             : //_____________________________________________________________________________
    4069             : AliTRDtrackerV1::AliTRDtrackFitterRieman::AliTRDtrackFitterRieman():
    4070           0 :   fTrackFitter(NULL),
    4071           0 :   fZfitter(NULL),
    4072           0 :   fCovarPolY(NULL),
    4073           0 :   fCovarPolZ(NULL),
    4074           0 :   fXref(0.),
    4075           0 :   fSysClusterError(0.)
    4076           0 : {
    4077             :   //
    4078             :   // Default constructor
    4079             :   //
    4080           0 :   fZfitter = new AliTRDLeastSquare;
    4081           0 :   fCovarPolY = new TMatrixD(3,3);
    4082           0 :   fCovarPolZ = new TMatrixD(2,2);
    4083           0 :   memset(fTracklets, 0, sizeof(AliTRDseedV1 *) * 6);
    4084           0 :   memset(fParameters, 0, sizeof(Double_t) * 5);
    4085           0 :   memset(fSumPolY, 0, sizeof(Double_t) * 5);
    4086           0 :   memset(fSumPolZ, 0, sizeof(Double_t) * 2);
    4087           0 : }
    4088             : 
    4089             : //_____________________________________________________________________________
    4090           0 : AliTRDtrackerV1::AliTRDtrackFitterRieman::~AliTRDtrackFitterRieman(){
    4091             :   //
    4092             :   // Destructor
    4093             :   //
    4094           0 :   if(fZfitter) delete fZfitter;
    4095           0 :   if(fCovarPolY) delete fCovarPolY;
    4096           0 :   if(fCovarPolZ) delete fCovarPolZ;
    4097           0 : }
    4098             : 
    4099             : //_____________________________________________________________________________
    4100             : void AliTRDtrackerV1::AliTRDtrackFitterRieman::Reset(){
    4101             :   //
    4102             :   // Reset the Fitter
    4103             :   //
    4104           0 :   if(fTrackFitter){
    4105           0 :     fTrackFitter->StoreData(kTRUE);
    4106           0 :     fTrackFitter->ClearPoints();
    4107           0 :   }
    4108           0 :   if(fZfitter){
    4109           0 :     fZfitter->Reset();
    4110           0 :   }
    4111           0 :   fXref = 0.;
    4112           0 :   memset(fTracklets, 0, sizeof(AliTRDseedV1 *) * AliTRDgeometry::kNlayer);
    4113           0 :   memset(fParameters, 0, sizeof(Double_t) * 5);
    4114           0 :   memset(fSumPolY, 0, sizeof(Double_t) * 5);
    4115           0 :   memset(fSumPolZ, 0, sizeof(Double_t) * 2);
    4116           0 :   for(Int_t irow = 0; irow < fCovarPolY->GetNrows(); irow++)
    4117           0 :     for(Int_t icol = 0; icol < fCovarPolY->GetNcols(); icol++){
    4118           0 :       (*fCovarPolY)(irow, icol) = 0.;
    4119           0 :       if(irow < 2 && icol < 2)
    4120           0 :         (*fCovarPolZ)(irow, icol) = 0.;
    4121             :     }
    4122           0 : }
    4123             : 
    4124             : //_____________________________________________________________________________
    4125             : void AliTRDtrackerV1::AliTRDtrackFitterRieman::SetTracklet(Int_t itr, AliTRDseedV1 *tracklet){ 
    4126             :   //
    4127             :   // Add tracklet into the fitter
    4128             :   //
    4129           0 :   if(itr >= AliTRDgeometry::kNlayer) return;
    4130           0 :   fTracklets[itr] = tracklet; 
    4131           0 : }
    4132             : 
    4133             : //_____________________________________________________________________________
    4134             : Double_t AliTRDtrackerV1::AliTRDtrackFitterRieman::Eval(){
    4135             :   //
    4136             :   // Perform the fit
    4137             :   // 1. Apply linear transformation and store points in the fitter
    4138             :   // 2. Evaluate the fit
    4139             :   // 3. Check if the result of the fit in z-direction is reasonable
    4140             :   // if not
    4141             :   // 3a. Fix the parameters 3 and 4 with the results of a simple least
    4142             :   //     square fit
    4143             :   // 3b. Redo the fit with the fixed parameters
    4144             :   // 4. Store fit results (parameters and errors)
    4145             :   //
    4146           0 :   if(!fTrackFitter){
    4147           0 :     return 1e10;
    4148             :   }
    4149           0 :   fXref = CalculateReferenceX();
    4150           0 :   for(Int_t il = 0; il < AliTRDgeometry::kNlayer; il++) UpdateFitters(fTracklets[il]);
    4151           0 :   if(!fTrackFitter->GetNpoints()) return 1e10;
    4152             :   // perform the fit
    4153           0 :   fTrackFitter->Eval();
    4154           0 :   fZfitter->Eval();
    4155           0 :   fParameters[3] = fTrackFitter->GetParameter(3);
    4156           0 :   fParameters[4] = fTrackFitter->GetParameter(4);
    4157           0 :   if(!CheckAcceptable(fParameters[3], fParameters[4])) {
    4158           0 :     fTrackFitter->FixParameter(3, fZfitter->GetFunctionValue(&fXref));
    4159           0 :     fTrackFitter->FixParameter(4, fZfitter->GetFunctionParameter(1));
    4160           0 :     fTrackFitter->Eval();
    4161           0 :     fTrackFitter->ReleaseParameter(3);
    4162           0 :     fTrackFitter->ReleaseParameter(4);
    4163           0 :     fParameters[3] = fTrackFitter->GetParameter(3);
    4164           0 :     fParameters[4] = fTrackFitter->GetParameter(4);
    4165           0 :   }
    4166             :   // Update the Fit Parameters and the errors
    4167           0 :   fParameters[0] = fTrackFitter->GetParameter(0);
    4168           0 :   fParameters[1] = fTrackFitter->GetParameter(1);
    4169           0 :   fParameters[2] = fTrackFitter->GetParameter(2);
    4170             : 
    4171             :   // Prepare Covariance estimation
    4172           0 :   (*fCovarPolY)(0,0) = fSumPolY[0]; (*fCovarPolY)(1,1) = fSumPolY[2]; (*fCovarPolY)(2,2) = fSumPolY[4];
    4173           0 :   (*fCovarPolY)(1,0) = (*fCovarPolY)(0,1) = fSumPolY[1];
    4174           0 :   (*fCovarPolY)(2,0) = (*fCovarPolY)(0,2) = fSumPolY[2];
    4175           0 :   (*fCovarPolY)(2,1) = (*fCovarPolY)(1,2) = fSumPolY[3];
    4176           0 :   fCovarPolY->Invert();
    4177           0 :   (*fCovarPolZ)(0,0) = fSumPolZ[0]; (*fCovarPolZ)(1,1) = fSumPolZ[2];
    4178           0 :   (*fCovarPolZ)(1,0) = (*fCovarPolZ)(0,1) = fSumPolZ[1];
    4179           0 :   fCovarPolZ->Invert();
    4180           0 :   return fTrackFitter->GetChisquare() / fTrackFitter->GetNpoints();
    4181           0 : }
    4182             : 
    4183             : //_____________________________________________________________________________
    4184             : void AliTRDtrackerV1::AliTRDtrackFitterRieman::UpdateFitters(const AliTRDseedV1 * const tracklet){
    4185             :   //
    4186             :   // Does the transformations and updates the fitters
    4187             :   // The following transformation is applied
    4188             :   //
    4189             :   AliTRDcluster *cl = NULL;
    4190           0 :   Double_t x, y, z, dx, t, w, we, yerr, zerr;
    4191           0 :   Double_t uvt[4];
    4192           0 :   if(!tracklet || !tracklet->IsOK()) return; 
    4193           0 :   Double_t tilt = tracklet->GetTilt();
    4194           0 :   for(Int_t itb = 0; itb < AliTRDseedV1::kNclusters; itb++){
    4195           0 :     if(!(cl = tracklet->GetClusters(itb))) continue;
    4196           0 :     if(!cl->IsInChamber()) continue;
    4197           0 :     if (!tracklet->IsUsable(itb)) continue;
    4198           0 :     x = cl->GetX();
    4199           0 :     y = cl->GetY();
    4200           0 :     z = cl->GetZ();
    4201           0 :     dx = x - fXref;
    4202             :     // Transformation
    4203           0 :     t = 1./(x*x + y*y);
    4204           0 :     uvt[0] = 2. * x * t;
    4205           0 :     uvt[1] = t;
    4206           0 :     uvt[2] = 2. * tilt * t;
    4207           0 :     uvt[3] = 2. * tilt * dx * t;
    4208           0 :     w = 2. * (y + tilt*z) * t;
    4209             :     // error definition changes for the different calls
    4210           0 :     we = 2. * t;
    4211           0 :     we *= TMath::Sqrt(cl->GetSigmaY2()+tilt*tilt*cl->GetSigmaZ2());
    4212             :     // Update sums for error calculation
    4213           0 :     yerr = 1./(TMath::Sqrt(cl->GetSigmaY2()) + fSysClusterError);
    4214           0 :     yerr *= yerr;
    4215           0 :     zerr = 1./cl->GetSigmaZ2();
    4216           0 :     for(Int_t ipol = 0; ipol < 5; ipol++){
    4217           0 :       fSumPolY[ipol] += yerr;
    4218           0 :       yerr *= x;
    4219           0 :       if(ipol < 3){
    4220           0 :         fSumPolZ[ipol] += zerr;
    4221           0 :         zerr *= x;
    4222           0 :       }
    4223             :     }
    4224           0 :     fTrackFitter->AddPoint(uvt, w, we);
    4225           0 :     fZfitter->AddPoint(&x, z, static_cast<Double_t>(TMath::Sqrt(cl->GetSigmaZ2())));
    4226           0 :   }
    4227           0 : }
    4228             : 
    4229             : //_____________________________________________________________________________
    4230             : Bool_t AliTRDtrackerV1::AliTRDtrackFitterRieman::CheckAcceptable(Double_t offset, Double_t slope){
    4231             :   // 
    4232             :   // Check whether z-results are acceptable
    4233             :   // Definition: Distance between tracklet fit and track fit has to be
    4234             :   // less then half a padlength
    4235             :   // Point of comparision is at the anode wire
    4236             :   //
    4237             :   Bool_t acceptablez = kTRUE;
    4238             :   Double_t zref = 0.0;
    4239           0 :   for (Int_t iLayer = 0; iLayer < kNPlanes; iLayer++) {
    4240           0 :     if(!fTracklets[iLayer]->IsOK()) continue;
    4241           0 :     zref = offset + slope * (fTracklets[iLayer]->GetX0() - fXref);
    4242           0 :     if (TMath::Abs(fTracklets[iLayer]->GetZfit(0) - zref) > fTracklets[iLayer]->GetPadLength() * 0.5 + 1.0) 
    4243           0 :       acceptablez = kFALSE;
    4244             :   }
    4245           0 :   return acceptablez;
    4246             : }
    4247             : 
    4248             : //_____________________________________________________________________________
    4249             : Double_t AliTRDtrackerV1::AliTRDtrackFitterRieman::GetYat(Double_t x) const {
    4250             :   //
    4251             :   // Calculate y position out of the track parameters
    4252             :   // y:     R^2 = (x - x0)^2 + (y - y0)^2
    4253             :   //     =>   y = y0 +/- Sqrt(R^2 - (x - x0)^2)
    4254             :   //          R = Sqrt() = 1/Curvature
    4255             :   //     =>   y = y0 +/- Sqrt(1/Curvature^2 - (x - x0)^2)
    4256             :   //
    4257             :   Double_t y = 0;
    4258           0 :   Double_t disc = (x * fParameters[0] + fParameters[1]);
    4259           0 :   disc = 1 - fParameters[0]*fParameters[2] + fParameters[1]*fParameters[1] - disc*disc;
    4260           0 :   if (disc >= 0) {
    4261           0 :     disc = TMath::Sqrt(disc);
    4262           0 :     y    = (1.0 - disc) / fParameters[0];
    4263           0 :   }
    4264           0 :   return y;
    4265             : }
    4266             : 
    4267             : //_____________________________________________________________________________
    4268             : Double_t AliTRDtrackerV1::AliTRDtrackFitterRieman::GetZat(Double_t x) const {
    4269             :   //
    4270             :   // Return z position for a given x position
    4271             :   // Simple linear function
    4272             :   //
    4273           0 :   return fParameters[3] + fParameters[4] * (x - fXref);
    4274             : }
    4275             : 
    4276             : //_____________________________________________________________________________
    4277             : Double_t AliTRDtrackerV1::AliTRDtrackFitterRieman::GetDyDxAt(Double_t x) const {
    4278             :   //
    4279             :   // Calculate dydx at a given radial position out of the track parameters
    4280             :   // dy:      R^2 = (x - x0)^2 + (y - y0)^2
    4281             :   //     =>     y = +/- Sqrt(R^2 - (x - x0)^2) + y0
    4282             :   //     => dy/dx = (x - x0)/Sqrt(R^2 - (x - x0)^2) 
    4283             :   // Curvature: cr = 1/R = a/Sqrt(1 + b^2 - c*a)
    4284             :   //     => dy/dx =  (x - x0)/(1/(cr^2) - (x - x0)^2) 
    4285             :   //
    4286           0 :   Double_t x0 = -fParameters[1] / fParameters[0];
    4287           0 :   Double_t curvature = GetCurvature();
    4288             :   Double_t dy = 0;
    4289           0 :   if (-fParameters[2] * fParameters[0] + fParameters[1] * fParameters[1] + 1 > 0) {
    4290           0 :     if (1.0/(curvature * curvature) - (x - x0) * (x - x0) > 0.0) {
    4291           0 :      Double_t yderiv = (x - x0) / TMath::Sqrt(1.0/(curvature * curvature) - (x - x0) * (x - x0));
    4292           0 :       if (fParameters[0] < 0) yderiv *= -1.0;
    4293             :       dy = yderiv;
    4294           0 :     }
    4295             :   }
    4296           0 :   return dy;
    4297             : }
    4298             : 
    4299             : //_____________________________________________________________________________
    4300             : Double_t AliTRDtrackerV1::AliTRDtrackFitterRieman::GetCurvature() const {
    4301             :   //
    4302             :   // Calculate track curvature
    4303             :   //
    4304             :   //
    4305           0 :   Double_t curvature =  1.0 + fParameters[1]*fParameters[1] - fParameters[2]*fParameters[0];
    4306           0 :   if (curvature > 0.0) 
    4307           0 :     curvature  =  fParameters[0] / TMath::Sqrt(curvature);
    4308           0 :   return curvature;
    4309             : }
    4310             : 
    4311             : //_____________________________________________________________________________
    4312             : void AliTRDtrackerV1::AliTRDtrackFitterRieman::GetCovAt(Double_t x, Double_t *cov) const {
    4313             :   //
    4314             :   // Error Definition according to gauss error propagation
    4315             :   //  
    4316           0 :   TMatrixD transform(3,3);
    4317           0 :   transform(0,0) = transform(1,1) = transform(2,2) = 1;
    4318           0 :   transform(0,1) = transform(1,2) = x;
    4319           0 :   transform(0,2) = x*x;
    4320           0 :   TMatrixD covariance(transform, TMatrixD::kMult, *fCovarPolY);
    4321           0 :   covariance *= transform.T();
    4322           0 :   cov[0] = covariance(0,0);
    4323           0 :   TMatrixD transformZ(2,2);
    4324           0 :   transformZ(0,0) = transformZ(1,1) = 1;
    4325           0 :   transformZ(0,1) = x;
    4326           0 :   TMatrixD covarZ(transformZ, TMatrixD::kMult, *fCovarPolZ);
    4327           0 :   covarZ *= transformZ.T();
    4328           0 :   cov[1] = covarZ(0,0);
    4329           0 :   cov[2] = 0;
    4330           0 : }
    4331             : 
    4332             : //____________________________________________________________________
    4333             : Double_t AliTRDtrackerV1::AliTRDtrackFitterRieman::CalculateReferenceX(){
    4334             :   //
    4335             :   // Calculates the reference x-position for the tilted Rieman fit defined as middle
    4336             :   // of the stack (middle between layers 2 and 3). For the calculation all the tracklets
    4337             :   // are taken into account
    4338             :   // 
    4339             :   // Parameters:        - Array of tracklets(AliTRDseedV1)
    4340             :   //
    4341             :   // Output:            - The reference x-position(Float_t)
    4342             :   //
    4343             :   Int_t nDistances = 0;
    4344             :   Float_t meanDistance = 0.;
    4345             :   Int_t startIndex = 5;
    4346           0 :   for(Int_t il =5; il > 0; il--){
    4347           0 :     if(fTracklets[il]->IsOK() && fTracklets[il -1]->IsOK()){
    4348           0 :       Float_t xdiff = fTracklets[il]->GetX0() - fTracklets[il -1]->GetX0();
    4349           0 :       meanDistance += xdiff;
    4350           0 :       nDistances++;
    4351           0 :     }
    4352           0 :     if(fTracklets[il]->IsOK()) startIndex = il;
    4353             :   }
    4354           0 :   if(fTracklets[0]->IsOK()) startIndex = 0;
    4355           0 :   if(!nDistances){
    4356             :     // We should normally never get here
    4357           0 :     Float_t xpos[2]; memset(xpos, 0, sizeof(Float_t) * 2);
    4358             :     Int_t iok = 0, idiff = 0;
    4359             :     // This attempt is worse and should be avoided:
    4360             :     // check for two chambers which are OK and repeat this without taking the mean value
    4361             :     // Strategy avoids a division by 0;
    4362           0 :     for(Int_t il = 5; il >= 0; il--){
    4363           0 :       if(fTracklets[il]->IsOK()){
    4364           0 :         xpos[iok] = fTracklets[il]->GetX0();
    4365           0 :         iok++;
    4366             :         startIndex = il;
    4367           0 :       }
    4368           0 :       if(iok) idiff++;  // to get the right difference;
    4369           0 :       if(iok > 1) break;
    4370             :     }
    4371           0 :     if(iok > 1){
    4372           0 :       meanDistance = (xpos[0] - xpos[1])/idiff;
    4373             :     }
    4374             :     else{
    4375             :       // we have do not even have 2 layers which are OK? The we do not need to fit at all
    4376           0 :       return 331.;
    4377             :     }
    4378           0 :   }
    4379             :   else{
    4380           0 :     meanDistance /= nDistances;
    4381             :   }
    4382           0 :   return fTracklets[startIndex]->GetX0() + (2.5 - startIndex) * meanDistance - 0.5 * (AliTRDgeometry::AmThick() + AliTRDgeometry::DrThick());
    4383           0 : }

Generated by: LCOV version 1.11