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