]> git.uio.no Git - u/mrichter/AliRoot.git/blob - MUON/AliMUONEventReconstructor.cxx
Add track matching between trigger and tracker informations (CF+JPC)
[u/mrichter/AliRoot.git] / MUON / AliMUONEventReconstructor.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 //
20 // MUON event reconstructor in ALICE
21 //
22 // This class contains as data:
23 // * the parameters for the event reconstruction
24 // * a pointer to the array of hits to be reconstructed (the event)
25 // * a pointer to the array of segments made with these hits inside each station
26 // * a pointer to the array of reconstructed tracks
27 //
28 // It contains as methods, among others:
29 // * MakeEventToBeReconstructed to build the array of hits to be reconstructed
30 // * MakeSegments to build the segments
31 // * MakeTracks to build the tracks
32 //
33 ////////////////////////////////////
34
35 #include <Riostream.h> // for cout
36 #include <stdlib.h> // for exit()
37
38 #include <TTree.h>
39
40 #include "AliMUON.h"
41 //#include "AliMUONChamber.h"
42 #include "AliMUONEventReconstructor.h"
43 #include "AliMUONHitForRec.h"
44 #include "AliMUONTriggerTrack.h"
45 //#include "AliMUONTriggerConstants.h"
46 #include "AliMUONTriggerCircuit.h"
47 #include "AliMUONRawCluster.h"
48 #include "AliMUONLocalTrigger.h"
49 #include "AliMUONGlobalTrigger.h"
50 #include "AliMUONRecoEvent.h"
51 #include "AliMUONSegment.h"
52 #include "AliMUONTrack.h"
53 #include "AliMUONTrackHit.h"
54 #include "AliMagF.h"
55 #include "AliRun.h" // for gAlice
56 #include "AliConfig.h"
57 #include "AliRunLoader.h"
58 #include "AliLoader.h"
59 #include "AliMUONTrackK.h" //AZ
60 #include <TMatrixD.h> //AZ
61 #include "AliMC.h"
62
63 //************* Defaults parameters for reconstruction
64 static const Double_t kDefaultMinBendingMomentum = 3.0;
65 static const Double_t kDefaultMaxBendingMomentum = 500.0;
66 static const Double_t kDefaultMaxChi2 = 100.0;
67 static const Double_t kDefaultMaxSigma2Distance = 16.0;
68 static const Double_t kDefaultBendingResolution = 0.01;
69 static const Double_t kDefaultNonBendingResolution = 0.144;
70 static const Double_t kDefaultChamberThicknessInX0 = 0.03;
71 // Simple magnetic field:
72 // Value taken from macro MUONtracking.C: 0.7 T, hence 7 kG
73 // Length and Position from reco_muon.F, with opposite sign:
74 // Length = ZMAGEND-ZCOIL
75 // Position = (ZMAGEND+ZCOIL)/2
76 // to be ajusted differently from real magnetic field ????
77 static const Double_t kDefaultSimpleBValue = 7.0;
78 static const Double_t kDefaultSimpleBLength = 428.0;
79 static const Double_t kDefaultSimpleBPosition = 1019.0;
80 static const Int_t kDefaultRecGeantHits = 0;
81 static const Double_t kDefaultEfficiency = 0.95;
82
83 static const Int_t kDefaultPrintLevel = -1;
84
85 ClassImp(AliMUONEventReconstructor) // Class implementation in ROOT context
86
87   //__________________________________________________________________________
88 AliMUONEventReconstructor::AliMUONEventReconstructor(AliLoader* loader)
89 {
90   // Constructor for class AliMUONEventReconstructor
91   SetReconstructionParametersToDefaults();
92   fTrackMethod = 1; //AZ - tracking method (1-default, 2-Kalman)
93   // Memory allocation for the TClonesArray of hits for reconstruction
94   // Is 10000 the right size ????
95   fHitsForRecPtr = new TClonesArray("AliMUONHitForRec", 10000);
96   fNHitsForRec = 0; // really needed or GetEntriesFast sufficient ????
97   // Memory allocation for the TClonesArray's of segments in stations
98   // Is 2000 the right size ????
99   for (Int_t st = 0; st < kMaxMuonTrackingStations; st++) {
100     fSegmentsPtr[st] = new TClonesArray("AliMUONSegment", 2000);
101     fNSegments[st] = 0; // really needed or GetEntriesFast sufficient ????
102   }
103   // Memory allocation for the TClonesArray of reconstructed tracks
104   // Is 10 the right size ????
105   fRecTracksPtr = new TClonesArray("AliMUONTrack", 10);
106   fNRecTracks = 0; // really needed or GetEntriesFast sufficient ????
107 // trigger tracks
108   fRecTriggerTracksPtr = new TClonesArray("AliMUONTriggerTrack", 10);
109   fNRecTriggerTracks = 0; // really needed or GetEntriesFast sufficient ????
110   // Memory allocation for the TClonesArray of hits on reconstructed tracks
111   // Is 100 the right size ????
112   fRecTrackHitsPtr = new TClonesArray("AliMUONTrack", 100);
113   fNRecTrackHits = 0; // really needed or GetEntriesFast sufficient ????
114
115   // Sign of fSimpleBValue according to sign of Bx value at (50,50,-950).
116   Float_t b[3], x[3];
117   x[0] = 50.; x[1] = 50.; x[2] = -950.;
118   gAlice->Field()->Field(x, b);
119   fSimpleBValue = TMath::Sign(fSimpleBValue,(Double_t) b[0]);
120   fSimpleBPosition = TMath::Sign(fSimpleBPosition,(Double_t) x[2]);
121   // See how to get fSimple(BValue, BLength, BPosition)
122   // automatically calculated from the actual magnetic field ????
123
124   if (fPrintLevel >= 0) {
125     cout << "AliMUONEventReconstructor constructed with defaults" << endl; Dump();
126     cout << endl << "Magnetic field from root file:" << endl;
127     gAlice->Field()->Dump();
128     cout << endl;
129   }
130   
131   // Initializions for GEANT background events
132   fBkgGeantFile = 0;
133   fBkgGeantTK = 0;
134   fBkgGeantParticles = 0;
135   fBkgGeantTH = 0;
136   fBkgGeantHits = 0;
137   fBkgGeantEventNumber = -1;
138   
139   // Initialize to 0 pointers to RecoEvent, tree and tree file
140   fRecoEvent = 0;
141   fEventTree = 0;
142   fTreeFile  = 0;
143  
144   // initialize loader's
145   fLoader = loader;
146
147   // initialize container
148   fMUONData  = new AliMUONData(fLoader,"MUON","MUON");
149
150    // Loading AliRun master
151   AliRunLoader* runloader = fLoader->GetRunLoader();
152   if (runloader->GetAliRun() == 0x0) runloader->LoadgAlice();
153   gAlice = runloader->GetAliRun();
154
155   return;
156 }
157   //__________________________________________________________________________
158 AliMUONEventReconstructor::AliMUONEventReconstructor (const AliMUONEventReconstructor& Reconstructor):TObject(Reconstructor)
159 {
160   // Dummy copy constructor
161 }
162
163 AliMUONEventReconstructor & AliMUONEventReconstructor::operator=(const AliMUONEventReconstructor& /*Reconstructor*/)
164 {
165   // Dummy assignment operator
166     return *this;
167 }
168
169   //__________________________________________________________________________
170 AliMUONEventReconstructor::~AliMUONEventReconstructor(void)
171 {
172   // Destructor for class AliMUONEventReconstructor
173   if (fTreeFile) {
174      fTreeFile->Close();
175      delete fTreeFile;
176   }
177 //  if (fEventTree) delete fEventTree;
178   if (fRecoEvent) delete fRecoEvent;
179   delete fHitsForRecPtr; // Correct destruction of everything ???? or delete [] ????
180   for (Int_t st = 0; st < kMaxMuonTrackingStations; st++)
181     delete fSegmentsPtr[st]; // Correct destruction of everything ????
182   return;
183 }
184
185   //__________________________________________________________________________
186 void AliMUONEventReconstructor::SetReconstructionParametersToDefaults(void)
187 {
188   // Set reconstruction parameters to default values
189   // Would be much more convenient with a structure (or class) ????
190   fMinBendingMomentum = kDefaultMinBendingMomentum;
191   fMaxBendingMomentum = kDefaultMaxBendingMomentum;
192   fMaxChi2 = kDefaultMaxChi2;
193   fMaxSigma2Distance = kDefaultMaxSigma2Distance;
194
195   AliMUON *pMUON = (AliMUON*) gAlice->GetModule("MUON");
196   // ******** Parameters for making HitsForRec
197   // minimum radius,
198   // like in TRACKF_STAT:
199   // 2 degrees for stations 1 and 2, or ch(0...) from 0 to 3;
200   // 30 cm for stations 3 to 5, or ch(0...) from 4 to 9
201   for (Int_t ch = 0; ch < kMaxMuonTrackingChambers; ch++) {
202     if (ch < 4) fRMin[ch] = TMath::Abs((&(pMUON->Chamber(ch)))->Z()) *
203                   2.0 * TMath::Pi() / 180.0;
204     else fRMin[ch] = 30.0;
205     // maximum radius at 10 degrees and Z of chamber
206     fRMax[ch] = TMath::Abs((&(pMUON->Chamber(ch)))->Z()) *
207                   10.0 * TMath::Pi() / 180.0;
208   }
209
210   // ******** Parameters for making segments
211   // should be parametrized ????
212   // according to interval between chambers in a station ????
213   // Maximum distance in non bending plane
214   // 5 * 0.22 just to remember the way it was made in TRACKF_STAT
215   // SIGCUT*DYMAX(IZ)
216   for (Int_t st = 0; st < kMaxMuonTrackingStations; st++)
217     fSegmentMaxDistNonBending[st] = 5. * 0.22;
218   // Maximum distance in bending plane:
219   // values from TRACKF_STAT, corresponding to (J psi 20cm),
220   // scaled to the real distance between chambers in a station
221   fSegmentMaxDistBending[0] = TMath::Abs( 1.5 *
222     ((&(pMUON->Chamber(1)))->Z() - (&(pMUON->Chamber(0)))->Z()) / 20.0);
223   fSegmentMaxDistBending[1] =  TMath::Abs( 1.5 *
224     ((&(pMUON->Chamber(3)))->Z() - (&(pMUON->Chamber(2)))->Z()) / 20.0);
225   fSegmentMaxDistBending[2] =  TMath::Abs( 3.0 *
226     ((&(pMUON->Chamber(5)))->Z() - (&(pMUON->Chamber(4)))->Z()) / 20.0);
227   fSegmentMaxDistBending[3] =  TMath::Abs( 6.0 *
228     ((&(pMUON->Chamber(7)))->Z() - (&(pMUON->Chamber(6)))->Z()) / 20.0);
229   fSegmentMaxDistBending[4] =  TMath::Abs( 6.0 *
230     ((&(pMUON->Chamber(9)))->Z() - (&(pMUON->Chamber(8)))->Z()) / 20.0);
231   
232   fBendingResolution = kDefaultBendingResolution;
233   fNonBendingResolution = kDefaultNonBendingResolution;
234   fChamberThicknessInX0 = kDefaultChamberThicknessInX0;
235   fSimpleBValue = kDefaultSimpleBValue;
236   fSimpleBLength = kDefaultSimpleBLength;
237   fSimpleBPosition = kDefaultSimpleBPosition;
238   fRecGeantHits = kDefaultRecGeantHits;
239   fEfficiency = kDefaultEfficiency;
240   fPrintLevel = kDefaultPrintLevel;
241   return;
242 }
243
244 //__________________________________________________________________________
245 Double_t AliMUONEventReconstructor::GetImpactParamFromBendingMomentum(Double_t BendingMomentum) const
246 {
247   // Returns impact parameter at vertex in bending plane (cm),
248   // from the signed bending momentum "BendingMomentum" in bending plane (GeV/c),
249   // using simple values for dipole magnetic field.
250   // The sign of "BendingMomentum" is the sign of the charge.
251   return (-0.0003 * fSimpleBValue * fSimpleBLength * fSimpleBPosition /
252           BendingMomentum);
253 }
254
255 //__________________________________________________________________________
256 Double_t AliMUONEventReconstructor::GetBendingMomentumFromImpactParam(Double_t ImpactParam) const
257 {
258   // Returns signed bending momentum in bending plane (GeV/c),
259   // the sign being the sign of the charge for particles moving forward in Z,
260   // from the impact parameter "ImpactParam" at vertex in bending plane (cm),
261   // using simple values for dipole magnetic field.
262   return (-0.0003 * fSimpleBValue * fSimpleBLength * fSimpleBPosition /
263           ImpactParam);
264 }
265
266 //__________________________________________________________________________
267 void AliMUONEventReconstructor::SetBkgGeantFile(Text_t *BkgGeantFileName)
268 {
269   // Set background file ... for GEANT hits
270   // Must be called after having loaded the firts signal event
271   if (fPrintLevel >= 0) {
272     cout << "Enter SetBkgGeantFile with BkgGeantFileName ``"
273          << BkgGeantFileName << "''" << endl;}
274   if (strlen(BkgGeantFileName)) {
275     // BkgGeantFileName not empty: try to open the file
276     if (fPrintLevel >= 2) {cout << "Before File(Bkg)" << endl; gDirectory->Dump();}
277     fBkgGeantFile = new TFile(BkgGeantFileName);
278     if (fPrintLevel >= 2) {cout << "After File(Bkg)" << endl; gDirectory->Dump();}
279     if (fBkgGeantFile-> IsOpen()) {
280       if (fPrintLevel >= 0) {
281         cout << "Background for GEANT hits in file: ``" << BkgGeantFileName
282              << "'' successfully opened" << endl;}
283     }
284     else {
285       cout << "Background for GEANT hits in file: " << BkgGeantFileName << endl;
286       cout << "NOT FOUND: EXIT" << endl;
287       exit(0); // right instruction for exit ????
288     }
289     // Arrays for "particles" and "hits"
290     fBkgGeantParticles = new TClonesArray("TParticle", 200);
291     fBkgGeantHits = new TClonesArray("AliMUONHit", 2000);
292     // Event number to -1 for initialization
293     fBkgGeantEventNumber = -1;
294     // Back to the signal file:
295     // first signal event must have been loaded previously,
296     // otherwise, Segmentation violation at the next instruction
297     // How is it possible to do smething better ????
298     ((gAlice->TreeK())->GetCurrentFile())->cd();
299     if (fPrintLevel >= 2) {cout << "After cd(gAlice)" << endl; gDirectory->Dump();}
300   }
301   return;
302 }
303
304 //__________________________________________________________________________
305 void AliMUONEventReconstructor::NextBkgGeantEvent(void)
306 {
307   // Get next event in background file for GEANT hits
308   // Goes back to event number 0 when end of file is reached
309   char treeName[20];
310   TBranch *branch;
311   if (fPrintLevel >= 0) {
312     cout << "Enter NextBkgGeantEvent" << endl;}
313   // Clean previous event
314   if(fBkgGeantTK) delete fBkgGeantTK;
315   fBkgGeantTK = NULL;
316   if(fBkgGeantParticles) fBkgGeantParticles->Clear();
317   if(fBkgGeantTH) delete fBkgGeantTH;
318   fBkgGeantTH = NULL;
319   if(fBkgGeantHits) fBkgGeantHits->Clear();
320   // Increment event number
321   fBkgGeantEventNumber++;
322   // Get access to Particles and Hits for event from background file
323   if (fPrintLevel >= 2) {cout << "Before cd(Bkg)" << endl; gDirectory->Dump();}
324   fBkgGeantFile->cd();
325   if (fPrintLevel >= 2) {cout << "After cd(Bkg)" << endl; gDirectory->Dump();}
326   // Particles: TreeK for event and branch "Particles"
327   sprintf(treeName, "TreeK%d", fBkgGeantEventNumber);
328   fBkgGeantTK = (TTree*)gDirectory->Get(treeName);
329   if (!fBkgGeantTK) {
330     if (fPrintLevel >= 0) {
331       cout << "Cannot find Kine Tree for background event: " <<
332         fBkgGeantEventNumber << endl;
333       cout << "Goes back to event 0" << endl;
334     }
335     fBkgGeantEventNumber = 0;
336     sprintf(treeName, "TreeK%d", fBkgGeantEventNumber);
337     fBkgGeantTK = (TTree*)gDirectory->Get(treeName);
338     if (!fBkgGeantTK) {
339       cout << "ERROR: cannot find Kine Tree for background event: " <<
340         fBkgGeantEventNumber << endl;
341       exit(0);
342     }
343   }
344   if (fBkgGeantTK) 
345     fBkgGeantTK->SetBranchAddress("Particles", &fBkgGeantParticles);
346   fBkgGeantTK->GetEvent(0); // why event 0 ???? necessary ????
347   // Hits: TreeH for event and branch "MUON"
348   sprintf(treeName, "TreeH%d", fBkgGeantEventNumber);
349   fBkgGeantTH = (TTree*)gDirectory->Get(treeName);
350   if (!fBkgGeantTH) {
351     cout << "ERROR: cannot find Hits Tree for background event: " <<
352       fBkgGeantEventNumber << endl;
353       exit(0);
354   }
355   if (fBkgGeantTH && fBkgGeantHits) {
356     branch = fBkgGeantTH->GetBranch("MUON");
357     if (branch) branch->SetAddress(&fBkgGeantHits);
358   }
359   fBkgGeantTH->GetEntries(); // necessary ????
360   // Back to the signal file
361   ((gAlice->TreeK())->GetCurrentFile())->cd();
362   if (fPrintLevel >= 2) {cout << "After cd(gAlice)" << endl; gDirectory->Dump();}
363   return;
364 }
365
366 //__________________________________________________________________________
367 void AliMUONEventReconstructor::EventReconstruct(void)
368 {
369   // To reconstruct one event
370   if (fPrintLevel >= 1) cout << "enter EventReconstruct" << endl;
371   MakeEventToBeReconstructed();
372   MakeSegments();
373   MakeTracks();
374   if (fMUONData->IsTriggerTrackBranchesInTree()) 
375     ValidateTracksWithTrigger(); 
376
377   // Add tracks to MUON data container 
378   for(Int_t i=0; i<GetNRecTracks(); i++) {
379     AliMUONTrack * track = (AliMUONTrack*) GetRecTracksPtr()->At(i);
380     fMUONData->AddRecTrack(*track);
381   }
382
383   return;
384 }
385
386 //__________________________________________________________________________
387 void AliMUONEventReconstructor::EventReconstructTrigger(void)
388 {
389   // To reconstruct one event
390   if (fPrintLevel >= 1) cout << "enter EventReconstructTrigger" << endl;
391   MakeTriggerTracks();  
392   return;
393 }
394
395   //__________________________________________________________________________
396 void AliMUONEventReconstructor::ResetHitsForRec(void)
397 {
398   // To reset the array and the number of HitsForRec,
399   // and also the number of HitsForRec
400   // and the index of the first HitForRec per chamber
401   if (fHitsForRecPtr) fHitsForRecPtr->Clear();
402   fNHitsForRec = 0;
403   for (Int_t ch = 0; ch < kMaxMuonTrackingChambers; ch++)
404     fNHitsForRecPerChamber[ch] = fIndexOfFirstHitForRecPerChamber[ch] = 0;
405   return;
406 }
407
408   //__________________________________________________________________________
409 void AliMUONEventReconstructor::ResetSegments(void)
410 {
411   // To reset the TClonesArray of segments and the number of Segments
412   // for all stations
413   for (Int_t st = 0; st < kMaxMuonTrackingStations; st++) {
414     if (fSegmentsPtr[st]) fSegmentsPtr[st]->Clear();
415     fNSegments[st] = 0;
416   }
417   return;
418 }
419
420   //__________________________________________________________________________
421 void AliMUONEventReconstructor::ResetTracks(void)
422 {
423   // To reset the TClonesArray of reconstructed tracks
424   if (fRecTracksPtr) fRecTracksPtr->Delete();
425   // Delete in order that the Track destructors are called,
426   // hence the space for the TClonesArray of pointers to TrackHit's is freed
427   fNRecTracks = 0;
428   return;
429 }
430
431   //__________________________________________________________________________
432 void AliMUONEventReconstructor::ResetTriggerTracks(void)
433 {
434   // To reset the TClonesArray of reconstructed trigger tracks
435     if (fRecTriggerTracksPtr) fRecTriggerTracksPtr->Delete();
436   // Delete in order that the Track destructors are called,
437   // hence the space for the TClonesArray of pointers to TrackHit's is freed
438     fNRecTriggerTracks = 0;
439   return;
440 }
441
442   //__________________________________________________________________________
443 void AliMUONEventReconstructor::ResetTrackHits(void)
444 {
445   // To reset the TClonesArray of hits on reconstructed tracks
446   if (fRecTrackHitsPtr) fRecTrackHitsPtr->Clear();
447   fNRecTrackHits = 0;
448   return;
449 }
450
451   //__________________________________________________________________________
452 void AliMUONEventReconstructor::MakeEventToBeReconstructed(void)
453 {
454   // To make the list of hits to be reconstructed,
455   // either from the GEANT hits or from the raw clusters
456   // according to the parameter set for the reconstructor
457 //   TString evfoldname = AliConfig::fgkDefaultEventFolderName;//to be interfaced properly
458   
459 //   AliRunLoader* rl = AliRunLoader::GetRunLoader(evfoldname);
460 //   if (rl == 0x0)
461 //    {
462 //      Error("MakeEventToBeReconstructed",
463 //            "Can not find Run Loader in Event Folder named %s.",
464 //            evfoldname.Data());
465 //      return;
466 //    }
467 //   AliLoader* gime = rl->GetLoader("MUONLoader");
468 //   if (gime == 0x0)
469 //    {
470 //      Error("MakeEventToBeReconstructed","Can not get MUON Loader from Run Loader.");
471 //      return;
472 //    }
473   
474   if (fPrintLevel >= 1) cout << "enter MakeEventToBeReconstructed" << endl;
475   ResetHitsForRec();
476   if (fRecGeantHits == 1) {
477     // Reconstruction from GEANT hits
478     // Back to the signal file
479       TTree* treeH = fLoader->TreeH();
480       if (treeH == 0x0)
481        {
482          Int_t retval = fLoader->LoadHits();
483          if ( retval)
484           {
485             Error("MakeEventToBeReconstructed","Error occured while loading hits.");
486             return;
487           }
488          treeH = fLoader->TreeH();
489          if (treeH == 0x0)
490           {
491            Error("MakeEventToBeReconstructed","Can not get TreeH");
492            return;
493           }
494        }
495       fMUONData->SetTreeAddress("H");
496       AddHitsForRecFromGEANT(treeH);
497     
498     // Background hits
499     AddHitsForRecFromBkgGEANT(fBkgGeantTH, fBkgGeantHits);
500     // Sort HitsForRec in increasing order with respect to chamber number
501     SortHitsForRecWithIncreasingChamber();
502   }
503   else {
504     // Reconstruction from raw clusters
505     // AliMUON *MUON  = (AliMUON*) gAlice->GetModule("MUON"); // necessary ????
506     // Security on MUON ????
507     // TreeR assumed to be be "prepared" in calling function
508     // by "MUON->GetTreeR(nev)" ????
509     TTree *treeR = fLoader->TreeR();
510     fMUONData->SetTreeAddress("RC");
511     AddHitsForRecFromRawClusters(treeR);
512     // No sorting: it is done automatically in the previous function
513   }
514   if (fPrintLevel >= 10) {
515     cout << "end of MakeEventToBeReconstructed" << endl;
516     cout << "NHitsForRec: " << fNHitsForRec << endl;
517     for (Int_t ch = 0; ch < kMaxMuonTrackingChambers; ch++) {
518       cout << "chamber(0...): " << ch
519            << "  NHitsForRec: " << fNHitsForRecPerChamber[ch]
520            << "  index(first HitForRec): " << fIndexOfFirstHitForRecPerChamber[ch]
521            << endl;
522       for (Int_t hit = fIndexOfFirstHitForRecPerChamber[ch];
523            hit < fIndexOfFirstHitForRecPerChamber[ch] + fNHitsForRecPerChamber[ch];
524            hit++) {
525         cout << "HitForRec index(0...): " << hit << endl;
526         ((*fHitsForRecPtr)[hit])->Dump();
527       }
528     }
529   }
530   return;
531 }
532
533   //__________________________________________________________________________
534 void AliMUONEventReconstructor::AddHitsForRecFromGEANT(TTree *TH)
535 {
536   // To add to the list of hits for reconstruction
537   // the GEANT signal hits from a hit tree TH.
538   Int_t hitBits, chamBits; //AZ
539   if (fPrintLevel >= 2)
540     cout << "enter AddHitsForRecFromGEANT with TH: " << TH << endl;
541   if (TH == NULL) return;
542   //  AliMUON *pMUON  = (AliMUON*) gAlice->GetModule("MUON"); // necessary ????
543   //AliMUONData * muondata = pMUON->GetMUONData();
544   // Security on MUON ????
545   // See whether it could be the same for signal and background ????
546   // Loop over tracks in tree
547   Int_t ntracks = (Int_t) TH->GetEntries();
548   if (fPrintLevel >= 2)
549     cout << "ntracks: " << ntracks << endl;
550   fMuons = 0; //AZ
551   for (Int_t track = 0; track < ntracks; track++) {
552     fMUONData->ResetHits();
553     TH->GetEvent(track);
554     // Loop over hits
555     Int_t hit = 0;
556     hitBits = 0; // AZ
557     chamBits = 0; // AZ
558     Int_t itrack = track; //AZ
559
560     Int_t ihit, nhits=0;
561       nhits = (Int_t) fMUONData->Hits()->GetEntriesFast();
562       AliMUONHit* mHit=0x0;
563
564       for(ihit=0; ihit<nhits; ihit++) {
565         mHit = static_cast<AliMUONHit*>(fMUONData->Hits()->At(ihit));
566         Int_t ipart = TMath::Abs ((Int_t) mHit->Particle()); //AZ
567         if (NewHitForRecFromGEANT(mHit,track, hit, 1) && ipart == 13
568             //if (NewHitForRecFromGEANT(mHit,itrack-1, hit, 1) && ipart == 13 
569             && itrack <= 2 && !BIT(mHit->Chamber()-1)  ) chamBits |= BIT(mHit->Chamber()-1); //AZ - set bit
570       }
571
572     if (chamBits&3 && chamBits>>2&3 && chamBits>>4&3 && chamBits>>6&3 && 
573         chamBits>>8&3 && ((chamBits>>6&3)==3 || (chamBits>>8&3)==3)) 
574       fMuons += 1; //AZ
575     //if (chamBits&3 && chamBits>>2&3 && chamBits>>4&3 && chamBits>>6&3 && 
576     //      chamBits>>8&3 && ((chamBits>>6&3)==3 || (chamBits>>8&3)==3) && 
577     //      ((chamBits&3)==3 || (chamBits>>2&3)==3)) fMuons += 1;
578   } // end of track loop
579   return;
580 }
581
582   //__________________________________________________________________________
583 void AliMUONEventReconstructor::AddHitsForRecFromBkgGEANT(TTree *TH, TClonesArray *Hits)
584 {
585   // To add to the list of hits for reconstruction
586   // the GEANT background hits from a hit tree TH and a pointer Hits to a hit list.
587   // How to have only one function "AddHitsForRecFromGEANT" ????
588   if (fPrintLevel >= 2)
589     cout << "enter AddHitsForRecFromBkgGEANT with TH: " << TH << endl;
590   if (TH == NULL) return;
591   // Loop over tracks in tree
592   Int_t ntracks = (Int_t) TH->GetEntries();
593   if (fPrintLevel >= 2)
594     cout << "ntracks: " << ntracks << endl;
595   for (Int_t track = 0; track < ntracks; track++) {
596     if (Hits) Hits->Clear();
597     TH->GetEvent(track);
598     // Loop over hits
599     for (Int_t hit = 0; hit < Hits->GetEntriesFast(); hit++) {
600       NewHitForRecFromGEANT((AliMUONHit*) (*Hits)[hit], track, hit, 0);
601     } // end of hit loop
602   } // end of track loop
603   return;
604 }
605
606   //__________________________________________________________________________
607 AliMUONHitForRec* AliMUONEventReconstructor::NewHitForRecFromGEANT(AliMUONHit* Hit, Int_t TrackNumber, Int_t HitNumber, Int_t Signal)
608 {
609   // To make a new hit for reconstruction from a GEANT hit pointed to by "Hit",
610   // with hit number "HitNumber" in the track numbered "TrackNumber",
611   // either from signal ("Signal" = 1) or background ("Signal" = 0) event.
612   // Selects hits in tracking (not trigger) chambers.
613   // Takes into account the efficiency (fEfficiency)
614   // and the smearing from resolution (fBendingResolution and fNonBendingResolution).
615   // Adds a condition on the radius between RMin and RMax
616   // to better simulate the real chambers.
617   // Returns the pointer to the new hit for reconstruction,
618   // or NULL in case of inefficiency or non tracking chamber or bad radius.
619   // No condition on at most 20 cm from a muon from a resonance
620   // like in Fortran TRACKF_STAT.
621   AliMUONHitForRec* hitForRec;
622   Double_t bendCoor, nonBendCoor, radius;
623   Int_t chamber = Hit->Chamber() - 1; // chamber(0...)
624   // only in tracking chambers (fChamber starts at 1)
625   if (chamber >= kMaxMuonTrackingChambers) return NULL;
626   // only if hit is efficient (keep track for checking ????)
627   if (gRandom->Rndm() > fEfficiency) return NULL;
628   // only if radius between RMin and RMax
629   bendCoor = Hit->Y();
630   nonBendCoor = Hit->X();
631   radius = TMath::Sqrt((bendCoor * bendCoor) + (nonBendCoor * nonBendCoor));
632   // This cut is not needed with a realistic chamber geometry !!!!
633 //   if ((radius < fRMin[chamber]) || (radius > fRMax[chamber])) return NULL;
634   // new AliMUONHitForRec from GEANT hit and increment number of AliMUONHitForRec's
635   hitForRec = new ((*fHitsForRecPtr)[fNHitsForRec]) AliMUONHitForRec(Hit);
636   fNHitsForRec++;
637   // add smearing from resolution
638   hitForRec->SetBendingCoor(bendCoor + gRandom->Gaus(0., fBendingResolution));
639   hitForRec->SetNonBendingCoor(nonBendCoor
640                                + gRandom->Gaus(0., fNonBendingResolution));
641 //   // !!!! without smearing
642 //   hitForRec->SetBendingCoor(bendCoor);
643 //   hitForRec->SetNonBendingCoor(nonBendCoor);
644   // more information into HitForRec
645   //  resolution: angular effect to be added here ????
646   hitForRec->SetBendingReso2(fBendingResolution * fBendingResolution);
647   hitForRec->SetNonBendingReso2(fNonBendingResolution * fNonBendingResolution);
648   //  GEANT track info
649   hitForRec->SetHitNumber(HitNumber);
650   hitForRec->SetTHTrack(TrackNumber);
651   hitForRec->SetGeantSignal(Signal);
652   if (fPrintLevel >= 10) {
653     cout << "track: " << TrackNumber << " hit: " << HitNumber << endl;
654     Hit->Dump();
655     cout << "AliMUONHitForRec number (1...): " << fNHitsForRec << endl;
656     hitForRec->Dump();}
657   return hitForRec;
658 }
659
660   //__________________________________________________________________________
661 void AliMUONEventReconstructor::SortHitsForRecWithIncreasingChamber()
662 {
663   // Sort HitsForRec's in increasing order with respect to chamber number.
664   // Uses the function "Compare".
665   // Update the information for HitsForRec per chamber too.
666   Int_t ch, nhits, prevch;
667   fHitsForRecPtr->Sort();
668   for (ch = 0; ch < kMaxMuonTrackingChambers; ch++) {
669     fNHitsForRecPerChamber[ch] = 0;
670     fIndexOfFirstHitForRecPerChamber[ch] = 0;
671   }
672   prevch = 0; // previous chamber
673   nhits = 0; // number of hits in current chamber
674   // Loop over HitsForRec
675   for (Int_t hit = 0; hit < fNHitsForRec; hit++) {
676     // chamber number (0...)
677     ch = ((AliMUONHitForRec*)  ((*fHitsForRecPtr)[hit]))->GetChamberNumber();
678     // increment number of hits in current chamber
679     (fNHitsForRecPerChamber[ch])++;
680     // update index of first HitForRec in current chamber
681     // if chamber number different from previous one
682     if (ch != prevch) {
683       fIndexOfFirstHitForRecPerChamber[ch] = hit;
684       prevch = ch;
685     }
686   }
687   return;
688 }
689
690 //   //__________________________________________________________________________
691 // void AliMUONEventReconstructor::AddHitsForRecFromCathodeCorrelations(TTree* TC)
692 // {
693 //   // OLD VERSION WHEN ONE ONE WAS USING SO CALLED CATHODE CORRELATIONS
694 //   // To add to the list of hits for reconstruction
695 //   // the (cathode correlated) raw clusters
696 //   // No condition added, like in Fortran TRACKF_STAT,
697 //   // on the radius between RMin and RMax.
698 //   AliMUONHitForRec *hitForRec;
699 //   if (fPrintLevel >= 1) cout << "enter AddHitsForRecFromCathodeCorrelations" << endl;
700 //   AliMUON *MUON  = (AliMUON*) gAlice->GetModule("MUON"); // necessary ????
701 //   // Security on MUON ????
702 //   // Loop over tracking chambers
703 //   for (Int_t ch = 0; ch < kMaxMuonTrackingChambers; ch++) {
704 //     // number of HitsForRec to 0 for the chamber
705 //     fNHitsForRecPerChamber[ch] = 0;
706 //     // index of first HitForRec for the chamber
707 //     if (ch == 0) fIndexOfFirstHitForRecPerChamber[ch] = 0;
708 //     else fIndexOfFirstHitForRecPerChamber[ch] = fNHitsForRec;
709 //     TClonesArray *reconst_hits  = MUON->ReconstHitsAddress(ch);
710 //     MUON->ResetReconstHits();
711 //     TC->GetEvent();
712 //     Int_t ncor = (Int_t)reconst_hits->GetEntries();
713 //     // Loop over (cathode correlated) raw clusters
714 //     for (Int_t cor = 0; cor < ncor; cor++) {
715 //       AliMUONReconstHit * mCor = 
716 //      (AliMUONReconstHit*) reconst_hits->UncheckedAt(cor);
717 //       // new AliMUONHitForRec from (cathode correlated) raw cluster
718 //       // and increment number of AliMUONHitForRec's (total and in chamber)
719 //       hitForRec = new ((*fHitsForRecPtr)[fNHitsForRec]) AliMUONHitForRec(mCor);
720 //       fNHitsForRec++;
721 //       (fNHitsForRecPerChamber[ch])++;
722 //       // more information into HitForRec
723 //       hitForRec->SetChamberNumber(ch);
724 //       hitForRec->SetHitNumber(cor);
725 //       // Z coordinate of the chamber (cm) with sign opposite to GEANT sign
726 //       // could (should) be more exact from chamber geometry ???? 
727 //       hitForRec->SetZ(-(&(MUON->Chamber(ch)))->Z());
728 //       if (fPrintLevel >= 10) {
729 //      cout << "chamber (0...): " << ch <<
730 //        " cathcorrel (0...): " << cor << endl;
731 //      mCor->Dump();
732 //      cout << "AliMUONHitForRec number (1...): " << fNHitsForRec << endl;
733 //      hitForRec->Dump();}
734 //     } // end of cluster loop
735 //   } // end of chamber loop
736 //   return;
737 // }
738
739   //__________________________________________________________________________
740 void AliMUONEventReconstructor::AddHitsForRecFromRawClusters(TTree* TR)
741 {
742   // To add to the list of hits for reconstruction all the raw clusters
743   // No condition added, like in Fortran TRACKF_STAT,
744   // on the radius between RMin and RMax.
745   AliMUONHitForRec *hitForRec;
746   AliMUONRawCluster *clus;
747   Int_t iclus, nclus, nTRentries;
748   TClonesArray *rawclusters;
749   if (fPrintLevel >= 1) cout << "enter AddHitsForRecFromRawClusters" << endl;
750
751 //   TString evfoldname = AliConfig::fgkDefaultEventFolderName;//to be interfaced properly
752 //   AliRunLoader* rl = AliRunLoader::GetRunLoader(evfoldname);
753 //   if (rl == 0x0)
754 //    {
755 //      Error("MakeEventToBeReconstructed",
756 //            "Can not find Run Loader in Event Folder named %s.",
757 //            evfoldname.Data());
758 //      return;
759 //    }
760 //   AliLoader* gime = rl->GetLoader("MUONLoader");
761 //   if (gime == 0x0)
762 //    {
763 //      Error("MakeEventToBeReconstructed","Can not get MUON Loader from Run Loader.");
764 //      return;
765 //    }
766 //    // Loading AliRun master
767 //   rl->LoadgAlice();
768 //   gAlice = rl->GetAliRun();
769
770   // Loading MUON subsystem
771   //  AliMUON * pMUON = (AliMUON *) gAlice->GetDetector("MUON");
772
773   nTRentries = Int_t(TR->GetEntries());
774   if (nTRentries != 1) {
775     cout << "Error in AliMUONEventReconstructor::AddHitsForRecFromRawClusters"
776          << endl;
777     cout << "nTRentries = " << nTRentries << " not equal to 1" << endl;
778     exit(0);
779   }
780   fLoader->TreeR()->GetEvent(0); // only one entry  
781
782   // Loop over tracking chambers
783   for (Int_t ch = 0; ch < kMaxMuonTrackingChambers; ch++) {
784     // number of HitsForRec to 0 for the chamber
785     fNHitsForRecPerChamber[ch] = 0;
786     // index of first HitForRec for the chamber
787     if (ch == 0) fIndexOfFirstHitForRecPerChamber[ch] = 0;
788     else fIndexOfFirstHitForRecPerChamber[ch] = fNHitsForRec;
789     rawclusters =fMUONData->RawClusters(ch);
790 //     pMUON->ResetRawClusters();
791 //     TR->GetEvent((Int_t) (TR->GetEntries()) - 1); // to be checked ????
792     nclus = (Int_t) (rawclusters->GetEntries());
793     // Loop over (cathode correlated) raw clusters
794     for (iclus = 0; iclus < nclus; iclus++) {
795       clus = (AliMUONRawCluster*) rawclusters->UncheckedAt(iclus);
796       // new AliMUONHitForRec from raw cluster
797       // and increment number of AliMUONHitForRec's (total and in chamber)
798       hitForRec = new ((*fHitsForRecPtr)[fNHitsForRec]) AliMUONHitForRec(clus);
799       fNHitsForRec++;
800       (fNHitsForRecPerChamber[ch])++;
801       // more information into HitForRec
802       //  resolution: info should be already in raw cluster and taken from it ????
803       hitForRec->SetBendingReso2(fBendingResolution * fBendingResolution);
804       hitForRec->SetNonBendingReso2(fNonBendingResolution * fNonBendingResolution);
805       //  original raw cluster
806       hitForRec->SetChamberNumber(ch);
807       hitForRec->SetHitNumber(iclus);
808       // Z coordinate of the raw cluster (cm)
809       hitForRec->SetZ(clus->fZ[0]);
810       if (fPrintLevel >= 10) {
811         cout << "chamber (0...): " << ch <<
812           " raw cluster (0...): " << iclus << endl;
813         clus->Dump();
814         cout << "AliMUONHitForRec number (1...): " << fNHitsForRec << endl;
815         hitForRec->Dump();}
816     } // end of cluster loop
817   } // end of chamber loop
818   SortHitsForRecWithIncreasingChamber(); //AZ 
819   return;
820 }
821
822   //__________________________________________________________________________
823 void AliMUONEventReconstructor::MakeSegments(void)
824 {
825   // To make the list of segments in all stations,
826   // from the list of hits to be reconstructed
827   if (fPrintLevel >= 1) cout << "enter MakeSegments" << endl;
828   ResetSegments();
829   // Loop over stations
830   Int_t nb = (fTrackMethod == 2) ? 3 : 0; //AZ
831   //AZ for (Int_t st = 0; st < kMaxMuonTrackingStations; st++)
832   for (Int_t st = nb; st < kMaxMuonTrackingStations; st++) //AZ
833     MakeSegmentsPerStation(st); 
834   if (fPrintLevel >= 10) {
835     cout << "end of MakeSegments" << endl;
836     for (Int_t st = 0; st < kMaxMuonTrackingStations; st++) {
837       cout << "station(0...): " << st
838            << "  Segments: " << fNSegments[st]
839            << endl;
840       for (Int_t seg = 0;
841            seg < fNSegments[st];
842            seg++) {
843         cout << "Segment index(0...): " << seg << endl;
844         ((*fSegmentsPtr[st])[seg])->Dump();
845       }
846     }
847   }
848   return;
849 }
850
851   //__________________________________________________________________________
852 void AliMUONEventReconstructor::MakeSegmentsPerStation(Int_t Station)
853 {
854   // To make the list of segments in station number "Station" (0...)
855   // from the list of hits to be reconstructed.
856   // Updates "fNSegments"[Station].
857   // Segments in stations 4 and 5 are sorted
858   // according to increasing absolute value of "impact parameter"
859   AliMUONHitForRec *hit1Ptr, *hit2Ptr;
860   AliMUONSegment *segment;
861   Bool_t last2st;
862   Double_t bendingSlope, distBend, distNonBend, extBendCoor, extNonBendCoor,
863       impactParam = 0., maxImpactParam = 0., minImpactParam = 0.; // =0 to avoid compilation warnings.
864   AliMUON *pMUON  = (AliMUON*) gAlice->GetModule("MUON"); // necessary ????
865   if (fPrintLevel >= 1)
866     cout << "enter MakeSegmentsPerStation (0...) " << Station << endl;
867   // first and second chambers (0...) in the station
868   Int_t ch1 = 2 * Station;
869   Int_t ch2 = ch1 + 1;
870   // variable true for stations downstream of the dipole:
871   // Station(0..4) equal to 3 or 4
872   if ((Station == 3) || (Station == 4)) {
873     last2st = kTRUE;
874     // maximum impact parameter (cm) according to fMinBendingMomentum...
875     maxImpactParam =
876       TMath::Abs(GetImpactParamFromBendingMomentum(fMinBendingMomentum));
877     // minimum impact parameter (cm) according to fMaxBendingMomentum...
878     minImpactParam =
879       TMath::Abs(GetImpactParamFromBendingMomentum(fMaxBendingMomentum));
880   }
881   else last2st = kFALSE;
882   // extrapolation factor from Z of first chamber to Z of second chamber
883   // dZ to be changed to take into account fine structure of chambers ????
884   Double_t extrapFact =
885     (&(pMUON->Chamber(ch2)))->Z() / (&(pMUON->Chamber(ch1)))->Z();
886   // index for current segment
887   Int_t segmentIndex = 0;
888   // Loop over HitsForRec in the first chamber of the station
889   for (Int_t hit1 = fIndexOfFirstHitForRecPerChamber[ch1];
890        hit1 < fIndexOfFirstHitForRecPerChamber[ch1] + fNHitsForRecPerChamber[ch1];
891        hit1++) {
892     // pointer to the HitForRec
893     hit1Ptr = (AliMUONHitForRec*) ((*fHitsForRecPtr)[hit1]);
894     // extrapolation,
895     // on the straight line joining the HitForRec to the vertex (0,0,0),
896     // to the Z of the second chamber of the station
897     extBendCoor = extrapFact * hit1Ptr->GetBendingCoor();
898     extNonBendCoor = extrapFact * hit1Ptr->GetNonBendingCoor();
899     // Loop over HitsForRec in the second chamber of the station
900     for (Int_t hit2 = fIndexOfFirstHitForRecPerChamber[ch2];
901          hit2 < fIndexOfFirstHitForRecPerChamber[ch2] + fNHitsForRecPerChamber[ch2];
902          hit2++) {
903       // pointer to the HitForRec
904       hit2Ptr = (AliMUONHitForRec*) ((*fHitsForRecPtr)[hit2]);
905       // absolute values of distances, in bending and non bending planes,
906       // between the HitForRec in the second chamber
907       // and the previous extrapolation
908       distBend = TMath::Abs(hit2Ptr->GetBendingCoor() - extBendCoor);
909       distNonBend = TMath::Abs(hit2Ptr->GetNonBendingCoor() - extNonBendCoor);
910       if (last2st) {
911         // bending slope
912         bendingSlope = (hit1Ptr->GetBendingCoor() - hit2Ptr->GetBendingCoor()) /
913           (hit1Ptr->GetZ() - hit2Ptr->GetZ());
914         // absolute value of impact parameter
915         impactParam =
916           TMath::Abs(hit1Ptr->GetBendingCoor() - hit1Ptr->GetZ() * bendingSlope);
917       }
918       // check for distances not too large,
919       // and impact parameter not too big if stations downstream of the dipole.
920       // Conditions "distBend" and "impactParam" correlated for these stations ????
921       if ((distBend < fSegmentMaxDistBending[Station]) &&
922           (distNonBend < fSegmentMaxDistNonBending[Station]) &&
923           (!last2st || (impactParam < maxImpactParam)) &&
924           (!last2st || (impactParam > minImpactParam))) {
925         // make new segment
926         segment = new ((*fSegmentsPtr[Station])[segmentIndex])
927           AliMUONSegment(hit1Ptr, hit2Ptr);
928         // update "link" to this segment from the hit in the first chamber
929         if (hit1Ptr->GetNSegments() == 0)
930           hit1Ptr->SetIndexOfFirstSegment(segmentIndex);
931         hit1Ptr->SetNSegments(hit1Ptr->GetNSegments() + 1);
932         if (fPrintLevel >= 10) {
933           cout << "segmentIndex(0...): " << segmentIndex
934                << "  distBend: " << distBend
935                << "  distNonBend: " << distNonBend
936                << endl;
937           segment->Dump();
938           cout << "HitForRec in first chamber" << endl;
939           hit1Ptr->Dump();
940           cout << "HitForRec in second chamber" << endl;
941           hit2Ptr->Dump();
942         };
943         // increment index for current segment
944         segmentIndex++;
945       }
946     } //for (Int_t hit2
947   } // for (Int_t hit1...
948   fNSegments[Station] = segmentIndex;
949   // Sorting according to "impact parameter" if station(1..5) 4 or 5,
950   // i.e. Station(0..4) 3 or 4, using the function "Compare".
951   // After this sorting, it is impossible to use
952   // the "fNSegments" and "fIndexOfFirstSegment"
953   // of the HitForRec in the first chamber to explore all segments formed with it.
954   // Is this sorting really needed ????
955   if ((Station == 3) || (Station == 4)) (fSegmentsPtr[Station])->Sort();
956   if (fPrintLevel >= 1) cout << "Station: " << Station << "  NSegments: "
957                              << fNSegments[Station] << endl;
958   return;
959 }
960
961   //__________________________________________________________________________
962 void AliMUONEventReconstructor::MakeTracks(void)
963 {
964   // To make the tracks,
965   // from the list of segments and points in all stations
966   if (fPrintLevel >= 1) cout << "enter MakeTracks" << endl;
967   // The order may be important for the following Reset's
968   ResetTracks();
969   ResetTrackHits();
970   if (fTrackMethod == 2) { //AZ - Kalman filter
971     MakeTrackCandidatesK();
972     // Follow tracks in stations(1..) 3, 2 and 1
973     FollowTracksK();
974     // Remove double tracks
975     RemoveDoubleTracksK();
976     // Propagate tracks to the vertex thru absorber
977     GoToVertex();
978   } else { 
979     // Look for candidates from at least 3 aligned points in stations(1..) 4 and 5
980     MakeTrackCandidates();
981     // Follow tracks in stations(1..) 3, 2 and 1
982     FollowTracks();
983     // Remove double tracks
984     RemoveDoubleTracks();
985     UpdateTrackParamAtHit();
986   }
987   return;
988 }
989
990   //__________________________________________________________________________
991 void AliMUONEventReconstructor::ValidateTracksWithTrigger(void)
992 {
993   AliMUONTrack *track;
994   TClonesArray *recTriggerTracks = fMUONData->RecTriggerTracks();
995   
996   track = (AliMUONTrack*) fRecTracksPtr->First();
997   while (track) {
998     track->MatchTriggerTrack(recTriggerTracks);
999     track = (AliMUONTrack*) fRecTracksPtr->After(track);
1000   } 
1001 }
1002
1003   //__________________________________________________________________________
1004 Bool_t AliMUONEventReconstructor::MakeTriggerTracks(void)
1005 {
1006     // To make the trigger tracks from Local Trigger
1007     if (fPrintLevel >= 1) cout << "enter MakeTriggerTracks" << endl;
1008     //    ResetTriggerTracks();
1009     
1010     Int_t nTRentries;
1011     Long_t gloTrigPat;
1012     TClonesArray *localTrigger;
1013     TClonesArray *globalTrigger;
1014     AliMUONLocalTrigger *locTrg;
1015     AliMUONGlobalTrigger *gloTrg;
1016     AliMUONTriggerCircuit *circuit;
1017     AliMUONTriggerTrack *recTriggerTrack = 0;
1018
1019     TTree* TR = fLoader->TreeR();
1020     
1021     // Loading MUON subsystem
1022     AliMUON * pMUON = (AliMUON *) gAlice->GetDetector("MUON");
1023     
1024     nTRentries = Int_t(TR->GetEntries());
1025      
1026     TR->GetEvent(0); // only one entry  
1027
1028     if (!(fMUONData->IsTriggerBranchesInTree())) {
1029       cout << "Warning in AliMUONEventReconstructor::MakeTriggerTracks"
1030            << endl;
1031       cout << "Trigger information is not avalaible, nTRentries = " << nTRentries << " not equal to 1" << endl;
1032       return kFALSE;
1033     }
1034
1035     fMUONData->SetTreeAddress("GLT");
1036     fMUONData->GetTrigger();
1037
1038     // global trigger for trigger pattern
1039     gloTrigPat = 0;
1040     globalTrigger = fMUONData->GlobalTrigger(); 
1041     gloTrg = (AliMUONGlobalTrigger*)globalTrigger->UncheckedAt(0);      
1042     if (gloTrg->SinglePlusLpt())  gloTrigPat|= 0x1;
1043     if (gloTrg->SinglePlusHpt())  gloTrigPat|= 0x2;
1044     if (gloTrg->SinglePlusApt())  gloTrigPat|= 0x4;
1045  
1046     if (gloTrg->SingleMinusLpt()) gloTrigPat|= 0x8;
1047     if (gloTrg->SingleMinusHpt()) gloTrigPat|= 0x10;
1048     if (gloTrg->SingleMinusApt()) gloTrigPat|= 0x20;
1049  
1050     if (gloTrg->SingleUndefLpt()) gloTrigPat|= 0x40;
1051     if (gloTrg->SingleUndefHpt()) gloTrigPat|= 0x80;
1052     if (gloTrg->SingleUndefApt()) gloTrigPat|= 0x100;
1053  
1054     if (gloTrg->PairUnlikeLpt())  gloTrigPat|= 0x200;
1055     if (gloTrg->PairUnlikeHpt())  gloTrigPat|= 0x400;
1056     if (gloTrg->PairUnlikeApt())  gloTrigPat|= 0x800;
1057
1058     if (gloTrg->PairLikeLpt())    gloTrigPat|= 0x1000;
1059     if (gloTrg->PairLikeHpt())    gloTrigPat|= 0x2000;
1060     if (gloTrg->PairLikeApt())    gloTrigPat|= 0x4000;
1061
1062  
1063
1064     // local trigger for tracking 
1065     localTrigger = fMUONData->LocalTrigger();    
1066     Int_t nlocals = (Int_t) (localTrigger->GetEntries());
1067     Float_t z11 = ( &(pMUON->Chamber(10)) )->Z();
1068     Float_t z21 = ( &(pMUON->Chamber(12)) )->Z();
1069
1070     for (Int_t i=0; i<nlocals; i++) { // loop on Local Trigger
1071       locTrg = (AliMUONLocalTrigger*)localTrigger->UncheckedAt(i);      
1072       circuit = &(pMUON->TriggerCircuit(locTrg->LoCircuit()));
1073       Float_t y11 = circuit->GetY11Pos(locTrg->LoStripX()); 
1074       Int_t stripX21 = locTrg->LoStripX()+locTrg->LoDev()+1;
1075       Float_t y21 = circuit->GetY21Pos(stripX21);       
1076       Float_t x11 = circuit->GetX11Pos(locTrg->LoStripY());
1077       Float_t thetax = TMath::ATan2( x11 , z11 );
1078       Float_t thetay = TMath::ATan2( (y21-y11) , (z21-z11) );
1079
1080       recTriggerTrack = new AliMUONTriggerTrack(x11,y11,thetax,thetay,gloTrigPat,this);
1081       // since static statement does not work, set gloTrigPat for each track
1082
1083       //        fNRecTriggerTracks++;
1084       fMUONData->AddRecTriggerTrack(*recTriggerTrack);
1085     } // end of loop on Local Trigger
1086     return kTRUE;    
1087 }
1088
1089   //__________________________________________________________________________
1090 Int_t AliMUONEventReconstructor::MakeTrackCandidatesWithTwoSegments(AliMUONSegment *BegSegment)
1091 {
1092   // To make track candidates with two segments in stations(1..) 4 and 5,
1093   // the first segment being pointed to by "BegSegment".
1094   // Returns the number of such track candidates.
1095   Int_t endStation, iEndSegment, nbCan2Seg;
1096   AliMUONSegment *endSegment, *extrapSegment;
1097   AliMUONTrack *recTrack;
1098   Double_t mcsFactor;
1099   if (fPrintLevel >= 1) cout << "enter MakeTrackCandidatesWithTwoSegments" << endl;
1100   // Station for the end segment
1101   endStation = 7 - (BegSegment->GetHitForRec1())->GetChamberNumber() / 2;
1102   // multiple scattering factor corresponding to one chamber
1103   mcsFactor = 0.0136 /
1104     GetBendingMomentumFromImpactParam(BegSegment->GetBendingImpact());
1105   mcsFactor     = fChamberThicknessInX0 * mcsFactor * mcsFactor;
1106   // linear extrapolation to end station
1107   extrapSegment =
1108     BegSegment->CreateSegmentFromLinearExtrapToStation(endStation, mcsFactor);
1109   // number of candidates with 2 segments to 0
1110   nbCan2Seg = 0;
1111   // Loop over segments in the end station
1112   for (iEndSegment = 0; iEndSegment < fNSegments[endStation]; iEndSegment++) {
1113     // pointer to segment
1114     endSegment = (AliMUONSegment*) ((*fSegmentsPtr[endStation])[iEndSegment]);
1115     // test compatibility between current segment and "extrapSegment"
1116     // 4 because 4 quantities in chi2
1117     if ((endSegment->
1118          NormalizedChi2WithSegment(extrapSegment,
1119                                    fMaxSigma2Distance)) <= 4.0) {
1120       // both segments compatible:
1121       // make track candidate from "begSegment" and "endSegment"
1122       if (fPrintLevel >= 2)
1123         cout << "TrackCandidate with Segment " << iEndSegment <<
1124           " in Station(0..) " << endStation << endl;
1125       // flag for both segments in one track:
1126       // to be done in track constructor ????
1127       BegSegment->SetInTrack(kTRUE);
1128       endSegment->SetInTrack(kTRUE);
1129       recTrack = new ((*fRecTracksPtr)[fNRecTracks])
1130         AliMUONTrack(BegSegment, endSegment, this);
1131       fNRecTracks++;
1132       if (fPrintLevel >= 10) recTrack->RecursiveDump();
1133       // increment number of track candidates with 2 segments
1134       nbCan2Seg++;
1135     }
1136   } // for (iEndSegment = 0;...
1137   delete extrapSegment; // should not delete HitForRec's it points to !!!!
1138   return nbCan2Seg;
1139 }
1140
1141   //__________________________________________________________________________
1142 Int_t AliMUONEventReconstructor::MakeTrackCandidatesWithOneSegmentAndOnePoint(AliMUONSegment *BegSegment)
1143 {
1144   // To make track candidates with one segment and one point
1145   // in stations(1..) 4 and 5,
1146   // the segment being pointed to by "BegSegment".
1147   Int_t ch, ch1, ch2, endStation, iHit, iHitMax, iHitMin, nbCan1Seg1Hit;
1148   AliMUONHitForRec *extrapHitForRec, *hit;
1149   AliMUONTrack *recTrack;
1150   Double_t mcsFactor;
1151   if (fPrintLevel >= 1)
1152     cout << "enter MakeTrackCandidatesWithOneSegmentAndOnePoint" << endl;
1153   // station for the end point
1154   endStation = 7 - (BegSegment->GetHitForRec1())->GetChamberNumber() / 2;
1155   // multiple scattering factor corresponding to one chamber
1156   mcsFactor = 0.0136 /
1157     GetBendingMomentumFromImpactParam(BegSegment->GetBendingImpact());
1158   mcsFactor     = fChamberThicknessInX0 * mcsFactor * mcsFactor;
1159   // first and second chambers(0..) in the end station
1160   ch1 = 2 * endStation;
1161   ch2 = ch1 + 1;
1162   // number of candidates to 0
1163   nbCan1Seg1Hit = 0;
1164   // Loop over chambers of the end station
1165   for (ch = ch2; ch >= ch1; ch--) {
1166     // linear extrapolation to chamber
1167     extrapHitForRec =
1168       BegSegment->CreateHitForRecFromLinearExtrapToChamber(ch, mcsFactor);
1169     // limits for the hit index in the loop
1170     iHitMin = fIndexOfFirstHitForRecPerChamber[ch];
1171     iHitMax = iHitMin + fNHitsForRecPerChamber[ch];
1172     // Loop over HitForRec's in the chamber
1173     for (iHit = iHitMin; iHit < iHitMax; iHit++) {
1174       // pointer to HitForRec
1175       hit = (AliMUONHitForRec*) ((*fHitsForRecPtr)[iHit]);
1176       // test compatibility between current HitForRec and "extrapHitForRec"
1177       // 2 because 2 quantities in chi2
1178       if ((hit->
1179            NormalizedChi2WithHitForRec(extrapHitForRec,
1180                                        fMaxSigma2Distance)) <= 2.0) {
1181         // both HitForRec's compatible:
1182         // make track candidate from begSegment and current HitForRec
1183         if (fPrintLevel >= 2)
1184           cout << "TrackCandidate with HitForRec " << iHit <<
1185             " in Chamber(0..) " << ch << endl;
1186         // flag for beginning segments in one track:
1187         // to be done in track constructor ????
1188         BegSegment->SetInTrack(kTRUE);
1189         recTrack = new ((*fRecTracksPtr)[fNRecTracks])
1190           AliMUONTrack(BegSegment, hit, this);
1191         // the right place to eliminate "double counting" ???? how ????
1192         fNRecTracks++;
1193         if (fPrintLevel >= 10) recTrack->RecursiveDump();
1194         // increment number of track candidates
1195         nbCan1Seg1Hit++;
1196       }
1197     } // for (iHit = iHitMin;...
1198     delete extrapHitForRec;
1199   } // for (ch = ch2;...
1200   return nbCan1Seg1Hit;
1201 }
1202
1203   //__________________________________________________________________________
1204 void AliMUONEventReconstructor::MakeTrackCandidates(void)
1205 {
1206   // To make track candidates
1207   // with at least 3 aligned points in stations(1..) 4 and 5
1208   // (two Segment's or one Segment and one HitForRec)
1209   Int_t begStation, iBegSegment, nbCan1Seg1Hit, nbCan2Seg;
1210   AliMUONSegment *begSegment;
1211   if (fPrintLevel >= 1) cout << "enter MakeTrackCandidates" << endl;
1212   // Loop over stations(1..) 5 and 4 for the beginning segment
1213   for (begStation = 4; begStation > 2; begStation--) {
1214     // Loop over segments in the beginning station
1215     for (iBegSegment = 0; iBegSegment < fNSegments[begStation]; iBegSegment++) {
1216       // pointer to segment
1217       begSegment = (AliMUONSegment*) ((*fSegmentsPtr[begStation])[iBegSegment]);
1218       if (fPrintLevel >= 2)
1219         cout << "look for TrackCandidate's with Segment " << iBegSegment <<
1220           " in Station(0..) " << begStation << endl;
1221       // Look for track candidates with two segments,
1222       // "begSegment" and all compatible segments in other station.
1223       // Only for beginning station(1..) 5
1224       // because candidates with 2 segments have to looked for only once.
1225       if (begStation == 4)
1226         nbCan2Seg = MakeTrackCandidatesWithTwoSegments(begSegment);
1227       // Look for track candidates with one segment and one point,
1228       // "begSegment" and all compatible HitForRec's in other station.
1229       // Only if "begSegment" does not belong already to a track candidate.
1230       // Is that a too strong condition ????
1231       if (!(begSegment->GetInTrack()))
1232         nbCan1Seg1Hit = MakeTrackCandidatesWithOneSegmentAndOnePoint(begSegment);
1233     } // for (iBegSegment = 0;...
1234   } // for (begStation = 4;...
1235   return;
1236 }
1237
1238   //__________________________________________________________________________
1239 void AliMUONEventReconstructor::FollowTracks(void)
1240 {
1241   // Follow tracks in stations(1..) 3, 2 and 1
1242   // too long: should be made more modular !!!!
1243   AliMUONHitForRec *bestHit, *extrapHit, *extrapCorrHit, *hit;
1244   AliMUONSegment *bestSegment, *extrapSegment, *extrapCorrSegment, *segment;
1245   AliMUONTrack *track, *nextTrack;
1246   AliMUONTrackParam *trackParam1, trackParam[2], trackParamVertex;
1247   // -1 to avoid compilation warnings
1248   Int_t ch = -1, chInStation, chBestHit = -1, iHit, iSegment, station, trackIndex; 
1249   Double_t bestChi2, chi2, dZ1, dZ2, dZ3, maxSigma2Distance, mcsFactor;
1250   Double_t bendingMomentum, chi2Norm = 0.;
1251   AliMUON *pMUON = (AliMUON*) gAlice->GetModule("MUON"); // necessary ????
1252   // local maxSigma2Distance, for easy increase in testing
1253   maxSigma2Distance = fMaxSigma2Distance;
1254   if (fPrintLevel >= 2)
1255     cout << "enter FollowTracks" << endl;
1256   // Loop over track candidates
1257   track = (AliMUONTrack*) fRecTracksPtr->First();
1258   trackIndex = -1;
1259   while (track) {
1260     // Follow function for each track candidate ????
1261     trackIndex++;
1262     nextTrack = (AliMUONTrack*) fRecTracksPtr->After(track); // prepare next track
1263     if (fPrintLevel >= 2)
1264       cout << "FollowTracks: track candidate(0..): " << trackIndex << endl;
1265     // Fit track candidate
1266     track->SetFitMCS(0); // without multiple Coulomb scattering
1267     track->SetFitNParam(3); // with 3 parameters (X = Y = 0)
1268     track->SetFitStart(0); // from parameters at vertex
1269     track->Fit();
1270     if (fPrintLevel >= 10) {
1271       cout << "FollowTracks: track candidate(0..): " << trackIndex
1272            << " after fit in stations(0..) 3 and 4" << endl;
1273       track->RecursiveDump();
1274     }
1275     // Loop over stations(1..) 3, 2 and 1
1276     // something SPECIAL for stations 2 and 1 for majority 3 coincidence ????
1277     // otherwise: majority coincidence 2 !!!!
1278     for (station = 2; station >= 0; station--) {
1279       // Track parameters at first track hit (smallest Z)
1280       trackParam1 = ((AliMUONTrackHit*)
1281                      (track->GetTrackHitsPtr()->First()))->GetTrackParam();
1282       // extrapolation to station
1283       trackParam1->ExtrapToStation(station, trackParam);
1284       extrapSegment = new AliMUONSegment(); //  empty segment
1285       extrapCorrSegment = new AliMUONSegment(); //  empty corrected segment
1286       // multiple scattering factor corresponding to one chamber
1287       // and momentum in bending plane (not total)
1288       mcsFactor = 0.0136 * trackParam1->GetInverseBendingMomentum();
1289       mcsFactor = fChamberThicknessInX0 * mcsFactor * mcsFactor;
1290       // Z difference from previous station
1291       dZ1 = (&(pMUON->Chamber(2 * station)))->Z() -
1292         (&(pMUON->Chamber(2 * station + 2)))->Z();
1293       // Z difference between the two previous stations
1294       dZ2 = (&(pMUON->Chamber(2 * station + 2)))->Z() -
1295         (&(pMUON->Chamber(2 * station + 4)))->Z();
1296       // Z difference between the two chambers in the previous station
1297       dZ3 = (&(pMUON->Chamber(2 * station)))->Z() -
1298         (&(pMUON->Chamber(2 * station + 1)))->Z();
1299       extrapSegment->SetBendingCoorReso2(fBendingResolution * fBendingResolution);
1300       extrapSegment->
1301         SetNonBendingCoorReso2(fNonBendingResolution * fNonBendingResolution);
1302       extrapSegment->UpdateFromStationTrackParam
1303         (trackParam, mcsFactor, dZ1, dZ2, dZ3, station,
1304          trackParam1->GetInverseBendingMomentum());
1305       // same thing for corrected segment
1306       // better to use copy constructor, after checking that it works properly !!!!
1307       extrapCorrSegment->SetBendingCoorReso2(fBendingResolution * fBendingResolution);
1308       extrapCorrSegment->
1309         SetNonBendingCoorReso2(fNonBendingResolution * fNonBendingResolution);
1310       extrapCorrSegment->UpdateFromStationTrackParam
1311         (trackParam, mcsFactor, dZ1, dZ2, dZ3, station,
1312          trackParam1->GetInverseBendingMomentum());
1313       bestChi2 = 5.0;
1314       bestSegment = NULL;
1315       if (fPrintLevel >= 10) {
1316         cout << "FollowTracks: track candidate(0..): " << trackIndex
1317              << " Look for segment in station(0..): " << station << endl;
1318       }
1319       // Loop over segments in station
1320       for (iSegment = 0; iSegment < fNSegments[station]; iSegment++) {
1321         // Look for best compatible Segment in station
1322         // should consider all possibilities ????
1323         // multiple scattering ????
1324         // separation in 2 functions: Segment and HitForRec ????
1325         segment = (AliMUONSegment*) ((*fSegmentsPtr[station])[iSegment]);
1326         // correction of corrected segment (fBendingCoor and fNonBendingCoor)
1327         // according to real Z value of "segment" and slopes of "extrapSegment"
1328         extrapCorrSegment->
1329           SetBendingCoor(extrapSegment->GetBendingCoor() +
1330                          extrapSegment->GetBendingSlope() *
1331                          (segment->GetHitForRec1()->GetZ() -
1332                           (&(pMUON->Chamber(2 * station)))->Z()));
1333         extrapCorrSegment->
1334           SetNonBendingCoor(extrapSegment->GetNonBendingCoor() +
1335                             extrapSegment->GetNonBendingSlope() *
1336                             (segment->GetHitForRec1()->GetZ() -
1337                              (&(pMUON->Chamber(2 * station)))->Z()));
1338         chi2 = segment->
1339           NormalizedChi2WithSegment(extrapCorrSegment, maxSigma2Distance);
1340         if (chi2 < bestChi2) {
1341           // update best Chi2 and Segment if better found
1342           bestSegment = segment;
1343           bestChi2 = chi2;
1344         }
1345       }
1346       if (bestSegment) {
1347         // best segment found: add it to track candidate
1348         track->AddSegment(bestSegment);
1349         // set track parameters at these two TrakHit's
1350         track->SetTrackParamAtHit(track->GetNTrackHits() - 2, &(trackParam[0]));
1351         track->SetTrackParamAtHit(track->GetNTrackHits() - 1, &(trackParam[1]));
1352         if (fPrintLevel >= 10) {
1353           cout << "FollowTracks: track candidate(0..): " << trackIndex
1354                << " Added segment in station(0..): " << station << endl;
1355           track->RecursiveDump();
1356         }
1357       }
1358       else {
1359         // No best segment found:
1360         // Look for best compatible HitForRec in station:
1361         // should consider all possibilities ????
1362         // multiple scattering ???? do about like for extrapSegment !!!!
1363         extrapHit = new AliMUONHitForRec(); //  empty hit
1364         extrapCorrHit = new AliMUONHitForRec(); //  empty corrected hit
1365         bestChi2 = 3.0;
1366         bestHit = NULL;
1367         if (fPrintLevel >= 10) {
1368           cout << "FollowTracks: track candidate(0..): " << trackIndex
1369                << " Segment not found, look for hit in station(0..): " << station
1370                << endl;
1371         }
1372         // Loop over chambers of the station
1373         for (chInStation = 0; chInStation < 2; chInStation++) {
1374           // coordinates of extrapolated hit
1375           extrapHit->
1376             SetBendingCoor((&(trackParam[chInStation]))->GetBendingCoor());
1377           extrapHit->
1378             SetNonBendingCoor((&(trackParam[chInStation]))->GetNonBendingCoor());
1379           // resolutions from "extrapSegment"
1380           extrapHit->SetBendingReso2(extrapSegment->GetBendingCoorReso2());
1381           extrapHit->SetNonBendingReso2(extrapSegment->GetNonBendingCoorReso2());
1382           // same things for corrected hit
1383           // better to use copy constructor, after checking that it works properly !!!!
1384           extrapCorrHit->
1385             SetBendingCoor((&(trackParam[chInStation]))->GetBendingCoor());
1386           extrapCorrHit->
1387             SetNonBendingCoor((&(trackParam[chInStation]))->GetNonBendingCoor());
1388           extrapHit->SetBendingReso2(extrapSegment->GetBendingCoorReso2());
1389           extrapHit->SetNonBendingReso2(extrapSegment->GetNonBendingCoorReso2());
1390           // Loop over hits in the chamber
1391           ch = 2 * station + chInStation;
1392           for (iHit = fIndexOfFirstHitForRecPerChamber[ch];
1393                iHit < fIndexOfFirstHitForRecPerChamber[ch] +
1394                  fNHitsForRecPerChamber[ch];
1395                iHit++) {
1396             hit = (AliMUONHitForRec*) ((*fHitsForRecPtr)[iHit]);
1397             // correction of corrected hit (fBendingCoor and fNonBendingCoor)
1398             // according to real Z value of "hit" and slopes of right "trackParam"
1399             extrapCorrHit->
1400               SetBendingCoor((&(trackParam[chInStation]))->GetBendingCoor() +
1401                              (&(trackParam[chInStation]))->GetBendingSlope() *
1402                              (hit->GetZ() -
1403                               (&(trackParam[chInStation]))->GetZ()));
1404             extrapCorrHit->
1405               SetNonBendingCoor((&(trackParam[chInStation]))->GetNonBendingCoor() +
1406                                 (&(trackParam[chInStation]))->GetNonBendingSlope() *
1407                                 (hit->GetZ() -
1408                                  (&(trackParam[chInStation]))->GetZ()));
1409             // condition for hit not already in segment ????
1410             chi2 = hit->NormalizedChi2WithHitForRec(extrapHit, maxSigma2Distance);
1411             if (chi2 < bestChi2) {
1412               // update best Chi2 and HitForRec if better found
1413               bestHit = hit;
1414               bestChi2 = chi2;
1415               chBestHit = chInStation;
1416             }
1417           }
1418         }
1419         if (bestHit) {
1420           // best hit found: add it to track candidate
1421           track->AddHitForRec(bestHit);
1422           // set track parameters at this TrackHit
1423           track->SetTrackParamAtHit(track->GetNTrackHits() - 1,
1424                                     &(trackParam[chBestHit]));
1425           if (fPrintLevel >= 10) {
1426             cout << "FollowTracks: track candidate(0..): " << trackIndex
1427                  << " Added hit in station(0..): " << station << endl;
1428             track->RecursiveDump();
1429           }
1430         }
1431         else {
1432           // Remove current track candidate
1433           // and corresponding TrackHit's, ...
1434           track->Remove();
1435           delete extrapSegment;
1436           delete extrapCorrSegment;
1437           delete extrapHit;
1438           delete extrapCorrHit;
1439           break; // stop the search for this candidate:
1440           // exit from the loop over station
1441         }
1442         delete extrapHit;
1443         delete extrapCorrHit;
1444       }
1445       delete extrapSegment;
1446       delete extrapCorrSegment;
1447       // Sort track hits according to increasing Z
1448       track->GetTrackHitsPtr()->Sort();
1449       // Update track parameters at first track hit (smallest Z)
1450       trackParam1 = ((AliMUONTrackHit*)
1451                      (track->GetTrackHitsPtr()->First()))->GetTrackParam();
1452       bendingMomentum = 0.;
1453       if (TMath::Abs(trackParam1->GetInverseBendingMomentum()) > 0.)
1454         bendingMomentum = TMath::Abs(1/(trackParam1->GetInverseBendingMomentum()));
1455       // Track removed if bendingMomentum not in window [min, max]
1456       if ((bendingMomentum < fMinBendingMomentum) || (bendingMomentum > fMaxBendingMomentum)) {
1457         track->Remove();
1458         break; // stop the search for this candidate:
1459         // exit from the loop over station 
1460       }
1461       // Track fit
1462       // with multiple Coulomb scattering if all stations
1463       if (station == 0) track->SetFitMCS(1);
1464       // without multiple Coulomb scattering if not all stations
1465       else track->SetFitMCS(0);
1466       track->SetFitNParam(5);  // with 5 parameters (momentum and position)
1467       track->SetFitStart(1);  // from parameters at first hit
1468       track->Fit();
1469       Double_t numberOfDegFree = (2.0 * track->GetNTrackHits() - 5);
1470       if (numberOfDegFree > 0) {
1471         chi2Norm =  track->GetFitFMin() / numberOfDegFree;
1472       } else {
1473         chi2Norm = 1.e10;
1474       }
1475       // Track removed if normalized chi2 too high
1476       if (chi2Norm > fMaxChi2) {
1477         track->Remove();
1478         break; // stop the search for this candidate:
1479         // exit from the loop over station 
1480       }
1481       if (fPrintLevel >= 10) {
1482         cout << "FollowTracks: track candidate(0..): " << trackIndex
1483              << " after fit from station(0..): " << station << " to 4" << endl;
1484         track->RecursiveDump();
1485       }
1486       // Track extrapolation to the vertex through the absorber (Branson)
1487       // after going through the first station
1488       if (station == 0) {
1489         trackParamVertex = *trackParam1;
1490         (&trackParamVertex)->ExtrapToVertex();
1491         track->SetTrackParamAtVertex(&trackParamVertex);
1492         if (fPrintLevel >= 1) {
1493           cout << "FollowTracks: track candidate(0..): " << trackIndex
1494                << " after extrapolation to vertex" << endl;
1495           track->RecursiveDump();
1496         }
1497       }
1498     } // for (station = 2;...
1499     // go really to next track
1500     track = nextTrack;
1501   } // while (track)
1502   // Compression of track array (necessary after Remove ????)
1503   fRecTracksPtr->Compress();
1504   return;
1505 }
1506
1507   //__________________________________________________________________________
1508 void AliMUONEventReconstructor::RemoveDoubleTracks(void)
1509 {
1510   // To remove double tracks.
1511   // Tracks are considered identical
1512   // if they have at least half of their hits in common.
1513   // Among two identical tracks, one keeps the track with the larger number of hits
1514   // or, if these numbers are equal, the track with the minimum Chi2.
1515   AliMUONTrack *track1, *track2, *trackToRemove;
1516   Bool_t identicalTracks;
1517   Int_t hitsInCommon, nHits1, nHits2;
1518   identicalTracks = kTRUE;
1519   while (identicalTracks) {
1520     identicalTracks = kFALSE;
1521     // Loop over first track of the pair
1522     track1 = (AliMUONTrack*) fRecTracksPtr->First();
1523     while (track1 && (!identicalTracks)) {
1524       nHits1 = track1->GetNTrackHits();
1525       // Loop over second track of the pair
1526       track2 = (AliMUONTrack*) fRecTracksPtr->After(track1);
1527       while (track2 && (!identicalTracks)) {
1528         nHits2 = track2->GetNTrackHits();
1529         // number of hits in common between two tracks
1530         hitsInCommon = track1->HitsInCommon(track2);
1531         // check for identical tracks
1532         if ((4 * hitsInCommon) >= (nHits1 + nHits2)) {
1533           identicalTracks = kTRUE;
1534           // decide which track to remove
1535           if (nHits1 > nHits2) trackToRemove = track2;
1536           else if (nHits1 < nHits2) trackToRemove = track1;
1537           else if ((track1->GetFitFMin()) < (track2->GetFitFMin()))
1538             trackToRemove = track2;
1539           else trackToRemove = track1;
1540           // remove it
1541           trackToRemove->Remove();
1542         }
1543         track2 = (AliMUONTrack*) fRecTracksPtr->After(track2);
1544       } // track2
1545       track1 = (AliMUONTrack*) fRecTracksPtr->After(track1);
1546     } // track1
1547   }
1548   return;
1549 }
1550
1551   //__________________________________________________________________________
1552 void AliMUONEventReconstructor::UpdateTrackParamAtHit()
1553 {
1554   // Set track parameters after track fitting. Fill fTrackParamAtHit of AliMUONTrack's
1555   AliMUONTrack *track;
1556   AliMUONTrackHit *trackHit;
1557   AliMUONTrackParam *trackParam;
1558   track = (AliMUONTrack*) fRecTracksPtr->First();
1559   while (track) {
1560     trackHit = (AliMUONTrackHit*) (track->GetTrackHitsPtr())->First();
1561     while (trackHit) {
1562       trackParam = trackHit->GetTrackParam();
1563       track->AddTrackParamAtHit(trackParam);
1564       trackHit = (AliMUONTrackHit*) (track->GetTrackHitsPtr())->After(trackHit); 
1565     } // trackHit    
1566     track = (AliMUONTrack*) fRecTracksPtr->After(track);
1567   } // track
1568   return;
1569 }
1570
1571   //__________________________________________________________________________
1572 void AliMUONEventReconstructor::EventDump(void)
1573 {
1574   // Dump reconstructed event (track parameters at vertex and at first hit),
1575   // and the particle parameters
1576
1577   AliMUONTrack *track;
1578   AliMUONTrackParam *trackParam, *trackParam1;
1579   Double_t bendingSlope, nonBendingSlope, pYZ;
1580   Double_t pX, pY, pZ, x, y, z, c;
1581   Int_t np, trackIndex, nTrackHits;
1582  
1583   if (fPrintLevel >= 1) cout << "****** enter EventDump ******" << endl;
1584   if (fPrintLevel >= 1) {
1585     cout << " Number of Reconstructed tracks :" <<  fNRecTracks << endl; 
1586   }
1587   fRecTracksPtr->Compress(); // for simple loop without "Next" since no hole
1588   // Loop over reconstructed tracks
1589   for (trackIndex = 0; trackIndex < fNRecTracks; trackIndex++) {
1590     if (fTrackMethod != 1) continue; //AZ - skip the rest for now
1591     if (fPrintLevel >= 1)
1592       cout << " track number: " << trackIndex << endl;
1593     // function for each track for modularity ????
1594     track = (AliMUONTrack*) ((*fRecTracksPtr)[trackIndex]);
1595     nTrackHits = track->GetNTrackHits();
1596     if (fPrintLevel >= 1)
1597       cout << " number of track hits: " << nTrackHits << endl;
1598     // track parameters at Vertex
1599     trackParam = track->GetTrackParamAtVertex();
1600     x = trackParam->GetNonBendingCoor();
1601     y = trackParam->GetBendingCoor();
1602     z = trackParam->GetZ();
1603     bendingSlope = trackParam->GetBendingSlope();
1604     nonBendingSlope = trackParam->GetNonBendingSlope();
1605     pYZ = 1/TMath::Abs(trackParam->GetInverseBendingMomentum());
1606     pZ = pYZ/TMath::Sqrt(1+bendingSlope*bendingSlope);
1607     pX = pZ * nonBendingSlope;
1608     pY = pZ * bendingSlope;
1609     c = TMath::Sign(1.0, trackParam->GetInverseBendingMomentum());
1610     if (fPrintLevel >= 1)
1611       printf(" track parameters at Vertex z= %f: X= %f Y= %f pX= %f pY= %f pZ= %f c= %f\n",
1612              z, x, y, pX, pY, pZ, c);
1613
1614     // track parameters at first hit
1615     trackParam1 = ((AliMUONTrackHit*)
1616                    (track->GetTrackHitsPtr()->First()))->GetTrackParam();
1617     x = trackParam1->GetNonBendingCoor();
1618     y = trackParam1->GetBendingCoor();
1619     z = trackParam1->GetZ();
1620     bendingSlope = trackParam1->GetBendingSlope();
1621     nonBendingSlope = trackParam1->GetNonBendingSlope();
1622     pYZ = 1/TMath::Abs(trackParam1->GetInverseBendingMomentum());
1623     pZ = pYZ/TMath::Sqrt(1.0 + bendingSlope * bendingSlope);
1624     pX = pZ * nonBendingSlope;
1625     pY = pZ * bendingSlope;
1626     c = TMath::Sign(1.0, trackParam1->GetInverseBendingMomentum());
1627     if (fPrintLevel >= 1)
1628       printf(" track parameters at z= %f: X= %f Y= %f pX= %f pY= %f pZ= %f c= %f\n",
1629              z, x, y, pX, pY, pZ, c);
1630   }
1631   // informations about generated particles
1632   np = gAlice->GetMCApp()->GetNtrack();
1633   printf(" **** number of generated particles: %d  \n", np);
1634   
1635 //    for (Int_t iPart = 0; iPart < np; iPart++) {
1636 //      p = gAlice->Particle(iPart);
1637 //      printf(" particle %d: type= %d px= %f py= %f pz= %f pdg= %d\n",
1638 //         iPart, p->GetPdgCode(), p->Px(), p->Py(), p->Pz(), p->GetPdgCode());    
1639 //    }
1640   return;
1641 }
1642
1643
1644 //__________________________________________________________________________
1645 void AliMUONEventReconstructor::EventDumpTrigger(void)
1646 {
1647   // Dump reconstructed trigger event 
1648   // and the particle parameters
1649     
1650   AliMUONTriggerTrack *triggertrack ;
1651   Int_t nTriggerTracks = fMUONData->RecTriggerTracks()->GetEntriesFast();
1652  
1653   if (fPrintLevel >= 1) {
1654     cout << "****** enter EventDumpTrigger ******" << endl;
1655     cout << " Number of Reconstructed tracks :" <<  nTriggerTracks << endl;
1656   }
1657   // Loop over reconstructed tracks
1658   for (Int_t trackIndex = 0; trackIndex < nTriggerTracks; trackIndex++) {
1659     triggertrack = (AliMUONTriggerTrack*)fMUONData->RecTriggerTracks()->At(trackIndex);
1660       printf(" trigger track number %i x11=%f y11=%f thetax=%f thetay=%f \n",
1661              trackIndex,
1662              triggertrack->GetX11(),triggertrack->GetY11(),
1663              triggertrack->GetThetax(),triggertrack->GetThetay());      
1664   } 
1665 }
1666
1667 //__________________________________________________________________________
1668 void AliMUONEventReconstructor::FillEvent()
1669 {
1670 // Create a new AliMUONRecoEvent, fill its track list, then add it as a
1671 // leaf in the Event branch of TreeRecoEvent tree
1672    cout << "Enter FillEvent() ...\n";
1673
1674    if (!fRecoEvent) {
1675       fRecoEvent = new AliMUONRecoEvent();
1676    } else {
1677       fRecoEvent->Clear();
1678    }
1679    //save current directory
1680    TDirectory *current =  gDirectory;
1681    if (!fTreeFile)  fTreeFile  = new TFile("tree_reco.root", "RECREATE");
1682    if (!fEventTree) fEventTree = new TTree("TreeRecoEvent", "MUON reconstructed events");
1683    //AZif (fRecoEvent->MakeDumpTracks(fRecTracksPtr)) {
1684    if (fRecoEvent->MakeDumpTracks(fMuons, fRecTracksPtr, this)) { //AZ
1685       if (fPrintLevel > 1) fRecoEvent->EventInfo();
1686       TBranch *branch = fEventTree->GetBranch("Event");
1687       if (!branch) branch = fEventTree->Branch("Event", "AliMUONRecoEvent", &fRecoEvent, 64000);
1688       branch->SetAutoDelete();
1689       fTreeFile->cd();
1690       fEventTree->Fill();
1691       fTreeFile->Write();
1692    }
1693    // restore directory
1694    current->cd();
1695 }
1696
1697 //__________________________________________________________________________
1698 void AliMUONEventReconstructor::MakeTrackCandidatesK(void)
1699 {
1700   // To make initial tracks for Kalman filter from the list of segments
1701   Int_t istat, iseg;
1702   AliMUONSegment *segment;
1703   AliMUONTrackK *trackK;
1704
1705   if (fPrintLevel >= 1) cout << "enter MakeTrackCandidatesK" << endl;
1706   // Reset the TClonesArray of reconstructed tracks
1707   if (fRecTracksPtr) fRecTracksPtr->Delete();
1708   // Delete in order that the Track destructors are called,
1709   // hence the space for the TClonesArray of pointers to TrackHit's is freed
1710   fNRecTracks = 0;
1711
1712   AliMUONTrackK a(this, fHitsForRecPtr); // bad idea ???
1713   // Loop over stations(1...) 5 and 4
1714   for (istat=4; istat>=3; istat--) {
1715     // Loop over segments in the station
1716     for (iseg=0; iseg<fNSegments[istat]; iseg++) {
1717       // Transform segments to tracks and evaluate covariance matrix
1718       segment = (AliMUONSegment*) ((*fSegmentsPtr[istat])[iseg]);
1719       trackK = new ((*fRecTracksPtr)[fNRecTracks]) AliMUONTrackK(segment);
1720       fNRecTracks++;
1721     } // for (iseg=0;...)
1722   } // for (istat=4;...)
1723   return;
1724 }
1725
1726 //__________________________________________________________________________
1727 void AliMUONEventReconstructor::FollowTracksK(void)
1728 {
1729   // Follow tracks using Kalman filter
1730   Bool_t Ok;
1731   Int_t icand, ichamBeg, ichamEnd, chamBits;
1732   Double_t zDipole1, zDipole2;
1733   AliMUONTrackK *trackK;
1734   AliMUONHitForRec *hit;
1735   AliMUONRawCluster *clus;
1736   TClonesArray *rawclusters;
1737   AliMUON *pMUON;
1738   clus = 0; rawclusters = 0;
1739
1740   zDipole1 = GetSimpleBPosition() - GetSimpleBLength()/2;
1741   zDipole2 = zDipole1 + GetSimpleBLength();
1742
1743   // Print hits
1744   pMUON  = (AliMUON*) gAlice->GetModule("MUON");
1745   for (Int_t i1=0; i1<fNHitsForRec; i1++) {
1746     hit = (AliMUONHitForRec*) ((*fHitsForRecPtr)[i1]);
1747     //if (hit->GetTHTrack() > 1 || hit->GetGeantSignal() == 0) continue;
1748     /*
1749     cout << " Hit #" << hit->GetChamberNumber() << " ";
1750     cout << hit->GetBendingCoor() << " ";
1751     cout << hit->GetNonBendingCoor() << " ";
1752     cout << hit->GetZ() << " ";
1753     cout << hit->GetGeantSignal() << " ";
1754     cout << hit->GetTHTrack() << endl;
1755     */
1756     /*
1757     printf(" Hit # %d %10.4f %10.4f %10.4f",
1758            hit->GetChamberNumber(), hit->GetBendingCoor(),
1759            hit->GetNonBendingCoor(), hit->GetZ());
1760     if (fRecGeantHits) {
1761       // from GEANT hits
1762       printf(" %3d %3d \n", hit->GetGeantSignal(), hit->GetTHTrack());
1763     } else {
1764       // from raw clusters
1765       rawclusters = pMUON->RawClustAddress(hit->GetChamberNumber());
1766       clus = (AliMUONRawCluster*) rawclusters->UncheckedAt(hit->
1767                                                GetHitNumber());
1768       printf("%3d", clus->fTracks[1]-1);
1769       if (clus->fTracks[2] != 0) printf("%3d \n", clus->fTracks[2]-1);
1770       else printf("\n");
1771     }
1772     */
1773   }
1774
1775   icand = -1;
1776   Int_t nSeeds = fNRecTracks; // starting number of seeds
1777   // Loop over track candidates
1778   while (icand < fNRecTracks-1) {
1779     icand ++;
1780     trackK = (AliMUONTrackK*) ((*fRecTracksPtr)[icand]);
1781
1782     // Discard candidate which will produce the double track
1783     if (icand > 0) {
1784       Ok = CheckCandidateK(icand,nSeeds);
1785       if (!Ok) {
1786         //trackK->SetRecover(-1); // mark candidate to be removed
1787         //continue;
1788       }
1789     }
1790
1791     Ok = kTRUE;
1792     if (trackK->GetRecover() == 0) hit = (AliMUONHitForRec*) 
1793                                    trackK->GetHitOnTrack()->Last(); // last hit
1794     else hit = (AliMUONHitForRec*) (*trackK->GetHitOnTrack())[1]; // 2'nd hit
1795     ichamBeg = hit->GetChamberNumber();
1796     ichamEnd = 0;
1797     // Check propagation direction
1798     if (trackK->GetTrackDir() > 0) {
1799       ichamEnd = 9; // forward propagation
1800       Ok = trackK->KalmanFilter(ichamBeg,ichamEnd,kFALSE,zDipole1,zDipole2);
1801       if (Ok) {
1802         ichamBeg = ichamEnd;
1803         ichamEnd = 6; // backward propagation
1804         // Change weight matrix and zero fChi2 for backpropagation
1805         trackK->StartBack();
1806         Ok = trackK->KalmanFilter(ichamBeg,ichamEnd,kTRUE,zDipole1,zDipole2);
1807         ichamBeg = ichamEnd;
1808         ichamEnd = 0;
1809       }
1810     } else {
1811       if (trackK->GetBPFlag()) {
1812         // backpropagation
1813         ichamEnd = 6; // backward propagation
1814         // Change weight matrix and zero fChi2 for backpropagation
1815         trackK->StartBack();
1816         Ok = trackK->KalmanFilter(ichamBeg,ichamEnd,kTRUE,zDipole1,zDipole2);
1817         ichamBeg = ichamEnd;
1818         ichamEnd = 0;
1819       }
1820     }
1821
1822     if (Ok) {
1823       trackK->SetTrackDir(-1);
1824       trackK->SetBPFlag(kFALSE);
1825       Ok = trackK->KalmanFilter(ichamBeg,ichamEnd,kFALSE,zDipole1,zDipole2);
1826     }
1827     if (Ok) trackK->SetTrackQuality(0); // compute "track quality"
1828     else trackK->SetRecover(-1); // mark candidate to be removed
1829
1830     // Majority 3 of 4 in first 2 stations
1831     chamBits = 0;
1832     for (Int_t i=0; i<trackK->GetNTrackHits(); i++) {
1833       hit = (AliMUONHitForRec*) (*trackK->GetHitOnTrack())[i];
1834       chamBits |= BIT(hit->GetChamberNumber()-1);
1835     }
1836     //if (!((chamBits&3)==3 || (chamBits>>2&3)==3)) trackK->SetRecover(-1); 
1837                                  //mark candidate to be removed
1838   } // while
1839
1840   for (Int_t i=0; i<fNRecTracks; i++) {
1841     trackK = (AliMUONTrackK*) ((*fRecTracksPtr)[i]);
1842     if (trackK->GetRecover() < 0) fRecTracksPtr->RemoveAt(i);
1843   }
1844
1845   // Compress TClonesArray
1846   fRecTracksPtr->Compress();
1847   fNRecTracks = fRecTracksPtr->GetEntriesFast();
1848   return;
1849 }
1850
1851 //__________________________________________________________________________
1852 Bool_t AliMUONEventReconstructor::CheckCandidateK(Int_t icand, Int_t nSeeds)
1853 {
1854   // Discards track candidate if it will produce the double track (having
1855   // the same seed segment hits as hits of a good track found before)
1856   AliMUONTrackK *track1, *track2;
1857   AliMUONHitForRec *hit1, *hit2, *hit;
1858
1859   track1 = (AliMUONTrackK*) ((*fRecTracksPtr)[icand]);
1860   hit1 = (AliMUONHitForRec*) (*track1->GetHitOnTrack())[0]; // 1'st hit
1861   hit2 = (AliMUONHitForRec*) (*track1->GetHitOnTrack())[1]; // 2'nd hit
1862
1863   for (Int_t i=0; i<icand; i++) {
1864     track2 = (AliMUONTrackK*) ((*fRecTracksPtr)[i]);
1865     //if (track2->GetRecover() < 0) continue;
1866     if (track2->GetRecover() < 0 && icand >= nSeeds) continue;
1867
1868     if (track1->GetStartSegment() == track2->GetStartSegment()) {
1869       return kFALSE;
1870     } else {
1871       Int_t nSame = 0;
1872       for (Int_t j=0; j<track2->GetNTrackHits(); j++) {
1873         hit = (AliMUONHitForRec*) (*track2->GetHitOnTrack())[j];
1874         if (hit == hit1 || hit == hit2) {
1875           nSame++;
1876           if (nSame == 2) return kFALSE;
1877         }
1878       } // for (Int_t j=0;
1879     }
1880   } // for (Int_t i=0;
1881   return kTRUE;
1882 }
1883
1884 //__________________________________________________________________________
1885 void AliMUONEventReconstructor::RemoveDoubleTracksK(void)
1886 {
1887   // Removes double tracks (sharing more than half of their hits). Keeps
1888   // the track with higher quality
1889   AliMUONTrackK *track1, *track2, *trackToKill;
1890
1891   // Sort tracks according to their quality
1892   fRecTracksPtr->Sort();
1893
1894   // Loop over first track of the pair
1895   track1 = (AliMUONTrackK*) fRecTracksPtr->First();
1896   while (track1) {
1897     // Loop over second track of the pair
1898     track2 = (AliMUONTrackK*) fRecTracksPtr->After(track1);
1899     while (track2) {
1900       // Check whether or not to keep track2
1901       if (!track2->KeepTrack(track1)) {
1902         cout << " Killed track: " << 1/(*track2->GetTrackParameters())(4,0) <<
1903           " " << track2->GetTrackQuality() << endl;
1904         trackToKill = track2;
1905         track2 = (AliMUONTrackK*) fRecTracksPtr->After(track2);
1906         trackToKill->Kill();
1907         fRecTracksPtr->Compress();
1908       } else track2 = (AliMUONTrackK*) fRecTracksPtr->After(track2);
1909     } // track2
1910     track1 = (AliMUONTrackK*) fRecTracksPtr->After(track1);
1911   } // track1
1912
1913   fNRecTracks = fRecTracksPtr->GetEntriesFast();
1914   cout << " Number of Kalman tracks: " << fNRecTracks << endl;
1915 }
1916
1917 //__________________________________________________________________________
1918 void AliMUONEventReconstructor::GoToVertex(void)
1919 {
1920   // Propagates track to the vertex thru absorber
1921   // (using Branson correction for now)
1922
1923   Double_t zVertex;
1924   zVertex = 0;
1925   for (Int_t i=0; i<fNRecTracks; i++) {
1926     //((AliMUONTrackK*)(*fRecTracksPtr)[i])->Branson();
1927     //((AliMUONTrackK*)(*fRecTracksPtr)[i])->GoToZ(zVertex); // w/out absorber
1928     ((AliMUONTrackK*)(*fRecTracksPtr)[i])->SetTrackQuality(1); // compute Chi2
1929     ((AliMUONTrackK*)(*fRecTracksPtr)[i])->GoToVertex(); // with absorber
1930   }
1931 }