]> git.uio.no Git - u/mrichter/AliRoot.git/blob - MUON/AliMUONVTrackReconstructor.cxx
update from salvatore
[u/mrichter/AliRoot.git] / MUON / AliMUONVTrackReconstructor.cxx
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 /// \class AliMUONVTrackReconstructor
20 /// Virtual MUON track reconstructor in ALICE (class renamed from AliMUONEventReconstructor)
21 ///
22 /// This class contains as data a pointer to the array of reconstructed tracks
23 ///
24 /// It contains as methods, among others:
25 /// * EventReconstruct to build the muon tracks
26 /// * EventReconstructTrigger to build the trigger tracks
27 /// * ValidateTracksWithTrigger to match tracker/trigger tracks
28 ///
29 /// Several options and adjustable parameters are available for both KALMAN and ORIGINAL
30 /// tracking algorithms. They can be changed through the AliMUONRecoParam object
31 /// set in the reconstruction macro or read from the CDB
32 /// (see methods in AliMUONRecoParam.h file for details)
33 ///
34 /// Main parameters and options are:
35 /// - *fgkSigmaToCutForTracking* : quality cut used to select new clusters to be
36 ///   attached to the track candidate and to select good tracks.
37 /// - *fgkMakeTrackCandidatesFast* : if this flag is set to 'true', the track candidates
38 ///   are made assuming linear propagation between stations 4 and 5.
39 /// - *fgkTrackAllTracks* : according to the value of this flag, in case that several
40 ///   new clusters pass the quality cut, either we consider all the possibilities
41 ///   (duplicating tracks) or we attach only the best cluster.
42 /// - *fgkRecoverTracks* : if this flag is set to 'true', we try to recover the tracks
43 ///   lost during the tracking by removing the worst of the 2 clusters attached in the
44 ///   previous station.
45 /// - *fgkImproveTracks* : if this flag is set to 'true', we try to improve the quality
46 ///   of the tracks at the end of the tracking by removing clusters that do not pass
47 ///   new quality cut (the track is removed is it does not contain enough cluster anymore).
48 /// - *fgkComplementTracks* : if this flag is set to 'true', we try to improve the quality
49 ///   of the tracks at the end of the tracking by adding potentially missing clusters
50 ///   (we may have 2 clusters in the same chamber because of the overlapping of detection
51 ///   elements, which is not handle by the tracking algorithm).
52 /// - *fgkSigmaToCutForImprovement* : quality cut used when we try to improve the
53 ///   quality of the tracks.
54 ///
55 ///  \author Philippe Pillot
56 //-----------------------------------------------------------------------------
57
58 #include "AliMUONVTrackReconstructor.h"
59
60 #include "AliMUONConstants.h"
61 #include "AliMUONObjectPair.h"
62 #include "AliMUONTriggerTrack.h"
63 #include "AliMUONTriggerCircuit.h"
64 #include "AliMUONLocalTrigger.h"
65 #include "AliMUONGlobalTrigger.h"
66 #include "AliMUONTrack.h"
67 #include "AliMUONTrackParam.h"
68 #include "AliMUONTrackExtrap.h"
69 #include "AliMUONTrackHitPattern.h"
70 #include "AliMUONVTrackStore.h"
71 #include "AliMUONVClusterStore.h"
72 #include "AliMUONVCluster.h"
73 #include "AliMUONVClusterServer.h"
74 #include "AliMUONVTriggerStore.h"
75 #include "AliMUONVTriggerTrackStore.h"
76 #include "AliMUONRecoParam.h"
77
78 #include "AliMpDEManager.h"
79 #include "AliMpArea.h"
80
81 #include "AliMpDDLStore.h"
82 #include "AliMpVSegmentation.h"
83 #include "AliMpSegmentation.h"
84 #include "AliMpPad.h"
85
86 #include "AliLog.h"
87 #include "AliCodeTimer.h"
88 #include "AliTracker.h"
89
90 #include <TClonesArray.h>
91 #include <TMath.h>
92 #include <TMatrixD.h>
93 #include <TVector2.h>
94
95 #include <Riostream.h>
96
97 using std::cout;
98 using std::endl;
99 /// \cond CLASSIMP
100 ClassImp(AliMUONVTrackReconstructor) // Class implementation in ROOT context
101 /// \endcond
102
103   //__________________________________________________________________________
104 AliMUONVTrackReconstructor::AliMUONVTrackReconstructor(const AliMUONRecoParam* recoParam,
105                                                        AliMUONVClusterServer* clusterServer)
106 : TObject(),
107 fRecTracksPtr(0x0),
108 fNRecTracks(0),
109 fClusterServer(clusterServer),
110 fkRecoParam(recoParam),
111 fMaxMCSAngle2(0x0)
112 {
113   /// Constructor for class AliMUONVTrackReconstructor
114   /// WARNING: if clusterServer=0x0, no clusterization will be possible at this level
115   
116   // Memory allocation for the TClonesArray of reconstructed tracks
117   fRecTracksPtr = new TClonesArray("AliMUONTrack", 100);
118   
119   // set the magnetic field for track extrapolations
120   AliMUONTrackExtrap::SetField();
121   
122   // set the maximum MCS angle in chamber from the minimum acceptable momentum
123   AliMUONTrackParam param;
124   Double_t inverseBendingP = (GetRecoParam()->GetMinBendingMomentum() > 0.) ? 1./GetRecoParam()->GetMinBendingMomentum() : 1.;
125   param.SetInverseBendingMomentum(inverseBendingP);
126   fMaxMCSAngle2 = new Double_t [AliMUONConstants::NTrackingCh()];
127   for (Int_t iCh=0; iCh<AliMUONConstants::NTrackingCh(); iCh++)
128     fMaxMCSAngle2[iCh] = AliMUONTrackExtrap::GetMCSAngle2(param, AliMUONConstants::ChamberThicknessInX0(iCh), 1.);
129   
130 }
131
132   //__________________________________________________________________________
133 AliMUONVTrackReconstructor::~AliMUONVTrackReconstructor()
134 {
135   /// Destructor for class AliMUONVTrackReconstructor
136   delete fRecTracksPtr;
137   delete[] fMaxMCSAngle2;
138 }
139
140   //__________________________________________________________________________
141 void AliMUONVTrackReconstructor::ResetTracks()
142 {
143   /// To reset the TClonesArray of reconstructed tracks
144   if (fRecTracksPtr) fRecTracksPtr->Clear("C");
145   fNRecTracks = 0;
146   return;
147 }
148
149   //__________________________________________________________________________
150 void AliMUONVTrackReconstructor::EventReconstruct(AliMUONVClusterStore& clusterStore, AliMUONVTrackStore& trackStore)
151 {
152   /// To reconstruct one event
153   AliDebug(1,"");
154   AliCodeTimerAuto("",0);
155   
156   // Reset array of tracks
157   ResetTracks();
158   
159   // Look for candidates from clusters in stations(1..) 4 and 5 (abort in case of failure)
160   if (!MakeTrackCandidates(clusterStore)) return;
161   
162   // Look for extra candidates from clusters in stations(1..) 4 and 5 (abort in case of failure)
163   if (GetRecoParam()->MakeMoreTrackCandidates()) {
164     if (!MakeMoreTrackCandidates(clusterStore)) return;
165   }
166   
167   // Stop tracking if no candidate found
168   if (fRecTracksPtr->GetEntriesFast() == 0) return;
169   
170   // Follow tracks in stations(1..) 3, 2 and 1 (abort in case of failure)
171   if (!FollowTracks(clusterStore)) return;
172   
173   // Complement the reconstructed tracks
174   if (GetRecoParam()->ComplementTracks()) {
175     if (ComplementTracks(clusterStore)) RemoveIdenticalTracks();
176   }
177   
178   // Improve the reconstructed tracks
179   if (GetRecoParam()->ImproveTracks()) ImproveTracks();
180   
181   // Remove connected tracks
182   RemoveConnectedTracks(3, 4, kFALSE);
183   RemoveConnectedTracks(2, 2, kFALSE);
184   if (GetRecoParam()->RemoveConnectedTracksInSt12()) RemoveConnectedTracks(0, 1, kFALSE);
185   
186   // Fill AliMUONTrack data members
187   Finalize();
188   if (!GetRecoParam()->RemoveConnectedTracksInSt12()) TagConnectedTracks(0, 1, kTRUE);
189   
190   // Add tracks to MUON data container 
191   for (Int_t i=0; i<fNRecTracks; ++i)
192   {
193     AliMUONTrack * track = (AliMUONTrack*) fRecTracksPtr->At(i);
194     if (track->GetGlobalChi2() < AliMUONTrack::MaxChi2()) {
195       track->SetUniqueID(i+1);
196       trackStore.Add(*track);
197     } else AliWarning("problem occur somewhere during track refitting --> discard track");
198   }
199 }
200
201 //__________________________________________________________________________
202 Bool_t AliMUONVTrackReconstructor::IsAcceptable(AliMUONTrackParam &trackParam)
203 {
204   /// Return kTRUE if the track is within given limits on momentum/angle/origin
205   
206   const TMatrixD& kParamCov = trackParam.GetCovariances();
207   Int_t chamber = trackParam.GetClusterPtr()->GetChamberId();
208   Double_t z = trackParam.GetZ();
209   Double_t sigmaCut = GetRecoParam()->GetSigmaCutForTracking();
210   
211   // MCS dipersion
212   Double_t angleMCS2 = 0.;
213   Double_t impactMCS2 = 0.;
214   if (AliMUONTrackExtrap::IsFieldON() && chamber < 6) {
215     
216     // track momentum is known
217     for (Int_t iCh=0; iCh<=chamber; iCh++) {
218       Double_t localMCS2 = AliMUONTrackExtrap::GetMCSAngle2(trackParam, AliMUONConstants::ChamberThicknessInX0(iCh), 1.);
219       angleMCS2 += localMCS2;
220       impactMCS2 += AliMUONConstants::DefaultChamberZ(chamber) * AliMUONConstants::DefaultChamberZ(chamber) * localMCS2;
221     }
222     
223   } else {
224     
225     // track momentum is unknown
226     for (Int_t iCh=0; iCh<=chamber; iCh++) {
227       angleMCS2 += fMaxMCSAngle2[iCh];
228       impactMCS2 += AliMUONConstants::DefaultChamberZ(chamber) * AliMUONConstants::DefaultChamberZ(chamber) * fMaxMCSAngle2[iCh];
229     }
230     
231   }
232   
233   // ------ track selection in non bending direction ------
234   if (GetRecoParam()->SelectOnTrackSlope()) {
235     
236     // check if non bending slope is within tolerances
237     Double_t nonBendingSlopeErr = TMath::Sqrt(kParamCov(1,1) + angleMCS2);
238     if ((TMath::Abs(trackParam.GetNonBendingSlope()) - sigmaCut * nonBendingSlopeErr) > GetRecoParam()->GetMaxNonBendingSlope()) return kFALSE;
239     
240   } else {
241     
242     // or check if non bending impact parameter is within tolerances
243     Double_t nonBendingImpactParam = TMath::Abs(trackParam.GetNonBendingCoor() - z * trackParam.GetNonBendingSlope());
244     Double_t nonBendingImpactParamErr = TMath::Sqrt(kParamCov(0,0) + z * z * kParamCov(1,1) - 2. * z * kParamCov(0,1) + impactMCS2);
245     if ((nonBendingImpactParam - sigmaCut * nonBendingImpactParamErr) > (3. * GetRecoParam()->GetNonBendingVertexDispersion())) return kFALSE;
246     
247   }
248   
249   // ------ track selection in bending direction ------
250   if (AliMUONTrackExtrap::IsFieldON()) { // depending whether the field is ON or OFF
251     
252     // check if bending momentum is within tolerances
253     Double_t bendingMomentum = TMath::Abs(1. / trackParam.GetInverseBendingMomentum());
254     Double_t bendingMomentumErr = TMath::Sqrt(kParamCov(4,4)) * bendingMomentum * bendingMomentum;
255     if (chamber < 6 && (bendingMomentum + sigmaCut * bendingMomentumErr) < GetRecoParam()->GetMinBendingMomentum()) return kFALSE;
256     else if ((bendingMomentum + 3. * bendingMomentumErr) < GetRecoParam()->GetMinBendingMomentum()) return kFALSE;
257     
258   } else {
259     
260     if (GetRecoParam()->SelectOnTrackSlope()) {
261       
262       // check if bending slope is within tolerances
263       Double_t bendingSlopeErr = TMath::Sqrt(kParamCov(3,3) + angleMCS2);
264       if ((TMath::Abs(trackParam.GetBendingSlope()) - sigmaCut * bendingSlopeErr) > GetRecoParam()->GetMaxBendingSlope()) return kFALSE;
265       
266     } else {
267       
268       // or check if bending impact parameter is within tolerances
269       Double_t bendingImpactParam = TMath::Abs(trackParam.GetBendingCoor() - z * trackParam.GetBendingSlope());
270       Double_t bendingImpactParamErr = TMath::Sqrt(kParamCov(2,2) + z * z * kParamCov(3,3) - 2. * z * kParamCov(2,3) + impactMCS2);
271       if ((bendingImpactParam - sigmaCut * bendingImpactParamErr) > (3. * GetRecoParam()->GetBendingVertexDispersion())) return kFALSE;
272       
273     }
274     
275   }
276   
277   return kTRUE;
278   
279 }
280
281 //__________________________________________________________________________
282 TClonesArray* AliMUONVTrackReconstructor::MakeSegmentsBetweenChambers(const AliMUONVClusterStore& clusterStore, Int_t ch1, Int_t ch2)
283 {
284   /// To make the list of segments from the list of clusters in the 2 given chambers.
285   /// Return a TClonesArray of new segments (segments made in a previous call of this function are removed).
286   AliDebug(1,Form("Enter MakeSegmentsBetweenChambers (1..) %d-%d", ch1+1, ch2+1));
287   AliCodeTimerAuto("",0);
288   
289   AliMUONVCluster *cluster1, *cluster2;
290   AliMUONObjectPair *segment;
291   Double_t z1 = 0., z2 = 0., dZ = 0.;
292   Double_t nonBendingSlope = 0., nonBendingSlopeErr = 0., nonBendingImpactParam = 0., nonBendingImpactParamErr = 0.;
293   Double_t bendingSlope = 0., bendingSlopeErr = 0., bendingImpactParam = 0., bendingImpactParamErr = 0., bendingImpactParamErr2 = 0.;
294   Double_t bendingMomentum = 0., bendingMomentumErr = 0.;
295   Double_t bendingVertexDispersion2 = GetRecoParam()->GetBendingVertexDispersion() * GetRecoParam()->GetBendingVertexDispersion();
296   Double_t angleMCS2 = 0.; // maximum angular dispersion**2 due to MCS in chamber
297   Double_t impactMCS2 = 0.; // maximum impact parameter dispersion**2 due to MCS in chamber
298   for (Int_t iCh=0; iCh<=ch1; iCh++) {
299     angleMCS2 += fMaxMCSAngle2[iCh];
300     impactMCS2 += AliMUONConstants::DefaultChamberZ(iCh) * AliMUONConstants::DefaultChamberZ(iCh) * fMaxMCSAngle2[iCh];
301   }
302   Double_t sigmaCut = GetRecoParam()->GetSigmaCutForTracking();
303   
304   // Create iterators to loop over clusters in both chambers
305   TIter nextInCh1(clusterStore.CreateChamberIterator(ch1,ch1));
306   TIter nextInCh2(clusterStore.CreateChamberIterator(ch2,ch2));
307   
308   // list of segments
309   static TClonesArray *segments = new TClonesArray("AliMUONObjectPair", 100);
310   segments->Clear("C");
311   
312   // Loop over clusters in the first chamber of the station
313   while ( ( cluster1 = static_cast<AliMUONVCluster*>(nextInCh1()) ) ) {
314     z1 = cluster1->GetZ();
315     
316     // reset cluster iterator of chamber 2
317     nextInCh2.Reset();
318     
319     // Loop over clusters in the second chamber of the station
320     while ( ( cluster2 = static_cast<AliMUONVCluster*>(nextInCh2()) ) ) {
321       z2 = cluster2->GetZ();
322       dZ = z1 - z2;
323       
324       // ------ track selection in non bending direction ------
325       nonBendingSlope = (cluster1->GetX() - cluster2->GetX()) / dZ;
326       if (GetRecoParam()->SelectOnTrackSlope()) {
327         
328         // check if non bending slope is within tolerances
329         nonBendingSlopeErr = TMath::Sqrt((cluster1->GetErrX2() + cluster2->GetErrX2()) / dZ / dZ + angleMCS2);
330         if ((TMath::Abs(nonBendingSlope) - sigmaCut * nonBendingSlopeErr) > GetRecoParam()->GetMaxNonBendingSlope()) continue;
331         
332       } else {
333         
334         // or check if non bending impact parameter is within tolerances
335         nonBendingImpactParam = TMath::Abs(cluster1->GetX() - cluster1->GetZ() * nonBendingSlope);
336         nonBendingImpactParamErr = TMath::Sqrt((z1 * z1 * cluster2->GetErrX2() + z2 * z2 * cluster1->GetErrX2()) / dZ / dZ + impactMCS2);
337         if ((nonBendingImpactParam - sigmaCut * nonBendingImpactParamErr) > (3. * GetRecoParam()->GetNonBendingVertexDispersion())) continue;
338         
339       }
340       
341       // ------ track selection in bending direction ------
342       bendingSlope = (cluster1->GetY() - cluster2->GetY()) / dZ;
343       if (AliMUONTrackExtrap::IsFieldON()) { // depending whether the field is ON or OFF
344         
345         // check if bending momentum is within tolerances
346         bendingImpactParam = cluster1->GetY() - cluster1->GetZ() * bendingSlope;
347         bendingImpactParamErr2 = (z1 * z1 * cluster2->GetErrY2() + z2 * z2 * cluster1->GetErrY2()) / dZ / dZ + impactMCS2;
348         bendingMomentum = TMath::Abs(AliMUONTrackExtrap::GetBendingMomentumFromImpactParam(bendingImpactParam));
349         bendingMomentumErr = TMath::Sqrt((bendingVertexDispersion2 + bendingImpactParamErr2) /
350                                          bendingImpactParam / bendingImpactParam + 0.01) * bendingMomentum;
351         if ((bendingMomentum + 3. * bendingMomentumErr) < GetRecoParam()->GetMinBendingMomentum()) continue;
352         
353       } else {
354         
355         if (GetRecoParam()->SelectOnTrackSlope()) {
356           
357           // check if bending slope is within tolerances
358           bendingSlopeErr = TMath::Sqrt((cluster1->GetErrY2() + cluster2->GetErrY2()) / dZ / dZ + angleMCS2);
359           if ((TMath::Abs(bendingSlope) - sigmaCut * bendingSlopeErr) > GetRecoParam()->GetMaxBendingSlope()) continue;
360           
361         } else {
362           
363           // or check if bending impact parameter is within tolerances
364           bendingImpactParam = TMath::Abs(cluster1->GetY() - cluster1->GetZ() * bendingSlope);
365           bendingImpactParamErr = TMath::Sqrt((z1 * z1 * cluster2->GetErrY2() + z2 * z2 * cluster1->GetErrY2()) / dZ / dZ + impactMCS2);
366           if ((bendingImpactParam - sigmaCut * bendingImpactParamErr) > (3. * GetRecoParam()->GetBendingVertexDispersion())) continue;
367           
368         }
369         
370       }
371       
372       // make new segment
373       segment = new ((*segments)[segments->GetLast()+1]) AliMUONObjectPair(cluster1, cluster2, kFALSE, kFALSE);
374       
375       // Printout for debug
376       if (AliLog::GetGlobalDebugLevel() > 1) {
377         cout << "segmentIndex(0...): " << segments->GetLast() << endl;
378         segment->Dump();
379         cout << "Cluster in first chamber" << endl;
380         cluster1->Print();
381         cout << "Cluster in second chamber" << endl;
382         cluster2->Print();
383       }
384       
385     }
386     
387   }
388   
389   // Printout for debug
390   AliDebug(1,Form("chambers%d-%d: NSegments =  %d ", ch1+1, ch2+1, segments->GetEntriesFast()));
391   
392   return segments;
393 }
394
395   //__________________________________________________________________________
396 void AliMUONVTrackReconstructor::RemoveUsedSegments(TClonesArray& segments)
397 {
398   /// To remove pairs of clusters already attached to a track
399   AliDebug(1,"Enter RemoveUsedSegments");
400   Int_t nSegments = segments.GetEntriesFast();
401   Int_t nTracks = fRecTracksPtr->GetEntriesFast();
402   AliMUONObjectPair *segment;
403   AliMUONTrack *track;
404   AliMUONVCluster *cluster, *cluster1, *cluster2;
405   Bool_t foundCluster1, foundCluster2, removeSegment;
406   
407   // Loop over segments
408   for (Int_t iSegment=0; iSegment<nSegments; iSegment++) {
409     segment = (AliMUONObjectPair*) segments.UncheckedAt(iSegment);
410     
411     cluster1 = (AliMUONVCluster*) segment->First();
412     cluster2 = (AliMUONVCluster*) segment->Second();
413     removeSegment = kFALSE;
414     
415     // Loop over tracks
416     for (Int_t iTrack = 0; iTrack < nTracks; iTrack++) {
417       track = (AliMUONTrack*) fRecTracksPtr->UncheckedAt(iTrack);
418       
419       // skip empty slot
420       if (!track) continue;
421       
422       foundCluster1 = kFALSE;
423       foundCluster2 = kFALSE;
424       
425       // Loop over clusters
426       Int_t nClusters = track->GetNClusters();
427       for (Int_t iCluster = 0; iCluster < nClusters; iCluster++) {
428         cluster = ((AliMUONTrackParam*) track->GetTrackParamAtCluster()->UncheckedAt(iCluster))->GetClusterPtr();
429         
430         // check if both clusters are in that track
431         if (cluster == cluster1) foundCluster1 = kTRUE;
432         else if (cluster == cluster2) foundCluster2 = kTRUE;
433         
434         if (foundCluster1 && foundCluster2) {
435           removeSegment = kTRUE;
436           break;
437         }
438         
439       }
440       
441       if (removeSegment) break;
442       
443     }
444     
445     if (removeSegment) segments.RemoveAt(iSegment);
446       
447   }
448   
449   segments.Compress();
450   
451   // Printout for debug
452   AliDebug(1,Form("NSegments =  %d ", segments.GetEntriesFast()));
453 }
454
455   //__________________________________________________________________________
456 void AliMUONVTrackReconstructor::RemoveIdenticalTracks()
457 {
458   /// To remove identical tracks:
459   /// Tracks are considered identical if they have all their clusters in common.
460   /// One keeps the track with the larger number of clusters if need be
461   AliMUONTrack *track1, *track2;
462   Int_t nTracks = fRecTracksPtr->GetEntriesFast();
463   Int_t clustersInCommon, nClusters1, nClusters2;
464   // Loop over first track of the pair
465   for (Int_t iTrack1 = 0; iTrack1 < nTracks; iTrack1++) {
466     track1 = (AliMUONTrack*) fRecTracksPtr->UncheckedAt(iTrack1);
467     // skip empty slot
468     if (!track1) continue;
469     nClusters1 = track1->GetNClusters();
470     // Loop over second track of the pair
471     for (Int_t iTrack2 = iTrack1+1; iTrack2 < nTracks; iTrack2++) {
472       track2 = (AliMUONTrack*) fRecTracksPtr->UncheckedAt(iTrack2);
473       // skip empty slot
474       if (!track2) continue;
475       nClusters2 = track2->GetNClusters();
476       // number of clusters in common between two tracks
477       clustersInCommon = track1->ClustersInCommon(track2);
478       // check for identical tracks
479       if ((clustersInCommon == nClusters1) || (clustersInCommon == nClusters2)) {
480         // decide which track to remove
481         if (nClusters2 > nClusters1) {
482           // remove track1 and continue the first loop with the track next to track1
483           fRecTracksPtr->RemoveAt(iTrack1);
484           fNRecTracks--;
485           break;
486         } else {
487           // remove track2 and continue the second loop with the track next to track2
488           fRecTracksPtr->RemoveAt(iTrack2);
489           fNRecTracks--;
490         }
491       }
492     } // track2
493   } // track1
494   fRecTracksPtr->Compress(); // this is essential to retrieve the TClonesArray afterwards
495 }
496
497   //__________________________________________________________________________
498 void AliMUONVTrackReconstructor::RemoveDoubleTracks()
499 {
500   /// To remove double tracks:
501   /// Tracks are considered identical if more than half of the clusters of the track
502   /// which has the smaller number of clusters are in common with the other track.
503   /// Among two identical tracks, one keeps the track with the larger number of clusters
504   /// or, if these numbers are equal, the track with the minimum chi2.
505   AliMUONTrack *track1, *track2;
506   Int_t nTracks = fRecTracksPtr->GetEntriesFast();
507   Int_t clustersInCommon2, nClusters1, nClusters2;
508   // Loop over first track of the pair
509   for (Int_t iTrack1 = 0; iTrack1 < nTracks; iTrack1++) {
510     track1 = (AliMUONTrack*) fRecTracksPtr->UncheckedAt(iTrack1);
511     // skip empty slot
512     if (!track1) continue;
513     nClusters1 = track1->GetNClusters();
514     // Loop over second track of the pair
515     for (Int_t iTrack2 = iTrack1+1; iTrack2 < nTracks; iTrack2++) {
516       track2 = (AliMUONTrack*) fRecTracksPtr->UncheckedAt(iTrack2);
517       // skip empty slot
518       if (!track2) continue;
519       nClusters2 = track2->GetNClusters();
520       // number of clusters in common between two tracks
521       clustersInCommon2 = 2 * track1->ClustersInCommon(track2);
522       // check for identical tracks
523       if (clustersInCommon2 > nClusters1 || clustersInCommon2 > nClusters2) {
524         // decide which track to remove
525         if ((nClusters1 > nClusters2) || ((nClusters1 == nClusters2) && (track1->GetGlobalChi2() <= track2->GetGlobalChi2()))) {
526           // remove track2 and continue the second loop with the track next to track2
527           fRecTracksPtr->RemoveAt(iTrack2);
528           fNRecTracks--;
529         } else {
530           // else remove track1 and continue the first loop with the track next to track1
531           fRecTracksPtr->RemoveAt(iTrack1);
532           fNRecTracks--;
533           break;
534         }
535       }
536     } // track2
537   } // track1
538   fRecTracksPtr->Compress(); // this is essential to retrieve the TClonesArray afterwards
539 }
540
541   //__________________________________________________________________________
542 void AliMUONVTrackReconstructor::RemoveConnectedTracks(Int_t stMin, Int_t stMax, Bool_t all)
543 {
544   /// Find and remove tracks sharing 1 cluster or more in station(s) [stMin, stMax].
545   /// For each couple of connected tracks, one removes the one with the smallest
546   /// number of clusters or with the highest chi2 value in case of equality.
547   /// If all=kTRUE: both tracks are removed.
548   
549   // tag the tracks to be removed
550   TagConnectedTracks(stMin, stMax, all);
551   
552   // remove them
553   Int_t nTracks = fRecTracksPtr->GetEntriesFast();
554   for (Int_t i = 0; i < nTracks; i++) {
555     if (((AliMUONTrack*) fRecTracksPtr->UncheckedAt(i))->IsConnected()) {
556       fRecTracksPtr->RemoveAt(i);
557       fNRecTracks--;
558     }
559   }
560   
561   // remove holes in the array if any
562   fRecTracksPtr->Compress();
563 }
564
565   //__________________________________________________________________________
566 void AliMUONVTrackReconstructor::TagConnectedTracks(Int_t stMin, Int_t stMax, Bool_t all)
567 {
568   /// Find and tag tracks sharing 1 cluster or more in station(s) [stMin, stMax].
569   /// For each couple of connected tracks, one tags the one with the smallest
570   /// number of clusters or with the highest chi2 value in case of equality.
571   /// If all=kTRUE: both tracks are tagged.
572   
573   AliMUONTrack *track1, *track2;
574   Int_t nClusters1, nClusters2;
575   Int_t nTracks = fRecTracksPtr->GetEntriesFast();
576   
577   // reset the tags
578   for (Int_t i = 0; i < nTracks; i++) ((AliMUONTrack*) fRecTracksPtr->UncheckedAt(i))->Connected(kFALSE);
579     
580   // Loop over first track of the pair
581   for (Int_t iTrack1 = 0; iTrack1 < nTracks; iTrack1++) {
582     track1 = (AliMUONTrack*) fRecTracksPtr->UncheckedAt(iTrack1);
583     
584     // Loop over second track of the pair
585     for (Int_t iTrack2 = iTrack1+1; iTrack2 < nTracks; iTrack2++) {
586       track2 = (AliMUONTrack*) fRecTracksPtr->UncheckedAt(iTrack2);
587       
588       // check for connected tracks and tag them
589       if (track1->ClustersInCommon(track2, stMin, stMax) > 0) {
590         
591         if (all) {
592           
593           // tag both tracks
594           track1->Connected();
595           track2->Connected();
596           
597         } else {
598           
599           // tag only the worst track
600           nClusters1 = track1->GetNClusters();
601           nClusters2 = track2->GetNClusters();
602           if ((nClusters1 > nClusters2) || ((nClusters1 == nClusters2) && (track1->GetGlobalChi2() <= track2->GetGlobalChi2()))) {
603             track2->Connected();
604           } else {
605             track1->Connected();
606           }
607           
608         }
609         
610       }
611       
612     }
613     
614   }
615   
616 }
617
618   //__________________________________________________________________________
619 void AliMUONVTrackReconstructor::AskForNewClustersInChamber(const AliMUONTrackParam &trackParam,
620                                                             AliMUONVClusterStore& clusterStore, Int_t chamber)
621 {
622   /// Ask the clustering to reconstruct new clusters around the track candidate position
623   
624   // check if the current chamber is useable
625   if (!fClusterServer || !GetRecoParam()->UseChamber(chamber)) return;
626   
627   // maximum distance between the center of the chamber and a detection element
628   // (accounting for the inclination of the chamber)
629   static const Double_t kMaxDZ = 15.; // 15 cm
630   
631   // extrapolate track parameters to the chamber
632   AliMUONTrackParam extrapTrackParam(trackParam);
633   if (!AliMUONTrackExtrap::ExtrapToZCov(&extrapTrackParam, AliMUONConstants::DefaultChamberZ(chamber))) return;
634   
635   // build the searching area using the track and chamber resolutions and the maximum-distance-to-track value
636   const TMatrixD& kParamCov = extrapTrackParam.GetCovariances();
637   Double_t errX2 = kParamCov(0,0) + kMaxDZ * kMaxDZ * kParamCov(1,1) + 2. * kMaxDZ * TMath::Abs(kParamCov(0,1)) +
638                    GetRecoParam()->GetDefaultNonBendingReso(chamber) * GetRecoParam()->GetDefaultNonBendingReso(chamber);
639   Double_t errY2 = kParamCov(2,2) + kMaxDZ * kMaxDZ * kParamCov(3,3) + 2. * kMaxDZ * TMath::Abs(kParamCov(2,3)) +
640                    GetRecoParam()->GetDefaultBendingReso(chamber) * GetRecoParam()->GetDefaultBendingReso(chamber);
641   Double_t dX = TMath::Abs(trackParam.GetNonBendingSlope()) * kMaxDZ +
642                 GetRecoParam()->GetMaxNonBendingDistanceToTrack() +
643                 GetRecoParam()->GetSigmaCutForTracking() * TMath::Sqrt(2. * errX2);
644   Double_t dY = TMath::Abs(trackParam.GetBendingSlope()) * kMaxDZ +
645                 GetRecoParam()->GetMaxBendingDistanceToTrack() +
646                 GetRecoParam()->GetSigmaCutForTracking() * TMath::Sqrt(2. * errY2);
647   AliMpArea area(extrapTrackParam.GetNonBendingCoor(), 
648                  extrapTrackParam.GetBendingCoor(),
649                  dX, dY);
650   
651   // ask to cluterize in the given area of the given chamber
652   fClusterServer->Clusterize(chamber, clusterStore, area, GetRecoParam());
653   
654 }
655
656   //__________________________________________________________________________
657 void AliMUONVTrackReconstructor::AskForNewClustersInStation(const AliMUONTrackParam &trackParam,
658                                                             AliMUONVClusterStore& clusterStore, Int_t station)
659 {
660   /// Ask the clustering to reconstruct new clusters around the track candidate position
661   /// in the 2 chambers of the given station
662   AskForNewClustersInChamber(trackParam, clusterStore, 2*station+1);
663   AskForNewClustersInChamber(trackParam, clusterStore, 2*station);
664 }
665
666   //__________________________________________________________________________
667 Double_t AliMUONVTrackReconstructor::TryOneCluster(const AliMUONTrackParam &trackParam, AliMUONVCluster* cluster,
668                                                    AliMUONTrackParam &trackParamAtCluster, Bool_t updatePropagator)
669 {
670 /// Test the compatibility between the track and the cluster (using trackParam's covariance matrix):
671 /// return the corresponding Chi2
672 /// return trackParamAtCluster
673   
674   // extrapolate track parameters and covariances at the z position of the tested cluster
675   // and set pointer to cluster into trackParamAtCluster
676   trackParamAtCluster = trackParam;
677   trackParamAtCluster.SetClusterPtr(cluster);
678   if (!AliMUONTrackExtrap::ExtrapToZCov(&trackParamAtCluster, cluster->GetZ(), updatePropagator))
679     return 2.*AliMUONTrack::MaxChi2();
680   
681   // Set differences between trackParam and cluster in the bending and non bending directions
682   Double_t dX = cluster->GetX() - trackParamAtCluster.GetNonBendingCoor();
683   Double_t dY = cluster->GetY() - trackParamAtCluster.GetBendingCoor();
684   
685   // Calculate errors and covariances
686   const TMatrixD& kParamCov = trackParamAtCluster.GetCovariances();
687   Double_t sigmaX2 = kParamCov(0,0) + cluster->GetErrX2();
688   Double_t sigmaY2 = kParamCov(2,2) + cluster->GetErrY2();
689   Double_t covXY   = kParamCov(0,2);
690   Double_t det     = sigmaX2 * sigmaY2 - covXY * covXY;
691   
692   // Compute chi2
693   if (det == 0.) return 2.*AliMUONTrack::MaxChi2();
694   return (dX * dX * sigmaY2 + dY * dY * sigmaX2 - 2. * dX * dY * covXY) / det;
695   
696 }
697
698   //__________________________________________________________________________
699 Bool_t AliMUONVTrackReconstructor::TryOneClusterFast(const AliMUONTrackParam &trackParam, const AliMUONVCluster* cluster)
700 {
701 /// Test the compatibility between the track and the cluster
702 /// given the track and cluster resolutions + the maximum-distance-to-track value
703 /// and assuming linear propagation of the track:
704 /// return kTRUE if they are compatibles
705   
706   Double_t dZ = cluster->GetZ() - trackParam.GetZ();
707   Double_t dX = cluster->GetX() - (trackParam.GetNonBendingCoor() + trackParam.GetNonBendingSlope() * dZ);
708   Double_t dY = cluster->GetY() - (trackParam.GetBendingCoor() + trackParam.GetBendingSlope() * dZ);
709   const TMatrixD& kParamCov = trackParam.GetCovariances();
710   Double_t errX2 = kParamCov(0,0) + dZ * dZ * kParamCov(1,1) + 2. * dZ * kParamCov(0,1) + cluster->GetErrX2();
711   Double_t errY2 = kParamCov(2,2) + dZ * dZ * kParamCov(3,3) + 2. * dZ * kParamCov(2,3) + cluster->GetErrY2();
712
713   Double_t dXmax = GetRecoParam()->GetSigmaCutForTracking() * TMath::Sqrt(2. * errX2) +
714                    GetRecoParam()->GetMaxNonBendingDistanceToTrack();
715   Double_t dYmax = GetRecoParam()->GetSigmaCutForTracking() * TMath::Sqrt(2. * errY2) +
716                    GetRecoParam()->GetMaxBendingDistanceToTrack();
717   
718   if (TMath::Abs(dX) > dXmax || TMath::Abs(dY) > dYmax) return kFALSE;
719   
720   return kTRUE;
721   
722 }
723
724   //__________________________________________________________________________
725 Double_t AliMUONVTrackReconstructor::TryTwoClustersFast(const AliMUONTrackParam &trackParamAtCluster1, AliMUONVCluster* cluster2,
726                                                         AliMUONTrackParam &trackParamAtCluster2)
727 {
728 /// Test the compatibility between the track and the 2 clusters together (using trackParam's covariance matrix)
729 /// assuming linear propagation between the two clusters:
730 /// return the corresponding Chi2 accounting for covariances between the 2 clusters
731 /// return trackParamAtCluster2
732   
733   // extrapolate linearly track parameters and covariances at the z position of the second cluster
734   trackParamAtCluster2 = trackParamAtCluster1;
735   AliMUONTrackExtrap::LinearExtrapToZCov(&trackParamAtCluster2, cluster2->GetZ());
736   
737   // set pointer to cluster2 into trackParamAtCluster2
738   trackParamAtCluster2.SetClusterPtr(cluster2);
739   
740   // Set differences between track and clusters in the bending and non bending directions
741   AliMUONVCluster* cluster1 = trackParamAtCluster1.GetClusterPtr();
742   Double_t dX1 = cluster1->GetX() - trackParamAtCluster1.GetNonBendingCoor();
743   Double_t dX2 = cluster2->GetX() - trackParamAtCluster2.GetNonBendingCoor();
744   Double_t dY1 = cluster1->GetY() - trackParamAtCluster1.GetBendingCoor();
745   Double_t dY2 = cluster2->GetY() - trackParamAtCluster2.GetBendingCoor();
746   
747   // Calculate errors and covariances
748   const TMatrixD& kParamCov1 = trackParamAtCluster1.GetCovariances();
749   const TMatrixD& kParamCov2 = trackParamAtCluster2.GetCovariances();
750   Double_t dZ = trackParamAtCluster2.GetZ() - trackParamAtCluster1.GetZ();
751   Double_t sigma2X1 = kParamCov1(0,0) + cluster1->GetErrX2();
752   Double_t sigma2X2 = kParamCov2(0,0) + cluster2->GetErrX2();
753   Double_t covX1X2  = kParamCov1(0,0) + dZ * kParamCov1(0,1);
754   Double_t sigma2Y1 = kParamCov1(2,2) + cluster1->GetErrY2();
755   Double_t sigma2Y2 = kParamCov2(2,2) + cluster2->GetErrY2();
756   Double_t covY1Y2  = kParamCov1(2,2) + dZ * kParamCov1(2,3);
757   
758   // Compute chi2
759   Double_t detX = sigma2X1 * sigma2X2 - covX1X2 * covX1X2;
760   Double_t detY = sigma2Y1 * sigma2Y2 - covY1Y2 * covY1Y2;
761   if (detX == 0. || detY == 0.) return 2.*AliMUONTrack::MaxChi2();
762   return   (dX1 * dX1 * sigma2X2 + dX2 * dX2 * sigma2X1 - 2. * dX1 * dX2 * covX1X2) / detX
763          + (dY1 * dY1 * sigma2Y2 + dY2 * dY2 * sigma2Y1 - 2. * dY1 * dY2 * covY1Y2) / detY;
764   
765 }
766
767   //__________________________________________________________________________
768 Bool_t AliMUONVTrackReconstructor::FollowLinearTrackInChamber(AliMUONTrack &trackCandidate, const AliMUONVClusterStore& clusterStore,
769                                                               Int_t nextChamber)
770 {
771   /// Follow trackCandidate in chamber(0..) nextChamber assuming linear propagation, and search for compatible cluster(s)
772   /// Keep all possibilities or only the best one(s) according to the flag fgkTrackAllTracks:
773   /// kTRUE:  duplicate "trackCandidate" if there are several possibilities and add the new tracks at the end of
774   ///         fRecTracksPtr to avoid conficts with other track candidates at this current stage of the tracking procedure.
775   ///         Remove the obsolete "trackCandidate" at the end.
776   /// kFALSE: add only the best cluster(s) to the "trackCandidate". Try to add a couple of clusters in priority.
777   /// return kTRUE if new cluster(s) have been found (otherwise return kFALSE)
778   AliDebug(1,Form("Enter FollowLinearTrackInChamber(1..) %d", nextChamber+1));
779   
780   Double_t chi2WithOneCluster = AliMUONTrack::MaxChi2();
781   Double_t maxChi2WithOneCluster = 2. * GetRecoParam()->GetSigmaCutForTracking() *
782                                         GetRecoParam()->GetSigmaCutForTracking(); // 2 because 2 quantities in chi2
783   Double_t bestChi2WithOneCluster = maxChi2WithOneCluster;
784   Bool_t foundOneCluster = kFALSE;
785   AliMUONTrack *newTrack = 0x0;
786   AliMUONVCluster *cluster;
787   AliMUONTrackParam trackParam;
788   AliMUONTrackParam extrapTrackParamAtCluster;
789   AliMUONTrackParam bestTrackParamAtCluster;
790   
791   // Get track parameters according to the propagation direction
792   if (nextChamber > 7) trackParam = *(AliMUONTrackParam*)trackCandidate.GetTrackParamAtCluster()->Last();
793   else trackParam = *(AliMUONTrackParam*)trackCandidate.GetTrackParamAtCluster()->First();
794   
795   // Printout for debuging
796   if ((AliLog::GetDebugLevel("MUON","AliMUONVTrackReconstructor") >= 2) || (AliLog::GetGlobalDebugLevel() >= 2)) {
797     cout<<endl<<"Track parameters and covariances at first cluster:"<<endl;
798     trackParam.GetParameters().Print();
799     trackParam.GetCovariances().Print();
800   }
801   
802   // Add MCS effect
803   AliMUONTrackExtrap::AddMCSEffect(&trackParam,AliMUONConstants::ChamberThicknessInX0(trackParam.GetClusterPtr()->GetChamberId()),-1.);
804   
805   // Printout for debuging
806   if ((AliLog::GetDebugLevel("MUON","AliMUONVTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
807     cout << "FollowLinearTrackInChamber: look for cluster in chamber(1..): " << nextChamber+1 << endl;
808   }
809   
810   // Create iterators to loop over clusters in chamber
811   TIter next(clusterStore.CreateChamberIterator(nextChamber,nextChamber));
812   
813   // look for candidates in chamber
814   while ( ( cluster = static_cast<AliMUONVCluster*>(next()) ) ) {
815     
816     // try to add the current cluster fast
817     if (!TryOneClusterFast(trackParam, cluster)) continue;
818     
819     // try to add the current cluster accuratly
820     extrapTrackParamAtCluster = trackParam;
821     AliMUONTrackExtrap::LinearExtrapToZCov(&extrapTrackParamAtCluster, cluster->GetZ());
822     chi2WithOneCluster = TryOneCluster(extrapTrackParamAtCluster, cluster, extrapTrackParamAtCluster);
823     
824     // if good chi2 then consider to add cluster
825     if (chi2WithOneCluster < maxChi2WithOneCluster) {
826       foundOneCluster = kTRUE;
827       
828       // Printout for debuging
829       if ((AliLog::GetDebugLevel("MUON","AliMUONVTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
830         cout << "FollowLinearTrackInChamber: found one cluster in chamber(1..): " << nextChamber+1
831         << " (Chi2 = " << chi2WithOneCluster << ")" << endl;
832         cluster->Print();
833       }
834       
835       if (GetRecoParam()->TrackAllTracks()) {
836         // copy trackCandidate into a new track put at the end of fRecTracksPtr and add the new cluster
837         newTrack = new ((*fRecTracksPtr)[fRecTracksPtr->GetLast()+1]) AliMUONTrack(trackCandidate);
838         if (GetRecoParam()->RequestStation(nextChamber/2))
839           extrapTrackParamAtCluster.SetRemovable(kFALSE);
840         else extrapTrackParamAtCluster.SetRemovable(kTRUE);
841         newTrack->AddTrackParamAtCluster(extrapTrackParamAtCluster,*cluster);
842         newTrack->SetGlobalChi2(trackCandidate.GetGlobalChi2()+chi2WithOneCluster);
843         fNRecTracks++;
844         
845         // Printout for debuging
846         if ((AliLog::GetDebugLevel("MUON","AliMUONVTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
847           cout << "FollowLinearTrackInChamber: added one cluster in chamber(1..): " << nextChamber+1 << endl;
848           if (AliLog::GetGlobalDebugLevel() >= 3) newTrack->RecursiveDump();
849         }
850         
851       } else if (chi2WithOneCluster < bestChi2WithOneCluster) {
852         // keep track of the best cluster
853         bestChi2WithOneCluster = chi2WithOneCluster;
854         bestTrackParamAtCluster = extrapTrackParamAtCluster;
855       }
856       
857     }
858     
859   }
860   
861   // fill out the best track if required else clean up the fRecTracksPtr array
862   if (!GetRecoParam()->TrackAllTracks()) {
863     if (foundOneCluster) {
864       if (GetRecoParam()->RequestStation(nextChamber/2))
865         bestTrackParamAtCluster.SetRemovable(kFALSE);
866       else bestTrackParamAtCluster.SetRemovable(kTRUE);
867       trackCandidate.AddTrackParamAtCluster(bestTrackParamAtCluster,*(bestTrackParamAtCluster.GetClusterPtr()));
868       trackCandidate.SetGlobalChi2(trackCandidate.GetGlobalChi2()+bestChi2WithOneCluster);
869       
870       // Printout for debuging
871       if ((AliLog::GetDebugLevel("MUON","AliMUONVTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
872         cout << "FollowLinearTrackInChamber: added the best cluster in chamber(1..): " << bestTrackParamAtCluster.GetClusterPtr()->GetChamberId()+1 << endl;
873         if (AliLog::GetGlobalDebugLevel() >= 3) newTrack->RecursiveDump();
874       }
875       
876     } else return kFALSE;
877     
878   } else if (foundOneCluster) {
879     
880     // remove obsolete track
881     fRecTracksPtr->Remove(&trackCandidate);
882     fNRecTracks--;
883     
884   } else return kFALSE;
885   
886   return kTRUE;
887   
888 }
889
890 //__________________________________________________________________________
891 Bool_t AliMUONVTrackReconstructor::FollowLinearTrackInStation(AliMUONTrack &trackCandidate, const AliMUONVClusterStore& clusterStore,
892                                                               Int_t nextStation)
893 {
894   /// Follow trackCandidate in station(0..) nextStation assuming linear propagation, and search for compatible cluster(s)
895   /// Keep all possibilities or only the best one(s) according to the flag fgkTrackAllTracks:
896   /// kTRUE:  duplicate "trackCandidate" if there are several possibilities and add the new tracks at the end of
897   ///         fRecTracksPtr to avoid conficts with other track candidates at this current stage of the tracking procedure.
898   ///         Remove the obsolete "trackCandidate" at the end.
899   /// kFALSE: add only the best cluster(s) to the "trackCandidate". Try to add a couple of clusters in priority.
900   /// return kTRUE if new cluster(s) have been found (otherwise return kFALSE)
901   AliDebug(1,Form("Enter FollowLinearTrackInStation(1..) %d", nextStation+1));
902   
903   // Order the chamber according to the propagation direction (tracking starts with chamber 2):
904   // - nextStation == station(1...) 5 => forward propagation
905   // - nextStation < station(1...) 5 => backward propagation
906   Int_t ch1, ch2;
907   if (nextStation==4) {
908     ch1 = 2*nextStation+1;
909     ch2 = 2*nextStation;
910   } else {
911     ch1 = 2*nextStation;
912     ch2 = 2*nextStation+1;
913   }
914   
915   Double_t chi2WithOneCluster = AliMUONTrack::MaxChi2();
916   Double_t chi2WithTwoClusters = AliMUONTrack::MaxChi2();
917   Double_t maxChi2WithOneCluster = 2. * GetRecoParam()->GetSigmaCutForTracking() *
918                                         GetRecoParam()->GetSigmaCutForTracking(); // 2 because 2 quantities in chi2
919   Double_t maxChi2WithTwoClusters = 4. * GetRecoParam()->GetSigmaCutForTracking() *
920                                          GetRecoParam()->GetSigmaCutForTracking(); // 4 because 4 quantities in chi2
921   Double_t bestChi2WithOneCluster = maxChi2WithOneCluster;
922   Double_t bestChi2WithTwoClusters = maxChi2WithTwoClusters;
923   Bool_t foundOneCluster = kFALSE;
924   Bool_t foundTwoClusters = kFALSE;
925   AliMUONTrack *newTrack = 0x0;
926   AliMUONVCluster *clusterCh1, *clusterCh2;
927   AliMUONTrackParam trackParam;
928   AliMUONTrackParam extrapTrackParamAtCluster1;
929   AliMUONTrackParam extrapTrackParamAtCluster2;
930   AliMUONTrackParam bestTrackParamAtCluster1;
931   AliMUONTrackParam bestTrackParamAtCluster2;
932   
933   Int_t nClusters = clusterStore.GetSize();
934   Bool_t *clusterCh1Used = new Bool_t[nClusters];
935   for (Int_t i = 0; i < nClusters; i++) clusterCh1Used[i] = kFALSE;
936   Int_t iCluster1;
937   
938   // Get track parameters according to the propagation direction
939   if (nextStation==4) trackParam = *(AliMUONTrackParam*)trackCandidate.GetTrackParamAtCluster()->Last();
940   else trackParam = *(AliMUONTrackParam*)trackCandidate.GetTrackParamAtCluster()->First();
941   
942   // Printout for debuging
943   if ((AliLog::GetDebugLevel("MUON","AliMUONVTrackReconstructor") >= 2) || (AliLog::GetGlobalDebugLevel() >= 2)) {
944     cout<<endl<<"Track parameters and covariances at first cluster:"<<endl;
945     trackParam.GetParameters().Print();
946     trackParam.GetCovariances().Print();
947   }
948   
949   // Add MCS effect
950   AliMUONTrackExtrap::AddMCSEffect(&trackParam,AliMUONConstants::ChamberThicknessInX0(trackParam.GetClusterPtr()->GetChamberId()),-1.);
951   
952   // Printout for debuging
953   if ((AliLog::GetDebugLevel("MUON","AliMUONVTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
954     cout << "FollowLinearTrackInStation: look for clusters in chamber(1..): " << ch2+1 << endl;
955   }
956   
957   // Create iterators to loop over clusters in both chambers
958   TIter nextInCh1(clusterStore.CreateChamberIterator(ch1,ch1));
959   TIter nextInCh2(clusterStore.CreateChamberIterator(ch2,ch2));
960   
961   // look for candidates in chamber 2
962   while ( ( clusterCh2 = static_cast<AliMUONVCluster*>(nextInCh2()) ) ) {
963     
964     // try to add the current cluster fast
965     if (!TryOneClusterFast(trackParam, clusterCh2)) continue;
966     
967     // try to add the current cluster accuratly
968     extrapTrackParamAtCluster2 = trackParam;
969     AliMUONTrackExtrap::LinearExtrapToZCov(&extrapTrackParamAtCluster2, clusterCh2->GetZ());
970     chi2WithOneCluster = TryOneCluster(extrapTrackParamAtCluster2, clusterCh2, extrapTrackParamAtCluster2);
971     
972     // if good chi2 then try to attach a cluster in the other chamber too
973     if (chi2WithOneCluster < maxChi2WithOneCluster) {
974       Bool_t foundSecondCluster = kFALSE;
975       
976       // Printout for debuging
977       if ((AliLog::GetDebugLevel("MUON","AliMUONVTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
978         cout << "FollowLinearTrackInStation: found one cluster in chamber(1..): " << ch2+1
979              << " (Chi2 = " << chi2WithOneCluster << ")" << endl;
980         clusterCh2->Print();
981         cout << "                      look for second clusters in chamber(1..): " << ch1+1 << " ..." << endl;
982       }
983       
984       // add MCS effect
985       AliMUONTrackExtrap::AddMCSEffect(&extrapTrackParamAtCluster2,AliMUONConstants::ChamberThicknessInX0(ch2),-1.);
986       
987       // reset cluster iterator of chamber 1
988       nextInCh1.Reset();
989       iCluster1 = -1;
990       
991       // look for second candidates in chamber 1
992       while ( ( clusterCh1 = static_cast<AliMUONVCluster*>(nextInCh1()) ) ) {
993         iCluster1++;
994         
995         // try to add the current cluster fast
996         if (!TryOneClusterFast(extrapTrackParamAtCluster2, clusterCh1)) continue;
997         
998         // try to add the current cluster in addition to the one found in the previous chamber
999         chi2WithTwoClusters = TryTwoClustersFast(extrapTrackParamAtCluster2, clusterCh1, extrapTrackParamAtCluster1);
1000         
1001         // if good chi2 then consider to add the 2 clusters to the "trackCandidate"
1002         if (chi2WithTwoClusters < maxChi2WithTwoClusters) {
1003           foundSecondCluster = kTRUE;
1004           foundTwoClusters = kTRUE;
1005           
1006           // Printout for debuging
1007           if ((AliLog::GetDebugLevel("MUON","AliMUONVTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
1008             cout << "FollowLinearTrackInStation: found one cluster in chamber(1..): " << ch1+1
1009                  << " (Chi2 = " << chi2WithTwoClusters << ")" << endl;
1010             clusterCh1->Print();
1011           }
1012           
1013           if (GetRecoParam()->TrackAllTracks()) {
1014             // copy trackCandidate into a new track put at the end of fRecTracksPtr and add the new clusters
1015             newTrack = new ((*fRecTracksPtr)[fRecTracksPtr->GetLast()+1]) AliMUONTrack(trackCandidate);
1016             extrapTrackParamAtCluster1.SetRemovable(kTRUE);
1017             newTrack->AddTrackParamAtCluster(extrapTrackParamAtCluster1,*clusterCh1);
1018             extrapTrackParamAtCluster2.SetRemovable(kTRUE);
1019             newTrack->AddTrackParamAtCluster(extrapTrackParamAtCluster2,*clusterCh2);
1020             newTrack->SetGlobalChi2(newTrack->GetGlobalChi2()+chi2WithTwoClusters);
1021             fNRecTracks++;
1022             
1023             // Tag clusterCh1 as used
1024             clusterCh1Used[iCluster1] = kTRUE;
1025             
1026             // Printout for debuging
1027             if ((AliLog::GetDebugLevel("MUON","AliMUONVTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
1028               cout << "FollowLinearTrackInStation: added two clusters in station(1..): " << nextStation+1 << endl;
1029               if (AliLog::GetGlobalDebugLevel() >= 3) newTrack->RecursiveDump();
1030             }
1031             
1032           } else if (chi2WithTwoClusters < bestChi2WithTwoClusters) {
1033             // keep track of the best couple of clusters
1034             bestChi2WithTwoClusters = chi2WithTwoClusters;
1035             bestTrackParamAtCluster1 = extrapTrackParamAtCluster1;
1036             bestTrackParamAtCluster2 = extrapTrackParamAtCluster2;
1037           }
1038           
1039         }
1040         
1041       }
1042       
1043       // if no cluster found in chamber1 then consider to add clusterCh2 only
1044       if (!foundSecondCluster) {
1045         foundOneCluster = kTRUE;
1046         
1047         if (GetRecoParam()->TrackAllTracks()) {
1048           // copy trackCandidate into a new track put at the end of fRecTracksPtr and add the new cluster
1049           newTrack = new ((*fRecTracksPtr)[fRecTracksPtr->GetLast()+1]) AliMUONTrack(trackCandidate);
1050           if (GetRecoParam()->RequestStation(nextStation))
1051             extrapTrackParamAtCluster2.SetRemovable(kFALSE);
1052           else extrapTrackParamAtCluster2.SetRemovable(kTRUE);
1053           newTrack->AddTrackParamAtCluster(extrapTrackParamAtCluster2,*clusterCh2);
1054           newTrack->SetGlobalChi2(newTrack->GetGlobalChi2()+chi2WithOneCluster);
1055           fNRecTracks++;
1056           
1057           // Printout for debuging
1058           if ((AliLog::GetDebugLevel("MUON","AliMUONVTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
1059             cout << "FollowLinearTrackInStation: added one cluster in chamber(1..): " << ch2+1 << endl;
1060             if (AliLog::GetGlobalDebugLevel() >= 3) newTrack->RecursiveDump();
1061           }
1062           
1063         } else if (!foundTwoClusters && chi2WithOneCluster < bestChi2WithOneCluster) {
1064           // keep track of the best cluster except if a couple of clusters has already been found
1065           bestChi2WithOneCluster = chi2WithOneCluster;
1066           bestTrackParamAtCluster1 = extrapTrackParamAtCluster2;
1067         }
1068         
1069       }
1070       
1071     }
1072     
1073   }
1074   
1075   // look for candidates in chamber 1 not already attached to a track
1076   // if we want to keep all possible tracks or if no good couple of clusters has been found
1077   if (GetRecoParam()->TrackAllTracks() || !foundTwoClusters) {
1078     
1079     // Printout for debuging
1080     if ((AliLog::GetDebugLevel("MUON","AliMUONVTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
1081       cout << "FollowLinearTrackInStation: look for single cluster in chamber(1..): " << ch1+1 << endl;
1082     }
1083     
1084     //Extrapolate trackCandidate to chamber "ch2"
1085     AliMUONTrackExtrap::LinearExtrapToZCov(&trackParam, AliMUONConstants::DefaultChamberZ(ch2));
1086     
1087     // add MCS effect for next step
1088     AliMUONTrackExtrap::AddMCSEffect(&trackParam,AliMUONConstants::ChamberThicknessInX0(ch2),-1.);
1089     
1090     // reset cluster iterator of chamber 1
1091     nextInCh1.Reset();
1092     iCluster1 = -1;
1093     
1094     // look for second candidates in chamber 1
1095     while ( ( clusterCh1 = static_cast<AliMUONVCluster*>(nextInCh1()) ) ) {
1096       iCluster1++;
1097       
1098       if (clusterCh1Used[iCluster1]) continue; // Skip clusters already used
1099       
1100       // try to add the current cluster fast
1101       if (!TryOneClusterFast(trackParam, clusterCh1)) continue;
1102       
1103       // try to add the current cluster accuratly
1104       extrapTrackParamAtCluster1 = trackParam;
1105       AliMUONTrackExtrap::LinearExtrapToZCov(&extrapTrackParamAtCluster1, clusterCh1->GetZ());
1106       chi2WithOneCluster = TryOneCluster(extrapTrackParamAtCluster1, clusterCh1, extrapTrackParamAtCluster1);
1107       
1108       // if good chi2 then consider to add clusterCh1
1109       // We do not try to attach a cluster in the other chamber too since it has already been done above
1110       if (chi2WithOneCluster < maxChi2WithOneCluster) {
1111         foundOneCluster = kTRUE;
1112         
1113         // Printout for debuging
1114         if ((AliLog::GetDebugLevel("MUON","AliMUONVTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
1115           cout << "FollowLinearTrackInStation: found one cluster in chamber(1..): " << ch1+1
1116                << " (Chi2 = " << chi2WithOneCluster << ")" << endl;
1117           clusterCh1->Print();
1118         }
1119         
1120         if (GetRecoParam()->TrackAllTracks()) {
1121           // copy trackCandidate into a new track put at the end of fRecTracksPtr and add the new cluster
1122           newTrack = new ((*fRecTracksPtr)[fRecTracksPtr->GetLast()+1]) AliMUONTrack(trackCandidate);
1123           if (GetRecoParam()->RequestStation(nextStation))
1124             extrapTrackParamAtCluster1.SetRemovable(kFALSE);
1125           else extrapTrackParamAtCluster1.SetRemovable(kTRUE);
1126           newTrack->AddTrackParamAtCluster(extrapTrackParamAtCluster1,*clusterCh1);
1127           newTrack->SetGlobalChi2(newTrack->GetGlobalChi2()+chi2WithOneCluster);
1128           fNRecTracks++;
1129           
1130           // Printout for debuging
1131           if ((AliLog::GetDebugLevel("MUON","AliMUONVTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
1132             cout << "FollowLinearTrackInStation: added one cluster in chamber(1..): " << ch1+1 << endl;
1133             if (AliLog::GetGlobalDebugLevel() >= 3) newTrack->RecursiveDump();
1134           }
1135           
1136         } else if (chi2WithOneCluster < bestChi2WithOneCluster) {
1137           // keep track of the best cluster except if a couple of clusters has already been found
1138           bestChi2WithOneCluster = chi2WithOneCluster;
1139           bestTrackParamAtCluster1 = extrapTrackParamAtCluster1;
1140         }
1141         
1142       }
1143       
1144     }
1145     
1146   }
1147   
1148   // fill out the best track if required else clean up the fRecTracksPtr array
1149   if (!GetRecoParam()->TrackAllTracks()) {
1150     if (foundTwoClusters) {
1151       bestTrackParamAtCluster1.SetRemovable(kTRUE);
1152       trackCandidate.AddTrackParamAtCluster(bestTrackParamAtCluster1,*(bestTrackParamAtCluster1.GetClusterPtr()));
1153       bestTrackParamAtCluster2.SetRemovable(kTRUE);
1154       trackCandidate.AddTrackParamAtCluster(bestTrackParamAtCluster2,*(bestTrackParamAtCluster2.GetClusterPtr()));
1155       trackCandidate.SetGlobalChi2(trackCandidate.GetGlobalChi2()+bestChi2WithTwoClusters);
1156       
1157       // Printout for debuging
1158       if ((AliLog::GetDebugLevel("MUON","AliMUONVTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
1159         cout << "FollowLinearTrackInStation: added the two best clusters in station(1..): " << nextStation+1 << endl;
1160         if (AliLog::GetGlobalDebugLevel() >= 3) newTrack->RecursiveDump();
1161       }
1162       
1163     } else if (foundOneCluster) {
1164       if (GetRecoParam()->RequestStation(nextStation))
1165         bestTrackParamAtCluster1.SetRemovable(kFALSE);
1166       else bestTrackParamAtCluster1.SetRemovable(kTRUE);
1167       trackCandidate.AddTrackParamAtCluster(bestTrackParamAtCluster1,*(bestTrackParamAtCluster1.GetClusterPtr()));
1168       trackCandidate.SetGlobalChi2(trackCandidate.GetGlobalChi2()+bestChi2WithOneCluster);
1169       
1170       // Printout for debuging
1171       if ((AliLog::GetDebugLevel("MUON","AliMUONVTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
1172         cout << "FollowLinearTrackInStation: added the best cluster in chamber(1..): " << bestTrackParamAtCluster1.GetClusterPtr()->GetChamberId()+1 << endl;
1173         if (AliLog::GetGlobalDebugLevel() >= 3) newTrack->RecursiveDump();
1174       }
1175       
1176     } else {
1177       delete [] clusterCh1Used;
1178       return kFALSE;
1179     }
1180     
1181   } else if (foundOneCluster || foundTwoClusters) {
1182     
1183     // remove obsolete track
1184     fRecTracksPtr->Remove(&trackCandidate);
1185     fNRecTracks--;
1186     
1187   } else {
1188     delete [] clusterCh1Used;  
1189     return kFALSE;
1190   }
1191   
1192   delete [] clusterCh1Used;
1193   return kTRUE;
1194   
1195 }
1196
1197 //__________________________________________________________________________
1198 void AliMUONVTrackReconstructor::ImproveTracks()
1199 {
1200   /// Improve tracks by removing clusters with local chi2 highter than the defined cut
1201   /// Recompute track parameters and covariances at the remaining clusters
1202   AliDebug(1,"Enter ImproveTracks");
1203   
1204   AliMUONTrack *track, *nextTrack;
1205   
1206   track = (AliMUONTrack*) fRecTracksPtr->First();
1207   while (track) {
1208     
1209     // prepare next track in case the actual track is suppressed
1210     nextTrack = (AliMUONTrack*) fRecTracksPtr->After(track);
1211     
1212     ImproveTrack(*track);
1213     
1214     // remove track if improvement failed
1215     if (!track->IsImproved()) {
1216       fRecTracksPtr->Remove(track);
1217       fNRecTracks--;
1218     }
1219     
1220     track = nextTrack;
1221   }
1222   
1223   // compress the array in case of some tracks have been removed
1224   fRecTracksPtr->Compress();
1225   
1226 }
1227
1228 //__________________________________________________________________________
1229 void AliMUONVTrackReconstructor::Finalize()
1230 {
1231   /// Recompute track parameters and covariances at each attached cluster
1232   /// Set the label pointing to the corresponding MC track
1233   /// Remove the track if finalization failed
1234   
1235   AliMUONTrack *track, *nextTrack;
1236   Bool_t trackRemoved = kFALSE;
1237   
1238   track = (AliMUONTrack*) fRecTracksPtr->First();
1239   while (track) {
1240     
1241     nextTrack = (AliMUONTrack*) fRecTracksPtr->After(track);
1242     
1243     if (FinalizeTrack(*track)) track->FindMCLabel();
1244     else {
1245       fRecTracksPtr->Remove(track);
1246       fNRecTracks--;
1247       trackRemoved = kTRUE;
1248     }
1249     
1250     track = nextTrack;
1251     
1252   }
1253   
1254   // compress array of tracks if needed
1255   if (trackRemoved) fRecTracksPtr->Compress();
1256   
1257 }
1258
1259 //__________________________________________________________________________
1260 void AliMUONVTrackReconstructor::ValidateTracksWithTrigger(AliMUONVTrackStore& trackStore,
1261                                                            const AliMUONVTriggerTrackStore& triggerTrackStore,
1262                                                            const AliMUONVTriggerStore& triggerStore,
1263                                                            const AliMUONTrackHitPattern& trackHitPattern)
1264 {
1265   /// Try to match track from tracking system with trigger track
1266   AliCodeTimerAuto("",0);
1267
1268   trackHitPattern.ExecuteValidation(trackStore, triggerTrackStore, triggerStore);
1269 }
1270
1271
1272 //__________________________________________________________________________
1273 void AliMUONVTrackReconstructor::EventReconstructTrigger(const AliMUONTriggerCircuit& circuit,
1274                                                          const AliMUONVTriggerStore& triggerStore,
1275                                                          AliMUONVTriggerTrackStore& triggerTrackStore)
1276 {
1277   /// Fill trigger track store from local trigger
1278   AliDebug(1, "");
1279   AliCodeTimerAuto("",0);
1280
1281   AliMUONGlobalTrigger* globalTrigger = triggerStore.Global();
1282   
1283   UChar_t gloTrigPat = 0;
1284
1285   if (globalTrigger)
1286   {
1287     gloTrigPat = globalTrigger->GetGlobalResponse();
1288   }
1289   
1290   AliMUONTriggerTrack triggerTrack;
1291   
1292   TIter next(triggerStore.CreateIterator());
1293   AliMUONLocalTrigger* locTrg(0x0);
1294   
1295   while ( ( locTrg = static_cast<AliMUONLocalTrigger*>(next()) ) )
1296   {
1297     if ( locTrg->IsTrigX() && locTrg->IsTrigY() ) 
1298     { // make Trigger Track if trigger in X and Y
1299       
1300       TriggerToTrack(circuit, *locTrg, triggerTrack, gloTrigPat);
1301
1302       triggerTrackStore.Add(triggerTrack);
1303     } // board is fired 
1304   } // end of loop on Local Trigger
1305 }
1306
1307 //__________________________________________________________________________
1308 void AliMUONVTrackReconstructor::TriggerToTrack(const AliMUONTriggerCircuit& circuit,
1309                                                 const AliMUONLocalTrigger& locTrg,
1310                                                 AliMUONTriggerTrack& triggerTrack,
1311                                                 UChar_t globalTriggerPattern)
1312 {
1313   /// To make the trigger tracks from Local Trigger
1314   const Double_t kTrigNonBendReso = AliMUONConstants::TriggerNonBendingReso();
1315   const Double_t kTrigBendReso = AliMUONConstants::TriggerBendingReso();
1316   const Double_t kSqrt12 = TMath::Sqrt(12.);
1317   
1318   TMatrixD trigCov(3,3);
1319
1320   Int_t localBoardId = locTrg.LoCircuit();
1321       
1322   Float_t y11 = circuit.GetY11Pos(localBoardId, locTrg.LoStripX()); 
1323   Float_t z11 = circuit.GetZ11Pos(localBoardId, locTrg.LoStripX());
1324   // need first to convert deviation to [0-30] 
1325   // (see AliMUONLocalTriggerBoard::LocalTrigger)
1326   Int_t deviation = locTrg.GetDeviation(); 
1327   Int_t stripX21 = locTrg.LoStripX()+deviation+1;
1328   Float_t y21 = circuit.GetY21Pos(localBoardId, stripX21);       
1329   Float_t z21 = circuit.GetZ21Pos(localBoardId, stripX21);
1330   Float_t x11 = circuit.GetX11Pos(localBoardId, locTrg.LoStripY());
1331       
1332   AliDebug(1, Form(" MakeTriggerTrack %3d %2d %2d %2d (%f %f %f) (%f %f)\n",locTrg.LoCircuit(),
1333                    locTrg.LoStripX(),locTrg.LoStripX()+deviation+1,locTrg.LoStripY(),x11, y11, z11, y21, z21));
1334       
1335   Double_t deltaZ = z11 - z21;
1336       
1337   Float_t slopeX = x11/z11;
1338   Float_t slopeY = (y11-y21) / deltaZ;
1339       
1340   Float_t sigmaX = circuit.GetX11Width(localBoardId, locTrg.LoStripY()) / kSqrt12;
1341   Float_t sigmaY = circuit.GetY11Width(localBoardId, locTrg.LoStripX()) / kSqrt12;
1342   Float_t sigmaY21 = circuit.GetY21Width(localBoardId, locTrg.LoStripX()) / kSqrt12;
1343       
1344   trigCov.Zero();
1345   trigCov(0,0) = kTrigNonBendReso * kTrigNonBendReso + sigmaX * sigmaX;
1346   trigCov(1,1) = kTrigBendReso * kTrigBendReso + sigmaY * sigmaY;
1347   trigCov(2,2) = 
1348     (2. * kTrigBendReso * kTrigBendReso + sigmaY * sigmaY + sigmaY21 * sigmaY21 ) / deltaZ / deltaZ;
1349     trigCov(1,2) = trigCov(2,1) = trigCov(1,1) / deltaZ;
1350       
1351   triggerTrack.SetX11(x11);
1352   triggerTrack.SetY11(y11);
1353   triggerTrack.SetZ11(z11);
1354   triggerTrack.SetZ21(z21);
1355   triggerTrack.SetSlopeX(slopeX);
1356   triggerTrack.SetSlopeY(slopeY);
1357   triggerTrack.SetGTPattern(globalTriggerPattern);
1358   triggerTrack.SetLoTrgNum(localBoardId);
1359   triggerTrack.SetCovariances(trigCov);
1360   triggerTrack.SetUniqueID(locTrg.GetUniqueID());
1361 }