]> git.uio.no Git - u/mrichter/AliRoot.git/blob - MUON/AliMUONTrackReconstructor.cxx
AliMUONTrackerIO:
[u/mrichter/AliRoot.git] / MUON / AliMUONTrackReconstructor.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 AliMUONTrackReconstructor
20 /// MUON track reconstructor using the original method
21 ///
22 /// This class contains as data:
23 /// - the parameters for the track reconstruction
24 ///
25 /// It contains as methods, among others:
26 /// - MakeTracks to build the tracks
27 //-----------------------------------------------------------------------------
28
29 #include "AliMUONTrackReconstructor.h"
30
31 #include "AliMUONConstants.h"
32 #include "AliMUONVCluster.h"
33 #include "AliMUONVClusterServer.h"
34 #include "AliMUONVClusterStore.h"
35 #include "AliMUONTrack.h"
36 #include "AliMUONTrackParam.h"
37 #include "AliMUONTrackExtrap.h"
38
39 #include "AliMpArea.h"
40
41 #include "AliLog.h"
42
43 #include <TMinuit.h>
44 #include <Riostream.h>
45 #include <TMath.h>
46 #include <TMatrixD.h>
47
48 // Functions to be minimized with Minuit
49 void TrackChi2(Int_t &nParam, Double_t *gradient, Double_t &chi2, Double_t *param, Int_t flag);
50
51 /// \cond CLASSIMP
52 ClassImp(AliMUONTrackReconstructor) // Class implementation in ROOT context
53 /// \endcond
54
55   //__________________________________________________________________________
56 AliMUONTrackReconstructor::AliMUONTrackReconstructor(AliMUONVClusterServer& clusterServer)
57   : AliMUONVTrackReconstructor(clusterServer)
58 {
59   /// Constructor
60 }
61
62   //__________________________________________________________________________
63 AliMUONTrackReconstructor::~AliMUONTrackReconstructor()
64 {
65 /// Destructor
66
67
68   //__________________________________________________________________________
69 void AliMUONTrackReconstructor::MakeTrackCandidates(AliMUONVClusterStore& clusterStore)
70 {
71   /// To make track candidates (assuming linear propagation if the flag fgkMakeTrackCandidatesFast is set to kTRUE):
72   /// Start with segments station(1..) 4 or 5 then follow track in station 5 or 4.
73   /// Good candidates are made of at least three clusters.
74   /// Keep only best candidates or all of them according to the flag fgkTrackAllTracks.
75   
76   TClonesArray *segments;
77   AliMUONTrack *track;
78   Int_t iCandidate = 0;
79   Bool_t clusterFound;
80
81   AliDebug(1,"Enter MakeTrackCandidates");
82
83   // Unless we're doing combined tracking, we'll clusterize all stations at once
84   Int_t firstChamber(0);
85   Int_t lastChamber(9);
86   
87   if (AliMUONReconstructor::GetRecoParam()->CombineClusterTrackReco()) {
88     // ... Here's the exception : ask the clustering to reconstruct
89     // clusters *only* in station 4 and 5 for combined tracking
90     firstChamber = 6;
91   }
92
93   for (Int_t i = firstChamber; i <= lastChamber; ++i ) 
94   {
95     fClusterServer.Clusterize(i, clusterStore, AliMpArea());
96   }
97   
98   // Loop over stations(1..) 5 and 4 and make track candidates
99   for (Int_t istat=4; istat>=3; istat--) {
100     
101     // Make segments in the station
102     segments = MakeSegmentsInStation(clusterStore,istat);
103     
104     // Loop over segments
105     for (Int_t iseg=0; iseg<segments->GetEntriesFast(); iseg++) 
106     {
107       AliDebug(1,Form("Making primary candidate(1..) %d",++iCandidate));
108       
109       // Transform segments to tracks and put them at the end of fRecTracksPtr
110       track = new ((*fRecTracksPtr)[fRecTracksPtr->GetLast()+1]) AliMUONTrack((AliMUONObjectPair*)((*segments)[iseg]));
111       fNRecTracks++;
112       
113       // Printout for debuging
114       if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 2) || (AliLog::GetGlobalDebugLevel() >= 2)) {
115         cout<<endl<<"Track parameter covariances at first cluster:"<<endl;
116         ((AliMUONTrackParam*) track->GetTrackParamAtCluster()->First())->GetCovariances().Print();
117       }
118       
119       // Look for compatible cluster(s) in the other station
120       if (AliMUONReconstructor::GetRecoParam()->MakeTrackCandidatesFast())
121         clusterFound = FollowLinearTrackInStation(*track, clusterStore, 7-istat);
122       else clusterFound = FollowTrackInStation(*track, clusterStore, 7-istat);
123       
124       // Remove track if no cluster found
125       if (!clusterFound) {
126         fRecTracksPtr->Remove(track);
127         fNRecTracks--;
128       }
129       
130     }
131     
132     // delete the array of segments
133     delete segments;
134   }
135   
136   fRecTracksPtr->Compress(); // this is essential before checking tracks
137   
138   // Keep all different tracks or only the best ones as required
139   if (AliMUONReconstructor::GetRecoParam()->TrackAllTracks()) RemoveIdenticalTracks();
140   else RemoveDoubleTracks();
141   
142   AliDebug(1,Form("Number of good candidates = %d",fNRecTracks));
143   
144 }
145
146   //__________________________________________________________________________
147 void AliMUONTrackReconstructor::FollowTracks(AliMUONVClusterStore& clusterStore)
148 {
149   /// Follow tracks in stations(1..) 3, 2 and 1
150   AliDebug(1,"Enter FollowTracks");
151   
152   AliMUONTrack *track, *nextTrack;
153   AliMUONTrackParam *trackParam, *nextTrackParam;
154   Int_t currentNRecTracks;
155   Bool_t clusterFound;
156   
157   Double_t sigmaCut2 = AliMUONReconstructor::GetRecoParam()->GetSigmaCutForTracking() *
158                        AliMUONReconstructor::GetRecoParam()->GetSigmaCutForTracking();
159   
160   for (Int_t station = 2; station >= 0; station--) {
161     
162     // Save the actual number of reconstructed track in case of
163     // tracks are added or suppressed during the tracking procedure
164     // !! Do not compress fRecTracksPtr until the end of the loop over tracks !!
165     currentNRecTracks = fNRecTracks;
166     
167     for (Int_t iRecTrack = 0; iRecTrack <currentNRecTracks; iRecTrack++) {
168       AliDebug(1,Form("FollowTracks: track candidate(1..) %d", iRecTrack+1));
169       
170       track = (AliMUONTrack*) fRecTracksPtr->UncheckedAt(iRecTrack);
171       
172       // Fit the track:
173       // Do not take into account the multiple scattering to speed up the fit
174       // Calculate the track parameter covariance matrix
175       // If "station" is station(1..) 3 then use the vertex to better constrain the fit
176       if (station==2) Fit(*track, kFALSE, kTRUE, kTRUE);
177       else Fit(*track, kFALSE, kFALSE, kTRUE);
178       
179       // Remove the track if the normalized chi2 is too high
180       if (track->GetNormalizedChi2() > sigmaCut2) {
181         fRecTracksPtr->Remove(track);
182         fNRecTracks--;
183         continue;
184       }
185       
186       // save parameters from fit into smoothed parameters to complete track afterward
187       if (AliMUONReconstructor::GetRecoParam()->ComplementTracks()) {
188         
189         if (station==2) { // save track parameters on stations 4 and 5
190           
191           // extrapolate track parameters and covariances at each cluster
192           track->UpdateCovTrackParamAtCluster();
193           
194           // save them
195           trackParam = (AliMUONTrackParam*) track->GetTrackParamAtCluster()->First();
196           while (trackParam) {
197             trackParam->SetSmoothParameters(trackParam->GetParameters());
198             trackParam->SetSmoothCovariances(trackParam->GetCovariances());
199             trackParam = (AliMUONTrackParam*) track->GetTrackParamAtCluster()->After(trackParam);
200           }
201           
202         } else { // or save track parameters on last station only
203           
204           // save parameters from fit
205           trackParam = (AliMUONTrackParam*) track->GetTrackParamAtCluster()->First();
206           trackParam->SetSmoothParameters(trackParam->GetParameters());
207           trackParam->SetSmoothCovariances(trackParam->GetCovariances());
208           
209           // save parameters extrapolated to the second chamber of the same station if it has been hit
210           nextTrackParam = (AliMUONTrackParam*) track->GetTrackParamAtCluster()->After(trackParam);
211           if (nextTrackParam->GetClusterPtr()->GetChamberId() < 2*(station+2)) {
212             
213             // reset parameters and covariances
214             nextTrackParam->SetParameters(trackParam->GetParameters());
215             nextTrackParam->SetZ(trackParam->GetZ());
216             nextTrackParam->SetCovariances(trackParam->GetCovariances());
217             
218             // extrapolate them to the z of the corresponding cluster
219             AliMUONTrackExtrap::ExtrapToZCov(nextTrackParam, nextTrackParam->GetClusterPtr()->GetZ());
220             
221             // save them
222             nextTrackParam->SetSmoothParameters(nextTrackParam->GetParameters());
223             nextTrackParam->SetSmoothCovariances(nextTrackParam->GetCovariances());
224             
225           }
226           
227         }
228         
229       }
230       
231       // Printout for debuging
232       if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 2) || (AliLog::GetGlobalDebugLevel() >= 2)) {
233         cout<<endl<<"Track parameter covariances at first cluster:"<<endl;
234         ((AliMUONTrackParam*) track->GetTrackParamAtCluster()->First())->GetCovariances().Print();
235       }
236       
237       // Look for compatible cluster(s) in station(0..) "station"
238       clusterFound = FollowTrackInStation(*track, clusterStore, station);
239       
240       // Try to recover track if required
241       if (!clusterFound && AliMUONReconstructor::GetRecoParam()->RecoverTracks())
242         clusterFound = RecoverTrack(*track, clusterStore, station);
243       
244       // remove track if no cluster found
245       if (!clusterFound) {
246         fRecTracksPtr->Remove(track);
247         fNRecTracks--;
248       }
249       
250     }
251     
252     // Compress fRecTracksPtr for the next step
253     fRecTracksPtr->Compress();
254     
255     // Keep only the best tracks if required
256     if (!AliMUONReconstructor::GetRecoParam()->TrackAllTracks()) RemoveDoubleTracks();
257     
258   }
259   
260   // Last fit of track candidates with all stations
261   // Take into account the multiple scattering and remove bad tracks
262   Int_t trackIndex = -1;
263   track = (AliMUONTrack*) fRecTracksPtr->First();
264   while (track) {
265     
266     trackIndex++;
267     nextTrack = (AliMUONTrack*) fRecTracksPtr->After(track); // prepare next track
268     
269     Fit(*track, kTRUE, kFALSE, kTRUE);
270     
271     // Printout for debuging
272     if (AliLog::GetGlobalDebugLevel() >= 3) {
273       cout << "FollowTracks: track candidate(0..) " << trackIndex << " after final fit" << endl;
274       track->RecursiveDump();
275     } 
276     
277     // Remove the track if the normalized chi2 is too high
278     if (track->GetNormalizedChi2() > sigmaCut2) {
279       fRecTracksPtr->Remove(track);
280       fNRecTracks--;
281       track = nextTrack;
282       continue;
283     }
284     
285     // save parameters from fit into smoothed parameters to complete track afterward
286     if (AliMUONReconstructor::GetRecoParam()->ComplementTracks()) {
287       
288       // save parameters from fit
289       trackParam = (AliMUONTrackParam*) track->GetTrackParamAtCluster()->First();
290       trackParam->SetSmoothParameters(trackParam->GetParameters());
291       trackParam->SetSmoothCovariances(trackParam->GetCovariances());
292       
293       // save parameters extrapolated to the second chamber of the same station if it has been hit
294       nextTrackParam = (AliMUONTrackParam*) track->GetTrackParamAtCluster()->After(trackParam);
295       if (nextTrackParam->GetClusterPtr()->GetChamberId() < 2) {
296         
297         // reset parameters and covariances
298         nextTrackParam->SetParameters(trackParam->GetParameters());
299         nextTrackParam->SetZ(trackParam->GetZ());
300         nextTrackParam->SetCovariances(trackParam->GetCovariances());
301         
302         // extrapolate them to the z of the corresponding cluster
303         AliMUONTrackExtrap::ExtrapToZCov(nextTrackParam, nextTrackParam->GetClusterPtr()->GetZ());
304         
305         // save them
306         nextTrackParam->SetSmoothParameters(nextTrackParam->GetParameters());
307         nextTrackParam->SetSmoothCovariances(nextTrackParam->GetCovariances());
308         
309       }
310       
311     }
312     
313     track = nextTrack;
314     
315   }
316   
317   fRecTracksPtr->Compress();
318   
319 }
320
321   //__________________________________________________________________________
322 Bool_t AliMUONTrackReconstructor::FollowTrackInStation(AliMUONTrack &trackCandidate, AliMUONVClusterStore& clusterStore, Int_t nextStation)
323 {
324   /// Follow trackCandidate in station(0..) nextStation and search for compatible cluster(s)
325   /// Keep all possibilities or only the best one(s) according to the flag fgkTrackAllTracks:
326   /// kTRUE:  duplicate "trackCandidate" if there are several possibilities and add the new tracks at the end of
327   ///         fRecTracksPtr to avoid conficts with other track candidates at this current stage of the tracking procedure.
328   ///         Remove the obsolete "trackCandidate" at the end.
329   /// kFALSE: add only the best cluster(s) to the "trackCandidate". Try to add a couple of clusters in priority.
330   AliDebug(1,Form("Enter FollowTrackInStation(1..) %d", nextStation+1));
331   
332   // Order the chamber according to the propagation direction (tracking starts with chamber 2):
333   // - nextStation == station(1...) 5 => forward propagation
334   // - nextStation < station(1...) 5 => backward propagation
335   Int_t ch1, ch2;
336   if (nextStation==4) {
337     ch1 = 2*nextStation+1;
338     ch2 = 2*nextStation;
339   } else {
340     ch1 = 2*nextStation;
341     ch2 = 2*nextStation+1;
342   }
343   
344   Double_t chi2WithOneCluster = 1.e10;
345   Double_t chi2WithTwoClusters = 1.e10;
346   Double_t maxChi2WithOneCluster = 2. * AliMUONReconstructor::GetRecoParam()->GetSigmaCutForTracking() *
347                                         AliMUONReconstructor::GetRecoParam()->GetSigmaCutForTracking(); // 2 because 2 quantities in chi2
348   Double_t maxChi2WithTwoClusters = 4. * AliMUONReconstructor::GetRecoParam()->GetSigmaCutForTracking() *
349                                          AliMUONReconstructor::GetRecoParam()->GetSigmaCutForTracking(); // 4 because 4 quantities in chi2
350   Double_t bestChi2WithOneCluster = maxChi2WithOneCluster;
351   Double_t bestChi2WithTwoClusters = maxChi2WithTwoClusters;
352   Bool_t foundOneCluster = kFALSE;
353   Bool_t foundTwoClusters = kFALSE;
354   AliMUONTrack *newTrack = 0x0;
355   AliMUONVCluster *clusterCh1, *clusterCh2;
356   AliMUONTrackParam extrapTrackParam;
357   AliMUONTrackParam extrapTrackParamAtCluster1;
358   AliMUONTrackParam extrapTrackParamAtCluster2;
359   AliMUONTrackParam bestTrackParamAtCluster1;
360   AliMUONTrackParam bestTrackParamAtCluster2;
361   
362   Int_t nClusters = clusterStore.GetSize();
363   Bool_t *clusterCh1Used = new Bool_t[nClusters];
364   for (Int_t i = 0; i < nClusters; i++) clusterCh1Used[i] = kFALSE;
365   Int_t iCluster1;
366   
367   // Get track parameters
368   AliMUONTrackParam extrapTrackParamAtCh(*(AliMUONTrackParam*)trackCandidate.GetTrackParamAtCluster()->First());
369   
370   // Add MCS effect
371   AliMUONTrackExtrap::AddMCSEffect(&extrapTrackParamAtCh,AliMUONConstants::ChamberThicknessInX0(),1.);
372   
373   // Add MCS in the missing chamber if any (only 1 chamber can be missing according to tracking criteria)
374   if (ch1 < ch2 && extrapTrackParamAtCh.GetClusterPtr()->GetChamberId() > ch2 + 1) {
375     // extrapolation to the missing chamber
376     AliMUONTrackExtrap::ExtrapToZCov(&extrapTrackParamAtCh, AliMUONConstants::DefaultChamberZ(ch2 + 1));
377     // add MCS effect
378     AliMUONTrackExtrap::AddMCSEffect(&extrapTrackParamAtCh,AliMUONConstants::ChamberThicknessInX0(),1.);
379   }
380   
381   //Extrapolate trackCandidate to chamber "ch2"
382   AliMUONTrackExtrap::ExtrapToZCov(&extrapTrackParamAtCh, AliMUONConstants::DefaultChamberZ(ch2));
383   
384   // Printout for debuging
385   if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 2) || (AliLog::GetGlobalDebugLevel() >= 2)) {
386     cout<<endl<<"Track parameter covariances at first cluster extrapolated to z = "<<AliMUONConstants::DefaultChamberZ(ch2)<<":"<<endl;
387     extrapTrackParamAtCh.GetCovariances().Print();
388   }
389   
390   // Printout for debuging
391   if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
392     cout << "FollowTrackInStation: look for clusters in chamber(1..): " << ch2+1 << endl;
393   }
394   
395   // Ask the clustering to reconstruct new clusters around the track position in the current station
396   // except for station 4 and 5 that are already entirely clusterized
397   if (AliMUONReconstructor::GetRecoParam()->CombineClusterTrackReco()) {
398     if (nextStation < 3) AskForNewClustersInStation(extrapTrackParamAtCh, clusterStore, nextStation);
399   }
400   
401   // Create iterators to loop over clusters in both chambers
402   TIter nextInCh1(clusterStore.CreateChamberIterator(ch1,ch1));
403   TIter nextInCh2(clusterStore.CreateChamberIterator(ch2,ch2));
404   
405   // look for candidates in chamber 2
406   while ( ( clusterCh2 = static_cast<AliMUONVCluster*>(nextInCh2()) ) ) {
407     
408     // try to add the current cluster fast
409     if (!TryOneClusterFast(extrapTrackParamAtCh, clusterCh2)) continue;
410     
411     // try to add the current cluster accuratly
412     chi2WithOneCluster = TryOneCluster(extrapTrackParamAtCh, clusterCh2, extrapTrackParamAtCluster2);
413     
414     // if good chi2 then try to attach a cluster in the other chamber too
415     if (chi2WithOneCluster < maxChi2WithOneCluster) {
416       Bool_t foundSecondCluster = kFALSE;
417       
418       // Printout for debuging
419       if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
420         cout << "FollowTrackInStation: found one cluster in chamber(1..): " << ch2+1
421              << " (Chi2 = " << chi2WithOneCluster << ")" << endl;
422         cout << "                      look for second clusters in chamber(1..): " << ch1+1 << " ..." << endl;
423       }
424       
425       // add MCS effect for next step
426       AliMUONTrackExtrap::AddMCSEffect(&extrapTrackParamAtCluster2,AliMUONConstants::ChamberThicknessInX0(),1.);
427       
428       // copy new track parameters for next step
429       extrapTrackParam = extrapTrackParamAtCluster2;
430       
431       //Extrapolate track parameters to chamber "ch1"
432       AliMUONTrackExtrap::ExtrapToZ(&extrapTrackParam, AliMUONConstants::DefaultChamberZ(ch1));
433       
434       // reset cluster iterator of chamber 1
435       nextInCh1.Reset();
436       iCluster1 = -1;
437       
438       // look for second candidates in chamber 1
439       while ( ( clusterCh1 = static_cast<AliMUONVCluster*>(nextInCh1()) ) ) {
440         iCluster1++;
441         
442         // try to add the current cluster fast
443         if (!TryOneClusterFast(extrapTrackParam, clusterCh1)) continue;
444         
445         // try to add the current cluster accuratly
446         chi2WithTwoClusters = TryTwoClusters(extrapTrackParamAtCluster2, clusterCh1, extrapTrackParamAtCluster1);
447         
448         // if good chi2 then create a new track by adding the 2 clusters to the "trackCandidate"
449         if (chi2WithTwoClusters < maxChi2WithTwoClusters) {
450           foundSecondCluster = kTRUE;
451           foundTwoClusters = kTRUE;
452           
453           // Printout for debuging
454           if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
455             cout << "FollowTrackInStation: found second cluster in chamber(1..): " << ch1+1
456                  << " (Global Chi2 = " << chi2WithTwoClusters << ")" << endl;
457           }
458           
459           if (AliMUONReconstructor::GetRecoParam()->TrackAllTracks()) {
460             // copy trackCandidate into a new track put at the end of fRecTracksPtr and add the new clusters
461             newTrack = new ((*fRecTracksPtr)[fRecTracksPtr->GetLast()+1]) AliMUONTrack(trackCandidate);
462             UpdateTrack(*newTrack,extrapTrackParamAtCluster1,extrapTrackParamAtCluster2);
463             fNRecTracks++;
464             
465             // Tag clusterCh1 as used
466             clusterCh1Used[iCluster1] = kTRUE;
467             
468             // Printout for debuging
469             if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
470               cout << "FollowTrackInStation: added two clusters in station(1..): " << nextStation+1 << endl;
471               if (AliLog::GetGlobalDebugLevel() >= 3) newTrack->RecursiveDump();
472             }
473             
474           } else if (chi2WithTwoClusters < bestChi2WithTwoClusters) {
475             // keep track of the best couple of clusters
476             bestChi2WithTwoClusters = chi2WithTwoClusters;
477             bestTrackParamAtCluster1 = extrapTrackParamAtCluster1;
478             bestTrackParamAtCluster2 = extrapTrackParamAtCluster2;
479           }
480           
481         }
482         
483       }
484       
485       // if no clusterCh1 found then consider to add clusterCh2 only
486       if (!foundSecondCluster) {
487         foundOneCluster = kTRUE;
488         
489         if (AliMUONReconstructor::GetRecoParam()->TrackAllTracks()) {
490           // copy trackCandidate into a new track put at the end of fRecTracksPtr and add the new cluster
491           newTrack = new ((*fRecTracksPtr)[fRecTracksPtr->GetLast()+1]) AliMUONTrack(trackCandidate);
492           UpdateTrack(*newTrack,extrapTrackParamAtCluster2);
493           fNRecTracks++;
494           
495           // Printout for debuging
496           if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
497             cout << "FollowTrackInStation: added one cluster in chamber(1..): " << ch2+1 << endl;
498             if (AliLog::GetGlobalDebugLevel() >= 3) newTrack->RecursiveDump();
499           }
500           
501         } else if (!foundTwoClusters && chi2WithOneCluster < bestChi2WithOneCluster) {
502           // keep track of the best single cluster except if a couple of clusters has already been found
503           bestChi2WithOneCluster = chi2WithOneCluster;
504           bestTrackParamAtCluster1 = extrapTrackParamAtCluster2;
505         }
506         
507       }
508       
509     }
510     
511   }
512   
513   // look for candidates in chamber 1 not already attached to a track
514   // if we want to keep all possible tracks or if no good couple of clusters has been found
515   if (AliMUONReconstructor::GetRecoParam()->TrackAllTracks() || !foundTwoClusters) {
516     
517     // Printout for debuging
518     if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
519       cout << "FollowTrackInStation: look for single clusters in chamber(1..): " << ch1+1 << endl;
520     }
521     
522     // add MCS effect for next step
523     AliMUONTrackExtrap::AddMCSEffect(&extrapTrackParamAtCh,AliMUONConstants::ChamberThicknessInX0(),1.);
524     
525     //Extrapolate trackCandidate to chamber "ch1"
526     AliMUONTrackExtrap::ExtrapToZCov(&extrapTrackParamAtCh, AliMUONConstants::DefaultChamberZ(ch1));
527     
528     // reset cluster iterator of chamber 1
529     nextInCh1.Reset();
530     iCluster1 = -1;
531     
532     // look for second candidates in chamber 1
533     while ( ( clusterCh1 = static_cast<AliMUONVCluster*>(nextInCh1()) ) ) {
534       iCluster1++;
535       
536       if (clusterCh1Used[iCluster1]) continue; // Skip cluster already used
537       
538       // try to add the current cluster fast
539       if (!TryOneClusterFast(extrapTrackParamAtCh, clusterCh1)) continue;
540       
541       // try to add the current cluster accuratly
542       chi2WithOneCluster = TryOneCluster(extrapTrackParamAtCh, clusterCh1, extrapTrackParamAtCluster1);
543     
544       // if good chi2 then consider to add clusterCh1
545       // We do not try to attach a cluster in the other chamber too since it has already been done above
546       if (chi2WithOneCluster < maxChi2WithOneCluster) {
547         foundOneCluster = kTRUE;
548           
549         // Printout for debuging
550         if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
551           cout << "FollowTrackInStation: found one cluster in chamber(1..): " << ch1+1
552                << " (Chi2 = " << chi2WithOneCluster << ")" << endl;
553         }
554         
555         if (AliMUONReconstructor::GetRecoParam()->TrackAllTracks()) {
556           // copy trackCandidate into a new track put at the end of fRecTracksPtr and add the new cluster
557           newTrack = new ((*fRecTracksPtr)[fRecTracksPtr->GetLast()+1]) AliMUONTrack(trackCandidate);
558           UpdateTrack(*newTrack,extrapTrackParamAtCluster1);
559           fNRecTracks++;
560           
561           // Printout for debuging
562           if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
563             cout << "FollowTrackInStation: added one cluster in chamber(1..): " << ch1+1 << endl;
564             if (AliLog::GetGlobalDebugLevel() >= 3) newTrack->RecursiveDump();
565           }
566           
567         } else if (chi2WithOneCluster < bestChi2WithOneCluster) {
568           // keep track of the best single cluster except if a couple of clusters has already been found
569           bestChi2WithOneCluster = chi2WithOneCluster;
570           bestTrackParamAtCluster1 = extrapTrackParamAtCluster1;
571         }
572         
573       }
574       
575     }
576     
577   }
578   
579   // fill out the best track if required else clean up the fRecTracksPtr array
580   if (!AliMUONReconstructor::GetRecoParam()->TrackAllTracks()) {
581     if (foundTwoClusters) {
582       UpdateTrack(trackCandidate,bestTrackParamAtCluster1,bestTrackParamAtCluster2);
583       
584       // Printout for debuging
585       if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
586         cout << "FollowTrackInStation: added the two best clusters in station(1..): " << nextStation+1 << endl;
587         if (AliLog::GetGlobalDebugLevel() >= 3) newTrack->RecursiveDump();
588       }
589       
590     } else if (foundOneCluster) {
591       UpdateTrack(trackCandidate,bestTrackParamAtCluster1);
592       
593       // Printout for debuging
594       if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
595         cout << "FollowTrackInStation: added the best cluster in chamber(1..): " << bestTrackParamAtCluster1.GetClusterPtr()->GetChamberId()+1 << endl;
596         if (AliLog::GetGlobalDebugLevel() >= 3) newTrack->RecursiveDump();
597       }
598       
599     } else {
600       delete [] clusterCh1Used;
601       return kFALSE;
602     }
603     
604   } else if (foundOneCluster || foundTwoClusters) {
605     
606     // remove obsolete track
607     fRecTracksPtr->Remove(&trackCandidate);
608     fNRecTracks--;
609     
610   } else {
611     delete [] clusterCh1Used;
612     return kFALSE;
613   }
614   
615   delete [] clusterCh1Used;
616   return kTRUE;
617   
618 }
619
620   //__________________________________________________________________________
621 Double_t AliMUONTrackReconstructor::TryTwoClusters(const AliMUONTrackParam &trackParamAtCluster1, AliMUONVCluster* cluster2,
622                                                    AliMUONTrackParam &trackParamAtCluster2)
623 {
624 /// Test the compatibility between the track and the 2 clusters together (using trackParam's covariance matrix):
625 /// return the corresponding Chi2 accounting for covariances between the 2 clusters
626 /// return trackParamAtCluster1 & 2
627   
628   // extrapolate track parameters at the z position of the second cluster (no need to extrapolate the covariances)
629   trackParamAtCluster2.SetParameters(trackParamAtCluster1.GetParameters());
630   trackParamAtCluster2.SetZ(trackParamAtCluster1.GetZ());
631   AliMUONTrackExtrap::ExtrapToZ(&trackParamAtCluster2, cluster2->GetZ());
632   
633   // set pointer to cluster2 into trackParamAtCluster2
634   trackParamAtCluster2.SetClusterPtr(cluster2);
635   
636   // Set differences between track and the 2 clusters in the bending and non bending directions
637   AliMUONVCluster* cluster1 = trackParamAtCluster1.GetClusterPtr();
638   TMatrixD dPos(4,1);
639   dPos(0,0) = cluster1->GetX() - trackParamAtCluster1.GetNonBendingCoor();
640   dPos(1,0) = cluster1->GetY() - trackParamAtCluster1.GetBendingCoor();
641   dPos(2,0) = cluster2->GetX() - trackParamAtCluster2.GetNonBendingCoor();
642   dPos(3,0) = cluster2->GetY() - trackParamAtCluster2.GetBendingCoor();
643   
644   // Calculate the error matrix from the track parameter covariances at first cluster
645   TMatrixD error(4,4);
646   error.Zero();
647   if (trackParamAtCluster1.CovariancesExist()) {
648     // Save track parameters at first cluster
649     TMatrixD paramAtCluster1Save(trackParamAtCluster1.GetParameters());
650     
651     // Save track coordinates at second cluster
652     Double_t nonBendingCoor2 = trackParamAtCluster2.GetNonBendingCoor();
653     Double_t bendingCoor2    = trackParamAtCluster2.GetBendingCoor();
654     
655     // copy track parameters at first cluster for jacobian calculation
656     AliMUONTrackParam trackParam(trackParamAtCluster1);
657     
658     // add MCS effect to the covariance matrix at first cluster
659     AliMUONTrackExtrap::AddMCSEffect(&trackParam,AliMUONConstants::ChamberThicknessInX0(),1.);
660     
661     // Get the pointer to the parameter covariance matrix at first cluster
662     const TMatrixD& kParamCov = trackParam.GetCovariances();
663     
664     // Calculate the jacobian related to the transformation between track parameters
665     // at first cluster and track coordinates at the 2 cluster z-positions
666     TMatrixD jacob(4,5);
667     jacob.Zero();
668     // first derivative at the first cluster:
669     jacob(0,0) = 1.; // dx1/dx
670     jacob(1,2) = 1.; // dy1/dy
671     // first derivative at the second cluster:
672     TMatrixD dParam(5,1);
673     for (Int_t i=0; i<5; i++) {
674       // Skip jacobian calculation for parameters with no associated error
675       if (kParamCov(i,i) == 0.) continue;
676       // Small variation of parameter i only
677       for (Int_t j=0; j<5; j++) {
678         if (j==i) {
679           dParam(j,0) = TMath::Sqrt(kParamCov(i,i));
680           if (j == 4) dParam(j,0) *= TMath::Sign(1.,-paramAtCluster1Save(4,0)); // variation always in the same direction
681         } else dParam(j,0) = 0.;
682       }
683       
684       // Set new track parameters at first cluster
685       trackParam.SetParameters(paramAtCluster1Save);
686       trackParam.AddParameters(dParam);
687       trackParam.SetZ(cluster1->GetZ());
688       
689       // Extrapolate new track parameters to the z position of the second cluster
690       AliMUONTrackExtrap::ExtrapToZ(&trackParam,cluster2->GetZ());
691       
692       // Calculate the jacobian
693       jacob(2,i) = (trackParam.GetNonBendingCoor() - nonBendingCoor2) / dParam(i,0); // dx2/dParami
694       jacob(3,i) = (trackParam.GetBendingCoor()    - bendingCoor2   ) / dParam(i,0); // dy2/dParami
695     }
696     
697     // Calculate the error matrix
698     TMatrixD tmp(jacob,TMatrixD::kMult,kParamCov);
699     error = TMatrixD(tmp,TMatrixD::kMultTranspose,jacob);
700   }
701   
702   // Add cluster resolution to the error matrix
703   error(0,0) += cluster1->GetErrX2();
704   error(1,1) += cluster1->GetErrY2();
705   error(2,2) += cluster2->GetErrX2();
706   error(3,3) += cluster2->GetErrY2();
707   
708   // invert the error matrix for Chi2 calculation
709   if (error.Determinant() != 0) {
710     error.Invert();
711   } else {
712     AliWarning(" Determinant error=0");
713     return 1.e10;
714   }
715   
716   // Compute the Chi2 value
717   TMatrixD tmp2(dPos,TMatrixD::kTransposeMult,error);
718   TMatrixD result(tmp2,TMatrixD::kMult,dPos);
719   
720   return result(0,0);
721   
722 }
723
724   //__________________________________________________________________________
725 void AliMUONTrackReconstructor::UpdateTrack(AliMUONTrack &track, AliMUONTrackParam &trackParamAtCluster)
726 {
727   /// Add 1 cluster to the track candidate
728   /// Update chi2 of the track 
729   
730   // Compute local chi2
731   AliMUONVCluster* cluster = trackParamAtCluster.GetClusterPtr();
732   Double_t deltaX = trackParamAtCluster.GetNonBendingCoor() - cluster->GetX();
733   Double_t deltaY = trackParamAtCluster.GetBendingCoor() - cluster->GetY();
734   Double_t localChi2 = deltaX*deltaX / cluster->GetErrX2() +
735                        deltaY*deltaY / cluster->GetErrY2();
736   
737   // Flag cluster as being not removable
738   trackParamAtCluster.SetRemovable(kFALSE);
739   trackParamAtCluster.SetLocalChi2(0.); // --> Local chi2 not used
740   
741   // Update the chi2 of the new track
742   track.SetGlobalChi2(track.GetGlobalChi2() + localChi2);
743   
744   // Update TrackParamAtCluster
745   track.AddTrackParamAtCluster(trackParamAtCluster,*cluster);
746   track.GetTrackParamAtCluster()->Sort();
747   
748 }
749
750   //__________________________________________________________________________
751 void AliMUONTrackReconstructor::UpdateTrack(AliMUONTrack &track, AliMUONTrackParam &trackParamAtCluster1, AliMUONTrackParam &trackParamAtCluster2)
752 {
753   /// Add 2 clusters to the track candidate
754   /// Update track and local chi2
755   
756   // Update local chi2 at first cluster
757   AliMUONVCluster* cluster1 = trackParamAtCluster1.GetClusterPtr();
758   Double_t deltaX = trackParamAtCluster1.GetNonBendingCoor() - cluster1->GetX();
759   Double_t deltaY = trackParamAtCluster1.GetBendingCoor() - cluster1->GetY();
760   Double_t localChi2AtCluster1 = deltaX*deltaX / cluster1->GetErrX2() +
761                                  deltaY*deltaY / cluster1->GetErrY2();
762   trackParamAtCluster1.SetLocalChi2(localChi2AtCluster1);
763   
764   // Flag first cluster as being removable
765   trackParamAtCluster1.SetRemovable(kTRUE);
766   
767   // Update local chi2 at second cluster
768   AliMUONVCluster* cluster2 = trackParamAtCluster2.GetClusterPtr();
769   deltaX = trackParamAtCluster2.GetNonBendingCoor() - cluster2->GetX();
770   deltaY = trackParamAtCluster2.GetBendingCoor() - cluster2->GetY();
771   Double_t localChi2AtCluster2 = deltaX*deltaX / cluster2->GetErrX2() +
772                                  deltaY*deltaY / cluster2->GetErrY2();
773   trackParamAtCluster2.SetLocalChi2(localChi2AtCluster2);
774   
775   // Flag first cluster as being removable
776   trackParamAtCluster2.SetRemovable(kTRUE);
777   
778   // Update the chi2 of the new track
779   track.SetGlobalChi2(track.GetGlobalChi2() + localChi2AtCluster1 + localChi2AtCluster2);
780   
781   // Update TrackParamAtCluster
782   track.AddTrackParamAtCluster(trackParamAtCluster1,*cluster1);
783   track.AddTrackParamAtCluster(trackParamAtCluster2,*cluster2);
784   track.GetTrackParamAtCluster()->Sort();
785   
786 }
787
788   //__________________________________________________________________________
789 Bool_t AliMUONTrackReconstructor::RecoverTrack(AliMUONTrack &trackCandidate, AliMUONVClusterStore& clusterStore, Int_t nextStation)
790 {
791   /// Try to recover the track candidate in the next station
792   /// by removing the worst of the two clusters attached in the current station
793   /// Return kTRUE if recovering succeeds
794   AliDebug(1,"Enter RecoverTrack");
795   
796   // Do not try to recover track until we have attached cluster(s) on station(1..) 3
797   if (nextStation > 1) return kFALSE;
798   
799   Int_t worstClusterNumber = -1;
800   Double_t localChi2, worstLocalChi2 = 0.;
801   
802   // Look for the cluster to remove
803   for (Int_t clusterNumber = 0; clusterNumber < 2; clusterNumber++) {
804     AliMUONTrackParam *trackParamAtCluster = (AliMUONTrackParam*)trackCandidate.GetTrackParamAtCluster()->UncheckedAt(clusterNumber);
805     
806     // check if current cluster is removable
807     if (!trackParamAtCluster->IsRemovable()) return kFALSE;
808     
809     // Pick up cluster with the worst chi2
810     localChi2 = trackParamAtCluster->GetLocalChi2();
811     if (localChi2 > worstLocalChi2) {
812       worstLocalChi2 = localChi2;
813       worstClusterNumber = clusterNumber;
814     }
815   }
816   
817   // Reset best cluster as being NOT removable
818   ((AliMUONTrackParam*)trackCandidate.GetTrackParamAtCluster()->UncheckedAt((worstClusterNumber+1)%2))->SetRemovable(kFALSE);
819   
820   // Remove the worst cluster
821   trackCandidate.RemoveTrackParamAtCluster((AliMUONTrackParam*)trackCandidate.GetTrackParamAtCluster()->UncheckedAt(worstClusterNumber));
822   
823   // Re-fit the track:
824   // Do not take into account the multiple scattering to speed up the fit
825   // Calculate the track parameter covariance matrix
826   Fit(trackCandidate, kFALSE, kFALSE, kTRUE);
827   
828   // Look for new cluster(s) in next station
829   return FollowTrackInStation(trackCandidate,clusterStore,nextStation);
830   
831 }
832
833   //__________________________________________________________________________
834 void AliMUONTrackReconstructor::SetVertexErrXY2ForFit(AliMUONTrack &trackCandidate)
835 {
836   /// Compute the vertex resolution square from natural vertex dispersion and
837   /// multiple scattering effets according to trackCandidate path in absorber
838   /// It is necessary to account for multiple scattering effects here instead of during the fit of
839   /// the "trackCandidate" to do not influence the result by changing track resolution at vertex
840   AliDebug(1,"Enter SetVertexForFit");
841   
842   Double_t nonBendingReso2 = AliMUONReconstructor::GetRecoParam()->GetNonBendingVertexDispersion() *
843                              AliMUONReconstructor::GetRecoParam()->GetNonBendingVertexDispersion();
844   Double_t bendingReso2 = AliMUONReconstructor::GetRecoParam()->GetBendingVertexDispersion() *
845                           AliMUONReconstructor::GetRecoParam()->GetBendingVertexDispersion();
846   
847   // add multiple scattering effets
848   AliMUONTrackParam paramAtVertex(*((AliMUONTrackParam*)(trackCandidate.GetTrackParamAtCluster()->First())));
849   paramAtVertex.DeleteCovariances(); // to be sure to account only for multiple scattering
850   AliMUONTrackExtrap::ExtrapToVertexUncorrected(&paramAtVertex,0.);
851   const TMatrixD& kParamCov = paramAtVertex.GetCovariances();
852   nonBendingReso2 += kParamCov(0,0);
853   bendingReso2 += kParamCov(2,2);
854   
855   // Set the vertex resolution square
856   trackCandidate.SetVertexErrXY2(nonBendingReso2,bendingReso2);
857 }
858
859   //__________________________________________________________________________
860 void AliMUONTrackReconstructor::Fit(AliMUONTrack &track, Bool_t includeMCS, Bool_t fitWithVertex, Bool_t calcCov)
861 {
862   /// Fit the track
863   /// w/wo multiple Coulomb scattering according to "includeMCS".
864   /// w/wo constraining the vertex according to "fitWithVertex".
865   /// calculating or not the covariance matrix according to "calcCov".
866   
867   Double_t benC, errorParam, invBenP, nonBenC, x, y;
868   AliMUONTrackParam *trackParam;
869   Double_t arg[1], fedm, errdef, globalChi2;
870   Int_t npari, nparx;
871   Int_t status, covStatus;
872   
873   // Instantiate gMinuit if not already done
874   if (!gMinuit) gMinuit = new TMinuit(6);
875   // Clear MINUIT parameters
876   gMinuit->mncler();
877   // Give the fitted track to MINUIT
878   gMinuit->SetObjectFit(&track);
879   if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 2) || (AliLog::GetGlobalDebugLevel() >= 2)) {
880     // Define print level
881     arg[0] = 1;
882     gMinuit->mnexcm("SET PRI", arg, 1, status);
883     // Print covariance matrix
884     gMinuit->mnexcm("SHO COV", arg, 0, status);
885   } else {
886     arg[0] = -1;
887     gMinuit->mnexcm("SET PRI", arg, 1, status);
888   }
889   // No warnings
890   gMinuit->mnexcm("SET NOW", arg, 0, status);
891   // Define strategy
892   //arg[0] = 2;
893   //gMinuit->mnexcm("SET STR", arg, 1, status);
894   
895   // set flag w/wo multiple scattering according to "includeMCS"
896   track.FitWithMCS(includeMCS);
897   if (includeMCS) {
898     // compute cluster weights only once
899     if (!track.ComputeClusterWeights()) {
900       AliWarning("cannot take into account the multiple scattering effects");
901       track.FitWithMCS(kFALSE);
902     }
903   }
904   
905   track.FitWithVertex(fitWithVertex);
906   if (fitWithVertex) SetVertexErrXY2ForFit(track);
907   
908   // Set fitting function
909   gMinuit->SetFCN(TrackChi2);
910   
911   // Set fitted parameters (!! The order is very important for the covariance matrix !!)
912   trackParam = (AliMUONTrackParam*) (track.GetTrackParamAtCluster()->First());
913   // could be tried with no limits for the search (min=max=0) ????
914   // mandatory limits in non Bending to avoid NaN values of parameters
915   gMinuit->mnparm(0, "X", trackParam->GetNonBendingCoor(), 0.03, -500.0, 500.0, status);
916   gMinuit->mnparm(1, "NonBenS", trackParam->GetNonBendingSlope(), 0.001, -0.5, 0.5, status);
917   // mandatory limits in Bending to avoid NaN values of parameters
918   gMinuit->mnparm(2, "Y", trackParam->GetBendingCoor(), 0.10, -500.0, 500.0, status);
919   gMinuit->mnparm(3, "BenS", trackParam->GetBendingSlope(), 0.001, -0.5, 0.5, status);
920   gMinuit->mnparm(4, "InvBenP", trackParam->GetInverseBendingMomentum(), 0.003, -0.4, 0.4, status);
921   
922   // minimization
923   gMinuit->mnexcm("MIGRAD", arg, 0, status);
924   
925   // Calculate the covariance matrix more accurately if required
926   if (calcCov) gMinuit->mnexcm("HESSE", arg, 0, status);
927    
928   // get results into "invBenP", "benC", "nonBenC" ("x", "y")
929   gMinuit->GetParameter(0, x, errorParam);
930   trackParam->SetNonBendingCoor(x);
931   gMinuit->GetParameter(1, nonBenC, errorParam);
932   trackParam->SetNonBendingSlope(nonBenC);
933   gMinuit->GetParameter(2, y, errorParam);
934   trackParam->SetBendingCoor(y);
935   gMinuit->GetParameter(3, benC, errorParam);
936   trackParam->SetBendingSlope(benC);
937   gMinuit->GetParameter(4, invBenP, errorParam);
938   trackParam->SetInverseBendingMomentum(invBenP);
939   
940   // global result of the fit
941   gMinuit->mnstat(globalChi2, fedm, errdef, npari, nparx, covStatus);
942   track.SetGlobalChi2(globalChi2);
943   
944   // Get the covariance matrix if required
945   if (calcCov) {
946     // Covariance matrix according to HESSE status
947     // If problem then keep only the diagonal terms (variances)
948     Double_t matrix[5][5];
949     gMinuit->mnemat(&matrix[0][0],5);
950     if (covStatus == 3) trackParam->SetCovariances(matrix);
951     else trackParam->SetVariances(matrix);
952   } else trackParam->DeleteCovariances();
953   
954 }
955
956   //__________________________________________________________________________
957 void TrackChi2(Int_t & /*nParam*/, Double_t * /*gradient*/, Double_t &chi2, Double_t *param, Int_t /*flag*/)
958 {
959   /// Return the "Chi2" to be minimized with Minuit for track fitting.
960   /// Assumes that the trackParamAtCluster are sorted according to increasing Z.
961   /// Track parameters at each cluster are updated accordingly.
962   /// Vertex is used according to the flag "trackBeingFitted->GetFitWithVertex()".
963   /// Multiple Coulomb scattering is taken into account according to the flag "trackBeingFitted->GetFitWithMCS()".
964   
965   AliMUONTrack *trackBeingFitted = (AliMUONTrack*) gMinuit->GetObjectFit();
966   AliMUONTrackParam* trackParamAtCluster = (AliMUONTrackParam*) trackBeingFitted->GetTrackParamAtCluster()->First();
967   Double_t dX, dY;
968   chi2 = 0.; // initialize chi2
969   
970   // update track parameters
971   trackParamAtCluster->SetNonBendingCoor(param[0]);
972   trackParamAtCluster->SetNonBendingSlope(param[1]);
973   trackParamAtCluster->SetBendingCoor(param[2]);
974   trackParamAtCluster->SetBendingSlope(param[3]);
975   trackParamAtCluster->SetInverseBendingMomentum(param[4]);
976   trackBeingFitted->UpdateTrackParamAtCluster();
977   
978   // Take the vertex into account in the fit if required
979   if (trackBeingFitted->FitWithVertex()) {
980     Double_t nonBendingReso2,bendingReso2;
981     trackBeingFitted->GetVertexErrXY2(nonBendingReso2,bendingReso2);
982     if (nonBendingReso2 == 0. || bendingReso2 == 0.) chi2 += 1.e10;
983     else {
984       AliMUONTrackParam paramAtVertex(*trackParamAtCluster);
985       AliMUONTrackExtrap::ExtrapToZ(&paramAtVertex, 0.); // vextex position = (0,0,0)
986       dX = paramAtVertex.GetNonBendingCoor();
987       dY = paramAtVertex.GetBendingCoor();
988       chi2 += dX * dX / nonBendingReso2 + dY * dY / bendingReso2;
989     }
990   }
991   
992   // compute chi2 w/wo multiple scattering
993   chi2 += trackBeingFitted->ComputeGlobalChi2(trackBeingFitted->FitWithMCS());
994   
995 }
996
997   //__________________________________________________________________________
998 void AliMUONTrackReconstructor::ComplementTracks(const AliMUONVClusterStore& clusterStore)
999 {
1000   /// Complete tracks by adding missing clusters (if there is an overlap between
1001   /// two detection elements, the track may have two clusters in the same chamber)
1002   /// Re-fit track parameters and covariances
1003   AliDebug(1,"Enter ComplementTracks");
1004   
1005   Int_t chamberId, detElemId;
1006   Double_t chi2OfCluster, bestChi2OfCluster;
1007   Double_t sigmaCut2 = AliMUONReconstructor::GetRecoParam()->GetSigmaCutForTracking() *
1008                        AliMUONReconstructor::GetRecoParam()->GetSigmaCutForTracking();
1009   Bool_t foundOneCluster, trackModified;
1010   AliMUONVCluster* cluster;
1011   AliMUONTrackParam *trackParam, *nextTrackParam, copyOfTrackParam, trackParamAtCluster, bestTrackParamAtCluster;
1012   
1013   // Remove double track to complete only "good" tracks
1014   RemoveDoubleTracks();
1015   
1016   AliMUONTrack *track = (AliMUONTrack*) fRecTracksPtr->First();
1017   while (track) {
1018     trackModified = kFALSE;
1019     
1020     trackParam = (AliMUONTrackParam*)track->GetTrackParamAtCluster()->First();
1021     while (trackParam) {
1022       foundOneCluster = kFALSE;
1023       bestChi2OfCluster = 2. * sigmaCut2; // 2 because 2 quantities in chi2
1024       chamberId = trackParam->GetClusterPtr()->GetChamberId();
1025       detElemId = trackParam->GetClusterPtr()->GetDetElemId();
1026       
1027       // prepare nextTrackParam before adding new cluster because of the sorting
1028       nextTrackParam = (AliMUONTrackParam*)track->GetTrackParamAtCluster()->After(trackParam);
1029       
1030       // recover track parameters from local fit and put them into a copy of trackParam
1031       copyOfTrackParam.SetZ(trackParam->GetZ());
1032       copyOfTrackParam.SetParameters(trackParam->GetSmoothParameters());
1033       copyOfTrackParam.SetCovariances(trackParam->GetSmoothCovariances());
1034       
1035       // Create iterators to loop over clusters in current chamber
1036       TIter nextInCh(clusterStore.CreateChamberIterator(chamberId,chamberId));
1037       
1038       // look for one second candidate in the same chamber
1039       while ( ( cluster = static_cast<AliMUONVCluster*>(nextInCh()) ) ) {
1040         
1041         // look for a cluster in another detection element
1042         if (cluster->GetDetElemId() == detElemId) continue;
1043         
1044         // try to add the current cluster fast
1045         if (!TryOneClusterFast(copyOfTrackParam, cluster)) continue;
1046         
1047         // try to add the current cluster accurately
1048         chi2OfCluster = TryOneCluster(copyOfTrackParam, cluster, trackParamAtCluster);
1049         
1050         // if better chi2 then prepare to add this cluster to the track
1051         if (chi2OfCluster < bestChi2OfCluster) {
1052           bestChi2OfCluster = chi2OfCluster;
1053           bestTrackParamAtCluster = trackParamAtCluster;
1054           foundOneCluster = kTRUE;
1055         }
1056         
1057       }
1058       
1059       // add new cluster if any
1060       if (foundOneCluster) {
1061         UpdateTrack(*track,bestTrackParamAtCluster);
1062         bestTrackParamAtCluster.SetAloneInChamber(kFALSE);
1063         trackParam->SetAloneInChamber(kFALSE);
1064         trackModified = kTRUE;
1065       }
1066       
1067       trackParam = nextTrackParam;
1068     }
1069     
1070     // re-fit track parameters if needed
1071     if (trackModified) Fit(*track, kTRUE, kFALSE, kTRUE);
1072     
1073     track = (AliMUONTrack*) fRecTracksPtr->After(track);
1074   }
1075   
1076 }
1077
1078   //__________________________________________________________________________
1079 void AliMUONTrackReconstructor::ImproveTracks()
1080 {
1081   /// Improve tracks by removing clusters with local chi2 highter than the defined cut
1082   /// Recompute track parameters and covariances at the remaining clusters
1083   AliDebug(1,"Enter ImproveTracks");
1084   
1085   Double_t localChi2, worstLocalChi2;
1086   Int_t worstChamber, previousChamber;
1087   AliMUONTrack *track, *nextTrack;
1088   AliMUONTrackParam *trackParamAtCluster, *worstTrackParamAtCluster, *previousTrackParam, *nextTrackParam;
1089   Double_t sigmaCut2 = AliMUONReconstructor::GetRecoParam()->GetSigmaCutForImprovement() *
1090                        AliMUONReconstructor::GetRecoParam()->GetSigmaCutForImprovement();
1091   
1092   // Remove double track to improve only "good" tracks
1093   RemoveDoubleTracks();
1094   
1095   track = (AliMUONTrack*) fRecTracksPtr->First();
1096   while (track) {
1097     
1098     // prepare next track in case the actual track is suppressed
1099     nextTrack = (AliMUONTrack*) fRecTracksPtr->After(track);
1100     
1101     while (!track->IsImproved()) {
1102       
1103       // Update track parameters and covariances
1104       track->UpdateCovTrackParamAtCluster();
1105       
1106       // Compute local chi2 of each clusters
1107       track->ComputeLocalChi2(kTRUE);
1108       
1109       // Look for the cluster to remove
1110       worstTrackParamAtCluster = NULL;
1111       worstLocalChi2 = 0.;
1112       trackParamAtCluster = (AliMUONTrackParam*) track->GetTrackParamAtCluster()->First();
1113       while (trackParamAtCluster) {
1114         
1115         // Pick up cluster with the worst chi2
1116         localChi2 = trackParamAtCluster->GetLocalChi2();
1117         if (localChi2 > worstLocalChi2) {
1118           worstLocalChi2 = localChi2;
1119           worstTrackParamAtCluster = trackParamAtCluster;
1120         }
1121         
1122       trackParamAtCluster = (AliMUONTrackParam*) track->GetTrackParamAtCluster()->After(trackParamAtCluster);
1123       }
1124       
1125       // Check if bad cluster found
1126       if (!worstTrackParamAtCluster) {
1127         track->SetImproved(kTRUE);
1128         break;
1129       }
1130       
1131       // Check whether the worst chi2 is under requirement or not
1132       if (worstLocalChi2 < 2. * sigmaCut2) { // 2 because 2 quantities in chi2
1133         track->SetImproved(kTRUE);
1134         break;
1135       }
1136       
1137       // if the worst cluster is not removable then remove the entire track
1138       if (!worstTrackParamAtCluster->IsRemovable() && worstTrackParamAtCluster->IsAloneInChamber()) {
1139         fRecTracksPtr->Remove(track);
1140         fNRecTracks--;
1141         break;
1142       }
1143       
1144       // Reset the second cluster in the same station as being not removable
1145       // or reset the second cluster in the same chamber as being alone
1146       worstChamber = worstTrackParamAtCluster->GetClusterPtr()->GetChamberId();
1147       previousTrackParam = (AliMUONTrackParam*) track->GetTrackParamAtCluster()->Before(worstTrackParamAtCluster);
1148       nextTrackParam = (AliMUONTrackParam*) track->GetTrackParamAtCluster()->After(worstTrackParamAtCluster);
1149       if (worstTrackParamAtCluster->IsAloneInChamber()) { // Worst cluster removable and alone in chamber
1150         
1151         if (worstChamber%2 == 0) { // Modify flags in next chamber
1152           
1153           nextTrackParam->SetRemovable(kFALSE);
1154           if (!nextTrackParam->IsAloneInChamber()) // Make sure both clusters in second chamber are not removable anymore
1155             ((AliMUONTrackParam*) track->GetTrackParamAtCluster()->After(nextTrackParam))->SetRemovable(kFALSE);
1156           
1157         } else { // Modify flags in previous chamber
1158           
1159           previousTrackParam->SetRemovable(kFALSE);
1160           if (!previousTrackParam->IsAloneInChamber()) // Make sure both clusters in second chamber are not removable anymore
1161             ((AliMUONTrackParam*) track->GetTrackParamAtCluster()->Before(previousTrackParam))->SetRemovable(kFALSE);
1162           
1163         }
1164         
1165       } else { // Worst cluster not alone in its chamber
1166         
1167         if (previousTrackParam) previousChamber = previousTrackParam->GetClusterPtr()->GetChamberId();
1168         else previousChamber = -1;
1169         
1170         if (previousChamber == worstChamber) { // the second cluster on the same chamber is the previous one
1171           
1172           previousTrackParam->SetAloneInChamber(kTRUE);
1173           // transfert the removability to the second cluster
1174           if (worstTrackParamAtCluster->IsRemovable()) previousTrackParam->SetRemovable(kTRUE);
1175           
1176         } else { // the second cluster on the same chamber is the next one
1177           
1178           nextTrackParam->SetAloneInChamber(kTRUE);
1179           // transfert the removability to the second cluster
1180           if (worstTrackParamAtCluster->IsRemovable()) nextTrackParam->SetRemovable(kTRUE);
1181           
1182         }
1183         
1184       }
1185       
1186       // Remove the worst cluster
1187       track->RemoveTrackParamAtCluster(worstTrackParamAtCluster);
1188       
1189       // Re-fit the track:
1190       // Take into account the multiple scattering
1191       // Calculate the track parameter covariance matrix
1192       Fit(*track, kTRUE, kFALSE, kTRUE);
1193       
1194       // Printout for debuging
1195       if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
1196         cout << "ImproveTracks: track " << fRecTracksPtr->IndexOf(track)+1 << " improved " << endl;
1197       }
1198       
1199     }
1200     
1201     track = nextTrack;
1202   }
1203   
1204   // compress the array in case of some tracks have been removed
1205   fRecTracksPtr->Compress();
1206   
1207 }
1208
1209   //__________________________________________________________________________
1210 void AliMUONTrackReconstructor::Finalize()
1211 {
1212   /// Recompute track parameters and covariances at each attached cluster from those at the first one
1213   
1214   AliMUONTrack *track;
1215   
1216   track = (AliMUONTrack*) fRecTracksPtr->First();
1217   while (track) {
1218     
1219     // update track parameters if not already done
1220     if (!track->IsImproved()) track->UpdateCovTrackParamAtCluster();
1221     
1222     track = (AliMUONTrack*) fRecTracksPtr->After(track);
1223     
1224   }
1225   
1226 }
1227