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