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