]> git.uio.no Git - u/mrichter/AliRoot.git/blob - MUON/AliMUONEventReconstructor.cxx
Patch for using MUONTriggerTracker and MUONTracker macros one after the other (Ch. F)
[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   static Bool_t isTriggerTrackInMem = 1;
995
996   TClonesArray *recTriggerTracks = fMUONData->RecTriggerTracks();
997
998   // protection if using triggertrack and track macro instead of reconstruct macro
999   if (recTriggerTracks == 0x0) 
1000     isTriggerTrackInMem = 0;
1001
1002   if (!isTriggerTrackInMem) {
1003     fMUONData->ResetRecTriggerTracks();
1004     fMUONData->SetTreeAddress("RL");
1005     fMUONData->GetRecTriggerTracks();
1006     recTriggerTracks = fMUONData->RecTriggerTracks();
1007   } 
1008
1009   track = (AliMUONTrack*) fRecTracksPtr->First();
1010   while (track) {
1011     track->MatchTriggerTrack(recTriggerTracks);
1012     track = (AliMUONTrack*) fRecTracksPtr->After(track);
1013   }
1014 }
1015
1016   //__________________________________________________________________________
1017 Bool_t AliMUONEventReconstructor::MakeTriggerTracks(void)
1018 {
1019     // To make the trigger tracks from Local Trigger
1020     if (fPrintLevel >= 1) cout << "enter MakeTriggerTracks" << endl;
1021     //    ResetTriggerTracks();
1022     
1023     Int_t nTRentries;
1024     Long_t gloTrigPat;
1025     TClonesArray *localTrigger;
1026     TClonesArray *globalTrigger;
1027     AliMUONLocalTrigger *locTrg;
1028     AliMUONGlobalTrigger *gloTrg;
1029     AliMUONTriggerCircuit *circuit;
1030     AliMUONTriggerTrack *recTriggerTrack = 0;
1031
1032     TTree* TR = fLoader->TreeR();
1033     
1034     // Loading MUON subsystem
1035     AliMUON * pMUON = (AliMUON *) gAlice->GetDetector("MUON");
1036     
1037     nTRentries = Int_t(TR->GetEntries());
1038      
1039     TR->GetEvent(0); // only one entry  
1040
1041     if (!(fMUONData->IsTriggerBranchesInTree())) {
1042       cout << "Warning in AliMUONEventReconstructor::MakeTriggerTracks"
1043            << endl;
1044       cout << "Trigger information is not avalaible, nTRentries = " << nTRentries << " not equal to 1" << endl;
1045       return kFALSE;
1046     }
1047
1048     fMUONData->SetTreeAddress("GLT");
1049     fMUONData->GetTrigger();
1050
1051     // global trigger for trigger pattern
1052     gloTrigPat = 0;
1053     globalTrigger = fMUONData->GlobalTrigger(); 
1054     gloTrg = (AliMUONGlobalTrigger*)globalTrigger->UncheckedAt(0);      
1055     if (gloTrg->SinglePlusLpt())  gloTrigPat|= 0x1;
1056     if (gloTrg->SinglePlusHpt())  gloTrigPat|= 0x2;
1057     if (gloTrg->SinglePlusApt())  gloTrigPat|= 0x4;
1058  
1059     if (gloTrg->SingleMinusLpt()) gloTrigPat|= 0x8;
1060     if (gloTrg->SingleMinusHpt()) gloTrigPat|= 0x10;
1061     if (gloTrg->SingleMinusApt()) gloTrigPat|= 0x20;
1062  
1063     if (gloTrg->SingleUndefLpt()) gloTrigPat|= 0x40;
1064     if (gloTrg->SingleUndefHpt()) gloTrigPat|= 0x80;
1065     if (gloTrg->SingleUndefApt()) gloTrigPat|= 0x100;
1066  
1067     if (gloTrg->PairUnlikeLpt())  gloTrigPat|= 0x200;
1068     if (gloTrg->PairUnlikeHpt())  gloTrigPat|= 0x400;
1069     if (gloTrg->PairUnlikeApt())  gloTrigPat|= 0x800;
1070
1071     if (gloTrg->PairLikeLpt())    gloTrigPat|= 0x1000;
1072     if (gloTrg->PairLikeHpt())    gloTrigPat|= 0x2000;
1073     if (gloTrg->PairLikeApt())    gloTrigPat|= 0x4000;
1074
1075  
1076
1077     // local trigger for tracking 
1078     localTrigger = fMUONData->LocalTrigger();    
1079     Int_t nlocals = (Int_t) (localTrigger->GetEntries());
1080     Float_t z11 = ( &(pMUON->Chamber(10)) )->Z();
1081     Float_t z21 = ( &(pMUON->Chamber(12)) )->Z();
1082
1083     for (Int_t i=0; i<nlocals; i++) { // loop on Local Trigger
1084       locTrg = (AliMUONLocalTrigger*)localTrigger->UncheckedAt(i);      
1085       circuit = &(pMUON->TriggerCircuit(locTrg->LoCircuit()));
1086       Float_t y11 = circuit->GetY11Pos(locTrg->LoStripX()); 
1087       Int_t stripX21 = locTrg->LoStripX()+locTrg->LoDev()+1;
1088       Float_t y21 = circuit->GetY21Pos(stripX21);       
1089       Float_t x11 = circuit->GetX11Pos(locTrg->LoStripY());
1090       Float_t thetax = TMath::ATan2( x11 , z11 );
1091       Float_t thetay = TMath::ATan2( (y21-y11) , (z21-z11) );
1092
1093       recTriggerTrack = new AliMUONTriggerTrack(x11,y11,thetax,thetay,gloTrigPat,this);
1094       // since static statement does not work, set gloTrigPat for each track
1095
1096       //        fNRecTriggerTracks++;
1097       fMUONData->AddRecTriggerTrack(*recTriggerTrack);
1098     } // end of loop on Local Trigger
1099     return kTRUE;    
1100 }
1101
1102   //__________________________________________________________________________
1103 Int_t AliMUONEventReconstructor::MakeTrackCandidatesWithTwoSegments(AliMUONSegment *BegSegment)
1104 {
1105   // To make track candidates with two segments in stations(1..) 4 and 5,
1106   // the first segment being pointed to by "BegSegment".
1107   // Returns the number of such track candidates.
1108   Int_t endStation, iEndSegment, nbCan2Seg;
1109   AliMUONSegment *endSegment, *extrapSegment;
1110   AliMUONTrack *recTrack;
1111   Double_t mcsFactor;
1112   if (fPrintLevel >= 1) cout << "enter MakeTrackCandidatesWithTwoSegments" << endl;
1113   // Station for the end segment
1114   endStation = 7 - (BegSegment->GetHitForRec1())->GetChamberNumber() / 2;
1115   // multiple scattering factor corresponding to one chamber
1116   mcsFactor = 0.0136 /
1117     GetBendingMomentumFromImpactParam(BegSegment->GetBendingImpact());
1118   mcsFactor     = fChamberThicknessInX0 * mcsFactor * mcsFactor;
1119   // linear extrapolation to end station
1120   extrapSegment =
1121     BegSegment->CreateSegmentFromLinearExtrapToStation(endStation, mcsFactor);
1122   // number of candidates with 2 segments to 0
1123   nbCan2Seg = 0;
1124   // Loop over segments in the end station
1125   for (iEndSegment = 0; iEndSegment < fNSegments[endStation]; iEndSegment++) {
1126     // pointer to segment
1127     endSegment = (AliMUONSegment*) ((*fSegmentsPtr[endStation])[iEndSegment]);
1128     // test compatibility between current segment and "extrapSegment"
1129     // 4 because 4 quantities in chi2
1130     if ((endSegment->
1131          NormalizedChi2WithSegment(extrapSegment,
1132                                    fMaxSigma2Distance)) <= 4.0) {
1133       // both segments compatible:
1134       // make track candidate from "begSegment" and "endSegment"
1135       if (fPrintLevel >= 2)
1136         cout << "TrackCandidate with Segment " << iEndSegment <<
1137           " in Station(0..) " << endStation << endl;
1138       // flag for both segments in one track:
1139       // to be done in track constructor ????
1140       BegSegment->SetInTrack(kTRUE);
1141       endSegment->SetInTrack(kTRUE);
1142       recTrack = new ((*fRecTracksPtr)[fNRecTracks])
1143         AliMUONTrack(BegSegment, endSegment, this);
1144       fNRecTracks++;
1145       if (fPrintLevel >= 10) recTrack->RecursiveDump();
1146       // increment number of track candidates with 2 segments
1147       nbCan2Seg++;
1148     }
1149   } // for (iEndSegment = 0;...
1150   delete extrapSegment; // should not delete HitForRec's it points to !!!!
1151   return nbCan2Seg;
1152 }
1153
1154   //__________________________________________________________________________
1155 Int_t AliMUONEventReconstructor::MakeTrackCandidatesWithOneSegmentAndOnePoint(AliMUONSegment *BegSegment)
1156 {
1157   // To make track candidates with one segment and one point
1158   // in stations(1..) 4 and 5,
1159   // the segment being pointed to by "BegSegment".
1160   Int_t ch, ch1, ch2, endStation, iHit, iHitMax, iHitMin, nbCan1Seg1Hit;
1161   AliMUONHitForRec *extrapHitForRec, *hit;
1162   AliMUONTrack *recTrack;
1163   Double_t mcsFactor;
1164   if (fPrintLevel >= 1)
1165     cout << "enter MakeTrackCandidatesWithOneSegmentAndOnePoint" << endl;
1166   // station for the end point
1167   endStation = 7 - (BegSegment->GetHitForRec1())->GetChamberNumber() / 2;
1168   // multiple scattering factor corresponding to one chamber
1169   mcsFactor = 0.0136 /
1170     GetBendingMomentumFromImpactParam(BegSegment->GetBendingImpact());
1171   mcsFactor     = fChamberThicknessInX0 * mcsFactor * mcsFactor;
1172   // first and second chambers(0..) in the end station
1173   ch1 = 2 * endStation;
1174   ch2 = ch1 + 1;
1175   // number of candidates to 0
1176   nbCan1Seg1Hit = 0;
1177   // Loop over chambers of the end station
1178   for (ch = ch2; ch >= ch1; ch--) {
1179     // linear extrapolation to chamber
1180     extrapHitForRec =
1181       BegSegment->CreateHitForRecFromLinearExtrapToChamber(ch, mcsFactor);
1182     // limits for the hit index in the loop
1183     iHitMin = fIndexOfFirstHitForRecPerChamber[ch];
1184     iHitMax = iHitMin + fNHitsForRecPerChamber[ch];
1185     // Loop over HitForRec's in the chamber
1186     for (iHit = iHitMin; iHit < iHitMax; iHit++) {
1187       // pointer to HitForRec
1188       hit = (AliMUONHitForRec*) ((*fHitsForRecPtr)[iHit]);
1189       // test compatibility between current HitForRec and "extrapHitForRec"
1190       // 2 because 2 quantities in chi2
1191       if ((hit->
1192            NormalizedChi2WithHitForRec(extrapHitForRec,
1193                                        fMaxSigma2Distance)) <= 2.0) {
1194         // both HitForRec's compatible:
1195         // make track candidate from begSegment and current HitForRec
1196         if (fPrintLevel >= 2)
1197           cout << "TrackCandidate with HitForRec " << iHit <<
1198             " in Chamber(0..) " << ch << endl;
1199         // flag for beginning segments in one track:
1200         // to be done in track constructor ????
1201         BegSegment->SetInTrack(kTRUE);
1202         recTrack = new ((*fRecTracksPtr)[fNRecTracks])
1203           AliMUONTrack(BegSegment, hit, this);
1204         // the right place to eliminate "double counting" ???? how ????
1205         fNRecTracks++;
1206         if (fPrintLevel >= 10) recTrack->RecursiveDump();
1207         // increment number of track candidates
1208         nbCan1Seg1Hit++;
1209       }
1210     } // for (iHit = iHitMin;...
1211     delete extrapHitForRec;
1212   } // for (ch = ch2;...
1213   return nbCan1Seg1Hit;
1214 }
1215
1216   //__________________________________________________________________________
1217 void AliMUONEventReconstructor::MakeTrackCandidates(void)
1218 {
1219   // To make track candidates
1220   // with at least 3 aligned points in stations(1..) 4 and 5
1221   // (two Segment's or one Segment and one HitForRec)
1222   Int_t begStation, iBegSegment, nbCan1Seg1Hit, nbCan2Seg;
1223   AliMUONSegment *begSegment;
1224   if (fPrintLevel >= 1) cout << "enter MakeTrackCandidates" << endl;
1225   // Loop over stations(1..) 5 and 4 for the beginning segment
1226   for (begStation = 4; begStation > 2; begStation--) {
1227     // Loop over segments in the beginning station
1228     for (iBegSegment = 0; iBegSegment < fNSegments[begStation]; iBegSegment++) {
1229       // pointer to segment
1230       begSegment = (AliMUONSegment*) ((*fSegmentsPtr[begStation])[iBegSegment]);
1231       if (fPrintLevel >= 2)
1232         cout << "look for TrackCandidate's with Segment " << iBegSegment <<
1233           " in Station(0..) " << begStation << endl;
1234       // Look for track candidates with two segments,
1235       // "begSegment" and all compatible segments in other station.
1236       // Only for beginning station(1..) 5
1237       // because candidates with 2 segments have to looked for only once.
1238       if (begStation == 4)
1239         nbCan2Seg = MakeTrackCandidatesWithTwoSegments(begSegment);
1240       // Look for track candidates with one segment and one point,
1241       // "begSegment" and all compatible HitForRec's in other station.
1242       // Only if "begSegment" does not belong already to a track candidate.
1243       // Is that a too strong condition ????
1244       if (!(begSegment->GetInTrack()))
1245         nbCan1Seg1Hit = MakeTrackCandidatesWithOneSegmentAndOnePoint(begSegment);
1246     } // for (iBegSegment = 0;...
1247   } // for (begStation = 4;...
1248   return;
1249 }
1250
1251   //__________________________________________________________________________
1252 void AliMUONEventReconstructor::FollowTracks(void)
1253 {
1254   // Follow tracks in stations(1..) 3, 2 and 1
1255   // too long: should be made more modular !!!!
1256   AliMUONHitForRec *bestHit, *extrapHit, *extrapCorrHit, *hit;
1257   AliMUONSegment *bestSegment, *extrapSegment, *extrapCorrSegment, *segment;
1258   AliMUONTrack *track, *nextTrack;
1259   AliMUONTrackParam *trackParam1, trackParam[2], trackParamVertex;
1260   // -1 to avoid compilation warnings
1261   Int_t ch = -1, chInStation, chBestHit = -1, iHit, iSegment, station, trackIndex; 
1262   Double_t bestChi2, chi2, dZ1, dZ2, dZ3, maxSigma2Distance, mcsFactor;
1263   Double_t bendingMomentum, chi2Norm = 0.;
1264   AliMUON *pMUON = (AliMUON*) gAlice->GetModule("MUON"); // necessary ????
1265   // local maxSigma2Distance, for easy increase in testing
1266   maxSigma2Distance = fMaxSigma2Distance;
1267   if (fPrintLevel >= 2)
1268     cout << "enter FollowTracks" << endl;
1269   // Loop over track candidates
1270   track = (AliMUONTrack*) fRecTracksPtr->First();
1271   trackIndex = -1;
1272   while (track) {
1273     // Follow function for each track candidate ????
1274     trackIndex++;
1275     nextTrack = (AliMUONTrack*) fRecTracksPtr->After(track); // prepare next track
1276     if (fPrintLevel >= 2)
1277       cout << "FollowTracks: track candidate(0..): " << trackIndex << endl;
1278     // Fit track candidate
1279     track->SetFitMCS(0); // without multiple Coulomb scattering
1280     track->SetFitNParam(3); // with 3 parameters (X = Y = 0)
1281     track->SetFitStart(0); // from parameters at vertex
1282     track->Fit();
1283     if (fPrintLevel >= 10) {
1284       cout << "FollowTracks: track candidate(0..): " << trackIndex
1285            << " after fit in stations(0..) 3 and 4" << endl;
1286       track->RecursiveDump();
1287     }
1288     // Loop over stations(1..) 3, 2 and 1
1289     // something SPECIAL for stations 2 and 1 for majority 3 coincidence ????
1290     // otherwise: majority coincidence 2 !!!!
1291     for (station = 2; station >= 0; station--) {
1292       // Track parameters at first track hit (smallest Z)
1293       trackParam1 = ((AliMUONTrackHit*)
1294                      (track->GetTrackHitsPtr()->First()))->GetTrackParam();
1295       // extrapolation to station
1296       trackParam1->ExtrapToStation(station, trackParam);
1297       extrapSegment = new AliMUONSegment(); //  empty segment
1298       extrapCorrSegment = new AliMUONSegment(); //  empty corrected segment
1299       // multiple scattering factor corresponding to one chamber
1300       // and momentum in bending plane (not total)
1301       mcsFactor = 0.0136 * trackParam1->GetInverseBendingMomentum();
1302       mcsFactor = fChamberThicknessInX0 * mcsFactor * mcsFactor;
1303       // Z difference from previous station
1304       dZ1 = (&(pMUON->Chamber(2 * station)))->Z() -
1305         (&(pMUON->Chamber(2 * station + 2)))->Z();
1306       // Z difference between the two previous stations
1307       dZ2 = (&(pMUON->Chamber(2 * station + 2)))->Z() -
1308         (&(pMUON->Chamber(2 * station + 4)))->Z();
1309       // Z difference between the two chambers in the previous station
1310       dZ3 = (&(pMUON->Chamber(2 * station)))->Z() -
1311         (&(pMUON->Chamber(2 * station + 1)))->Z();
1312       extrapSegment->SetBendingCoorReso2(fBendingResolution * fBendingResolution);
1313       extrapSegment->
1314         SetNonBendingCoorReso2(fNonBendingResolution * fNonBendingResolution);
1315       extrapSegment->UpdateFromStationTrackParam
1316         (trackParam, mcsFactor, dZ1, dZ2, dZ3, station,
1317          trackParam1->GetInverseBendingMomentum());
1318       // same thing for corrected segment
1319       // better to use copy constructor, after checking that it works properly !!!!
1320       extrapCorrSegment->SetBendingCoorReso2(fBendingResolution * fBendingResolution);
1321       extrapCorrSegment->
1322         SetNonBendingCoorReso2(fNonBendingResolution * fNonBendingResolution);
1323       extrapCorrSegment->UpdateFromStationTrackParam
1324         (trackParam, mcsFactor, dZ1, dZ2, dZ3, station,
1325          trackParam1->GetInverseBendingMomentum());
1326       bestChi2 = 5.0;
1327       bestSegment = NULL;
1328       if (fPrintLevel >= 10) {
1329         cout << "FollowTracks: track candidate(0..): " << trackIndex
1330              << " Look for segment in station(0..): " << station << endl;
1331       }
1332       // Loop over segments in station
1333       for (iSegment = 0; iSegment < fNSegments[station]; iSegment++) {
1334         // Look for best compatible Segment in station
1335         // should consider all possibilities ????
1336         // multiple scattering ????
1337         // separation in 2 functions: Segment and HitForRec ????
1338         segment = (AliMUONSegment*) ((*fSegmentsPtr[station])[iSegment]);
1339         // correction of corrected segment (fBendingCoor and fNonBendingCoor)
1340         // according to real Z value of "segment" and slopes of "extrapSegment"
1341         extrapCorrSegment->
1342           SetBendingCoor(extrapSegment->GetBendingCoor() +
1343                          extrapSegment->GetBendingSlope() *
1344                          (segment->GetHitForRec1()->GetZ() -
1345                           (&(pMUON->Chamber(2 * station)))->Z()));
1346         extrapCorrSegment->
1347           SetNonBendingCoor(extrapSegment->GetNonBendingCoor() +
1348                             extrapSegment->GetNonBendingSlope() *
1349                             (segment->GetHitForRec1()->GetZ() -
1350                              (&(pMUON->Chamber(2 * station)))->Z()));
1351         chi2 = segment->
1352           NormalizedChi2WithSegment(extrapCorrSegment, maxSigma2Distance);
1353         if (chi2 < bestChi2) {
1354           // update best Chi2 and Segment if better found
1355           bestSegment = segment;
1356           bestChi2 = chi2;
1357         }
1358       }
1359       if (bestSegment) {
1360         // best segment found: add it to track candidate
1361         track->AddSegment(bestSegment);
1362         // set track parameters at these two TrakHit's
1363         track->SetTrackParamAtHit(track->GetNTrackHits() - 2, &(trackParam[0]));
1364         track->SetTrackParamAtHit(track->GetNTrackHits() - 1, &(trackParam[1]));
1365         if (fPrintLevel >= 10) {
1366           cout << "FollowTracks: track candidate(0..): " << trackIndex
1367                << " Added segment in station(0..): " << station << endl;
1368           track->RecursiveDump();
1369         }
1370       }
1371       else {
1372         // No best segment found:
1373         // Look for best compatible HitForRec in station:
1374         // should consider all possibilities ????
1375         // multiple scattering ???? do about like for extrapSegment !!!!
1376         extrapHit = new AliMUONHitForRec(); //  empty hit
1377         extrapCorrHit = new AliMUONHitForRec(); //  empty corrected hit
1378         bestChi2 = 3.0;
1379         bestHit = NULL;
1380         if (fPrintLevel >= 10) {
1381           cout << "FollowTracks: track candidate(0..): " << trackIndex
1382                << " Segment not found, look for hit in station(0..): " << station
1383                << endl;
1384         }
1385         // Loop over chambers of the station
1386         for (chInStation = 0; chInStation < 2; chInStation++) {
1387           // coordinates of extrapolated hit
1388           extrapHit->
1389             SetBendingCoor((&(trackParam[chInStation]))->GetBendingCoor());
1390           extrapHit->
1391             SetNonBendingCoor((&(trackParam[chInStation]))->GetNonBendingCoor());
1392           // resolutions from "extrapSegment"
1393           extrapHit->SetBendingReso2(extrapSegment->GetBendingCoorReso2());
1394           extrapHit->SetNonBendingReso2(extrapSegment->GetNonBendingCoorReso2());
1395           // same things for corrected hit
1396           // better to use copy constructor, after checking that it works properly !!!!
1397           extrapCorrHit->
1398             SetBendingCoor((&(trackParam[chInStation]))->GetBendingCoor());
1399           extrapCorrHit->
1400             SetNonBendingCoor((&(trackParam[chInStation]))->GetNonBendingCoor());
1401           extrapHit->SetBendingReso2(extrapSegment->GetBendingCoorReso2());
1402           extrapHit->SetNonBendingReso2(extrapSegment->GetNonBendingCoorReso2());
1403           // Loop over hits in the chamber
1404           ch = 2 * station + chInStation;
1405           for (iHit = fIndexOfFirstHitForRecPerChamber[ch];
1406                iHit < fIndexOfFirstHitForRecPerChamber[ch] +
1407                  fNHitsForRecPerChamber[ch];
1408                iHit++) {
1409             hit = (AliMUONHitForRec*) ((*fHitsForRecPtr)[iHit]);
1410             // correction of corrected hit (fBendingCoor and fNonBendingCoor)
1411             // according to real Z value of "hit" and slopes of right "trackParam"
1412             extrapCorrHit->
1413               SetBendingCoor((&(trackParam[chInStation]))->GetBendingCoor() +
1414                              (&(trackParam[chInStation]))->GetBendingSlope() *
1415                              (hit->GetZ() -
1416                               (&(trackParam[chInStation]))->GetZ()));
1417             extrapCorrHit->
1418               SetNonBendingCoor((&(trackParam[chInStation]))->GetNonBendingCoor() +
1419                                 (&(trackParam[chInStation]))->GetNonBendingSlope() *
1420                                 (hit->GetZ() -
1421                                  (&(trackParam[chInStation]))->GetZ()));
1422             // condition for hit not already in segment ????
1423             chi2 = hit->NormalizedChi2WithHitForRec(extrapHit, maxSigma2Distance);
1424             if (chi2 < bestChi2) {
1425               // update best Chi2 and HitForRec if better found
1426               bestHit = hit;
1427               bestChi2 = chi2;
1428               chBestHit = chInStation;
1429             }
1430           }
1431         }
1432         if (bestHit) {
1433           // best hit found: add it to track candidate
1434           track->AddHitForRec(bestHit);
1435           // set track parameters at this TrackHit
1436           track->SetTrackParamAtHit(track->GetNTrackHits() - 1,
1437                                     &(trackParam[chBestHit]));
1438           if (fPrintLevel >= 10) {
1439             cout << "FollowTracks: track candidate(0..): " << trackIndex
1440                  << " Added hit in station(0..): " << station << endl;
1441             track->RecursiveDump();
1442           }
1443         }
1444         else {
1445           // Remove current track candidate
1446           // and corresponding TrackHit's, ...
1447           track->Remove();
1448           delete extrapSegment;
1449           delete extrapCorrSegment;
1450           delete extrapHit;
1451           delete extrapCorrHit;
1452           break; // stop the search for this candidate:
1453           // exit from the loop over station
1454         }
1455         delete extrapHit;
1456         delete extrapCorrHit;
1457       }
1458       delete extrapSegment;
1459       delete extrapCorrSegment;
1460       // Sort track hits according to increasing Z
1461       track->GetTrackHitsPtr()->Sort();
1462       // Update track parameters at first track hit (smallest Z)
1463       trackParam1 = ((AliMUONTrackHit*)
1464                      (track->GetTrackHitsPtr()->First()))->GetTrackParam();
1465       bendingMomentum = 0.;
1466       if (TMath::Abs(trackParam1->GetInverseBendingMomentum()) > 0.)
1467         bendingMomentum = TMath::Abs(1/(trackParam1->GetInverseBendingMomentum()));
1468       // Track removed if bendingMomentum not in window [min, max]
1469       if ((bendingMomentum < fMinBendingMomentum) || (bendingMomentum > fMaxBendingMomentum)) {
1470         track->Remove();
1471         break; // stop the search for this candidate:
1472         // exit from the loop over station 
1473       }
1474       // Track fit
1475       // with multiple Coulomb scattering if all stations
1476       if (station == 0) track->SetFitMCS(1);
1477       // without multiple Coulomb scattering if not all stations
1478       else track->SetFitMCS(0);
1479       track->SetFitNParam(5);  // with 5 parameters (momentum and position)
1480       track->SetFitStart(1);  // from parameters at first hit
1481       track->Fit();
1482       Double_t numberOfDegFree = (2.0 * track->GetNTrackHits() - 5);
1483       if (numberOfDegFree > 0) {
1484         chi2Norm =  track->GetFitFMin() / numberOfDegFree;
1485       } else {
1486         chi2Norm = 1.e10;
1487       }
1488       // Track removed if normalized chi2 too high
1489       if (chi2Norm > fMaxChi2) {
1490         track->Remove();
1491         break; // stop the search for this candidate:
1492         // exit from the loop over station 
1493       }
1494       if (fPrintLevel >= 10) {
1495         cout << "FollowTracks: track candidate(0..): " << trackIndex
1496              << " after fit from station(0..): " << station << " to 4" << endl;
1497         track->RecursiveDump();
1498       }
1499       // Track extrapolation to the vertex through the absorber (Branson)
1500       // after going through the first station
1501       if (station == 0) {
1502         trackParamVertex = *trackParam1;
1503         (&trackParamVertex)->ExtrapToVertex();
1504         track->SetTrackParamAtVertex(&trackParamVertex);
1505         if (fPrintLevel >= 1) {
1506           cout << "FollowTracks: track candidate(0..): " << trackIndex
1507                << " after extrapolation to vertex" << endl;
1508           track->RecursiveDump();
1509         }
1510       }
1511     } // for (station = 2;...
1512     // go really to next track
1513     track = nextTrack;
1514   } // while (track)
1515   // Compression of track array (necessary after Remove ????)
1516   fRecTracksPtr->Compress();
1517   return;
1518 }
1519
1520   //__________________________________________________________________________
1521 void AliMUONEventReconstructor::RemoveDoubleTracks(void)
1522 {
1523   // To remove double tracks.
1524   // Tracks are considered identical
1525   // if they have at least half of their hits in common.
1526   // Among two identical tracks, one keeps the track with the larger number of hits
1527   // or, if these numbers are equal, the track with the minimum Chi2.
1528   AliMUONTrack *track1, *track2, *trackToRemove;
1529   Bool_t identicalTracks;
1530   Int_t hitsInCommon, nHits1, nHits2;
1531   identicalTracks = kTRUE;
1532   while (identicalTracks) {
1533     identicalTracks = kFALSE;
1534     // Loop over first track of the pair
1535     track1 = (AliMUONTrack*) fRecTracksPtr->First();
1536     while (track1 && (!identicalTracks)) {
1537       nHits1 = track1->GetNTrackHits();
1538       // Loop over second track of the pair
1539       track2 = (AliMUONTrack*) fRecTracksPtr->After(track1);
1540       while (track2 && (!identicalTracks)) {
1541         nHits2 = track2->GetNTrackHits();
1542         // number of hits in common between two tracks
1543         hitsInCommon = track1->HitsInCommon(track2);
1544         // check for identical tracks
1545         if ((4 * hitsInCommon) >= (nHits1 + nHits2)) {
1546           identicalTracks = kTRUE;
1547           // decide which track to remove
1548           if (nHits1 > nHits2) trackToRemove = track2;
1549           else if (nHits1 < nHits2) trackToRemove = track1;
1550           else if ((track1->GetFitFMin()) < (track2->GetFitFMin()))
1551             trackToRemove = track2;
1552           else trackToRemove = track1;
1553           // remove it
1554           trackToRemove->Remove();
1555         }
1556         track2 = (AliMUONTrack*) fRecTracksPtr->After(track2);
1557       } // track2
1558       track1 = (AliMUONTrack*) fRecTracksPtr->After(track1);
1559     } // track1
1560   }
1561   return;
1562 }
1563
1564   //__________________________________________________________________________
1565 void AliMUONEventReconstructor::UpdateTrackParamAtHit()
1566 {
1567   // Set track parameters after track fitting. Fill fTrackParamAtHit of AliMUONTrack's
1568   AliMUONTrack *track;
1569   AliMUONTrackHit *trackHit;
1570   AliMUONTrackParam *trackParam;
1571   track = (AliMUONTrack*) fRecTracksPtr->First();
1572   while (track) {
1573     trackHit = (AliMUONTrackHit*) (track->GetTrackHitsPtr())->First();
1574     while (trackHit) {
1575       trackParam = trackHit->GetTrackParam();
1576       track->AddTrackParamAtHit(trackParam);
1577       trackHit = (AliMUONTrackHit*) (track->GetTrackHitsPtr())->After(trackHit); 
1578     } // trackHit    
1579     track = (AliMUONTrack*) fRecTracksPtr->After(track);
1580   } // track
1581   return;
1582 }
1583
1584   //__________________________________________________________________________
1585 void AliMUONEventReconstructor::EventDump(void)
1586 {
1587   // Dump reconstructed event (track parameters at vertex and at first hit),
1588   // and the particle parameters
1589
1590   AliMUONTrack *track;
1591   AliMUONTrackParam *trackParam, *trackParam1;
1592   Double_t bendingSlope, nonBendingSlope, pYZ;
1593   Double_t pX, pY, pZ, x, y, z, c;
1594   Int_t np, trackIndex, nTrackHits;
1595  
1596   if (fPrintLevel >= 1) cout << "****** enter EventDump ******" << endl;
1597   if (fPrintLevel >= 1) {
1598     cout << " Number of Reconstructed tracks :" <<  fNRecTracks << endl; 
1599   }
1600   fRecTracksPtr->Compress(); // for simple loop without "Next" since no hole
1601   // Loop over reconstructed tracks
1602   for (trackIndex = 0; trackIndex < fNRecTracks; trackIndex++) {
1603     if (fTrackMethod != 1) continue; //AZ - skip the rest for now
1604     if (fPrintLevel >= 1)
1605       cout << " track number: " << trackIndex << endl;
1606     // function for each track for modularity ????
1607     track = (AliMUONTrack*) ((*fRecTracksPtr)[trackIndex]);
1608     nTrackHits = track->GetNTrackHits();
1609     if (fPrintLevel >= 1)
1610       cout << " number of track hits: " << nTrackHits << endl;
1611     // track parameters at Vertex
1612     trackParam = track->GetTrackParamAtVertex();
1613     x = trackParam->GetNonBendingCoor();
1614     y = trackParam->GetBendingCoor();
1615     z = trackParam->GetZ();
1616     bendingSlope = trackParam->GetBendingSlope();
1617     nonBendingSlope = trackParam->GetNonBendingSlope();
1618     pYZ = 1/TMath::Abs(trackParam->GetInverseBendingMomentum());
1619     pZ = pYZ/TMath::Sqrt(1+bendingSlope*bendingSlope);
1620     pX = pZ * nonBendingSlope;
1621     pY = pZ * bendingSlope;
1622     c = TMath::Sign(1.0, trackParam->GetInverseBendingMomentum());
1623     if (fPrintLevel >= 1)
1624       printf(" track parameters at Vertex z= %f: X= %f Y= %f pX= %f pY= %f pZ= %f c= %f\n",
1625              z, x, y, pX, pY, pZ, c);
1626
1627     // track parameters at first hit
1628     trackParam1 = ((AliMUONTrackHit*)
1629                    (track->GetTrackHitsPtr()->First()))->GetTrackParam();
1630     x = trackParam1->GetNonBendingCoor();
1631     y = trackParam1->GetBendingCoor();
1632     z = trackParam1->GetZ();
1633     bendingSlope = trackParam1->GetBendingSlope();
1634     nonBendingSlope = trackParam1->GetNonBendingSlope();
1635     pYZ = 1/TMath::Abs(trackParam1->GetInverseBendingMomentum());
1636     pZ = pYZ/TMath::Sqrt(1.0 + bendingSlope * bendingSlope);
1637     pX = pZ * nonBendingSlope;
1638     pY = pZ * bendingSlope;
1639     c = TMath::Sign(1.0, trackParam1->GetInverseBendingMomentum());
1640     if (fPrintLevel >= 1)
1641       printf(" track parameters at z= %f: X= %f Y= %f pX= %f pY= %f pZ= %f c= %f\n",
1642              z, x, y, pX, pY, pZ, c);
1643   }
1644   // informations about generated particles
1645   np = gAlice->GetMCApp()->GetNtrack();
1646   printf(" **** number of generated particles: %d  \n", np);
1647   
1648 //    for (Int_t iPart = 0; iPart < np; iPart++) {
1649 //      p = gAlice->Particle(iPart);
1650 //      printf(" particle %d: type= %d px= %f py= %f pz= %f pdg= %d\n",
1651 //         iPart, p->GetPdgCode(), p->Px(), p->Py(), p->Pz(), p->GetPdgCode());    
1652 //    }
1653   return;
1654 }
1655
1656
1657 //__________________________________________________________________________
1658 void AliMUONEventReconstructor::EventDumpTrigger(void)
1659 {
1660   // Dump reconstructed trigger event 
1661   // and the particle parameters
1662     
1663   AliMUONTriggerTrack *triggertrack ;
1664   Int_t nTriggerTracks = fMUONData->RecTriggerTracks()->GetEntriesFast();
1665  
1666   if (fPrintLevel >= 1) {
1667     cout << "****** enter EventDumpTrigger ******" << endl;
1668     cout << " Number of Reconstructed tracks :" <<  nTriggerTracks << endl;
1669   }
1670   // Loop over reconstructed tracks
1671   for (Int_t trackIndex = 0; trackIndex < nTriggerTracks; trackIndex++) {
1672     triggertrack = (AliMUONTriggerTrack*)fMUONData->RecTriggerTracks()->At(trackIndex);
1673       printf(" trigger track number %i x11=%f y11=%f thetax=%f thetay=%f \n",
1674              trackIndex,
1675              triggertrack->GetX11(),triggertrack->GetY11(),
1676              triggertrack->GetThetax(),triggertrack->GetThetay());      
1677   } 
1678 }
1679
1680 //__________________________________________________________________________
1681 void AliMUONEventReconstructor::FillEvent()
1682 {
1683 // Create a new AliMUONRecoEvent, fill its track list, then add it as a
1684 // leaf in the Event branch of TreeRecoEvent tree
1685    cout << "Enter FillEvent() ...\n";
1686
1687    if (!fRecoEvent) {
1688       fRecoEvent = new AliMUONRecoEvent();
1689    } else {
1690       fRecoEvent->Clear();
1691    }
1692    //save current directory
1693    TDirectory *current =  gDirectory;
1694    if (!fTreeFile)  fTreeFile  = new TFile("tree_reco.root", "RECREATE");
1695    if (!fEventTree) fEventTree = new TTree("TreeRecoEvent", "MUON reconstructed events");
1696    //AZif (fRecoEvent->MakeDumpTracks(fRecTracksPtr)) {
1697    if (fRecoEvent->MakeDumpTracks(fMuons, fRecTracksPtr, this)) { //AZ
1698       if (fPrintLevel > 1) fRecoEvent->EventInfo();
1699       TBranch *branch = fEventTree->GetBranch("Event");
1700       if (!branch) branch = fEventTree->Branch("Event", "AliMUONRecoEvent", &fRecoEvent, 64000);
1701       branch->SetAutoDelete();
1702       fTreeFile->cd();
1703       fEventTree->Fill();
1704       fTreeFile->Write();
1705    }
1706    // restore directory
1707    current->cd();
1708 }
1709
1710 //__________________________________________________________________________
1711 void AliMUONEventReconstructor::MakeTrackCandidatesK(void)
1712 {
1713   // To make initial tracks for Kalman filter from the list of segments
1714   Int_t istat, iseg;
1715   AliMUONSegment *segment;
1716   AliMUONTrackK *trackK;
1717
1718   if (fPrintLevel >= 1) cout << "enter MakeTrackCandidatesK" << endl;
1719   // Reset the TClonesArray of reconstructed tracks
1720   if (fRecTracksPtr) fRecTracksPtr->Delete();
1721   // Delete in order that the Track destructors are called,
1722   // hence the space for the TClonesArray of pointers to TrackHit's is freed
1723   fNRecTracks = 0;
1724
1725   AliMUONTrackK a(this, fHitsForRecPtr); // bad idea ???
1726   // Loop over stations(1...) 5 and 4
1727   for (istat=4; istat>=3; istat--) {
1728     // Loop over segments in the station
1729     for (iseg=0; iseg<fNSegments[istat]; iseg++) {
1730       // Transform segments to tracks and evaluate covariance matrix
1731       segment = (AliMUONSegment*) ((*fSegmentsPtr[istat])[iseg]);
1732       trackK = new ((*fRecTracksPtr)[fNRecTracks]) AliMUONTrackK(segment);
1733       fNRecTracks++;
1734     } // for (iseg=0;...)
1735   } // for (istat=4;...)
1736   return;
1737 }
1738
1739 //__________________________________________________________________________
1740 void AliMUONEventReconstructor::FollowTracksK(void)
1741 {
1742   // Follow tracks using Kalman filter
1743   Bool_t Ok;
1744   Int_t icand, ichamBeg, ichamEnd, chamBits;
1745   Double_t zDipole1, zDipole2;
1746   AliMUONTrackK *trackK;
1747   AliMUONHitForRec *hit;
1748   AliMUONRawCluster *clus;
1749   TClonesArray *rawclusters;
1750   AliMUON *pMUON;
1751   clus = 0; rawclusters = 0;
1752
1753   zDipole1 = GetSimpleBPosition() - GetSimpleBLength()/2;
1754   zDipole2 = zDipole1 + GetSimpleBLength();
1755
1756   // Print hits
1757   pMUON  = (AliMUON*) gAlice->GetModule("MUON");
1758   for (Int_t i1=0; i1<fNHitsForRec; i1++) {
1759     hit = (AliMUONHitForRec*) ((*fHitsForRecPtr)[i1]);
1760     //if (hit->GetTHTrack() > 1 || hit->GetGeantSignal() == 0) continue;
1761     /*
1762     cout << " Hit #" << hit->GetChamberNumber() << " ";
1763     cout << hit->GetBendingCoor() << " ";
1764     cout << hit->GetNonBendingCoor() << " ";
1765     cout << hit->GetZ() << " ";
1766     cout << hit->GetGeantSignal() << " ";
1767     cout << hit->GetTHTrack() << endl;
1768     */
1769     /*
1770     printf(" Hit # %d %10.4f %10.4f %10.4f",
1771            hit->GetChamberNumber(), hit->GetBendingCoor(),
1772            hit->GetNonBendingCoor(), hit->GetZ());
1773     if (fRecGeantHits) {
1774       // from GEANT hits
1775       printf(" %3d %3d \n", hit->GetGeantSignal(), hit->GetTHTrack());
1776     } else {
1777       // from raw clusters
1778       rawclusters = pMUON->RawClustAddress(hit->GetChamberNumber());
1779       clus = (AliMUONRawCluster*) rawclusters->UncheckedAt(hit->
1780                                                GetHitNumber());
1781       printf("%3d", clus->fTracks[1]-1);
1782       if (clus->fTracks[2] != 0) printf("%3d \n", clus->fTracks[2]-1);
1783       else printf("\n");
1784     }
1785     */
1786   }
1787
1788   icand = -1;
1789   Int_t nSeeds = fNRecTracks; // starting number of seeds
1790   // Loop over track candidates
1791   while (icand < fNRecTracks-1) {
1792     icand ++;
1793     trackK = (AliMUONTrackK*) ((*fRecTracksPtr)[icand]);
1794
1795     // Discard candidate which will produce the double track
1796     if (icand > 0) {
1797       Ok = CheckCandidateK(icand,nSeeds);
1798       if (!Ok) {
1799         //trackK->SetRecover(-1); // mark candidate to be removed
1800         //continue;
1801       }
1802     }
1803
1804     Ok = kTRUE;
1805     if (trackK->GetRecover() == 0) hit = (AliMUONHitForRec*) 
1806                                    trackK->GetHitOnTrack()->Last(); // last hit
1807     else hit = (AliMUONHitForRec*) (*trackK->GetHitOnTrack())[1]; // 2'nd hit
1808     ichamBeg = hit->GetChamberNumber();
1809     ichamEnd = 0;
1810     // Check propagation direction
1811     if (trackK->GetTrackDir() > 0) {
1812       ichamEnd = 9; // forward propagation
1813       Ok = trackK->KalmanFilter(ichamBeg,ichamEnd,kFALSE,zDipole1,zDipole2);
1814       if (Ok) {
1815         ichamBeg = ichamEnd;
1816         ichamEnd = 6; // backward propagation
1817         // Change weight matrix and zero fChi2 for backpropagation
1818         trackK->StartBack();
1819         Ok = trackK->KalmanFilter(ichamBeg,ichamEnd,kTRUE,zDipole1,zDipole2);
1820         ichamBeg = ichamEnd;
1821         ichamEnd = 0;
1822       }
1823     } else {
1824       if (trackK->GetBPFlag()) {
1825         // backpropagation
1826         ichamEnd = 6; // backward propagation
1827         // Change weight matrix and zero fChi2 for backpropagation
1828         trackK->StartBack();
1829         Ok = trackK->KalmanFilter(ichamBeg,ichamEnd,kTRUE,zDipole1,zDipole2);
1830         ichamBeg = ichamEnd;
1831         ichamEnd = 0;
1832       }
1833     }
1834
1835     if (Ok) {
1836       trackK->SetTrackDir(-1);
1837       trackK->SetBPFlag(kFALSE);
1838       Ok = trackK->KalmanFilter(ichamBeg,ichamEnd,kFALSE,zDipole1,zDipole2);
1839     }
1840     if (Ok) trackK->SetTrackQuality(0); // compute "track quality"
1841     else trackK->SetRecover(-1); // mark candidate to be removed
1842
1843     // Majority 3 of 4 in first 2 stations
1844     chamBits = 0;
1845     for (Int_t i=0; i<trackK->GetNTrackHits(); i++) {
1846       hit = (AliMUONHitForRec*) (*trackK->GetHitOnTrack())[i];
1847       chamBits |= BIT(hit->GetChamberNumber()-1);
1848     }
1849     //if (!((chamBits&3)==3 || (chamBits>>2&3)==3)) trackK->SetRecover(-1); 
1850                                  //mark candidate to be removed
1851   } // while
1852
1853   for (Int_t i=0; i<fNRecTracks; i++) {
1854     trackK = (AliMUONTrackK*) ((*fRecTracksPtr)[i]);
1855     if (trackK->GetRecover() < 0) fRecTracksPtr->RemoveAt(i);
1856   }
1857
1858   // Compress TClonesArray
1859   fRecTracksPtr->Compress();
1860   fNRecTracks = fRecTracksPtr->GetEntriesFast();
1861   return;
1862 }
1863
1864 //__________________________________________________________________________
1865 Bool_t AliMUONEventReconstructor::CheckCandidateK(Int_t icand, Int_t nSeeds)
1866 {
1867   // Discards track candidate if it will produce the double track (having
1868   // the same seed segment hits as hits of a good track found before)
1869   AliMUONTrackK *track1, *track2;
1870   AliMUONHitForRec *hit1, *hit2, *hit;
1871
1872   track1 = (AliMUONTrackK*) ((*fRecTracksPtr)[icand]);
1873   hit1 = (AliMUONHitForRec*) (*track1->GetHitOnTrack())[0]; // 1'st hit
1874   hit2 = (AliMUONHitForRec*) (*track1->GetHitOnTrack())[1]; // 2'nd hit
1875
1876   for (Int_t i=0; i<icand; i++) {
1877     track2 = (AliMUONTrackK*) ((*fRecTracksPtr)[i]);
1878     //if (track2->GetRecover() < 0) continue;
1879     if (track2->GetRecover() < 0 && icand >= nSeeds) continue;
1880
1881     if (track1->GetStartSegment() == track2->GetStartSegment()) {
1882       return kFALSE;
1883     } else {
1884       Int_t nSame = 0;
1885       for (Int_t j=0; j<track2->GetNTrackHits(); j++) {
1886         hit = (AliMUONHitForRec*) (*track2->GetHitOnTrack())[j];
1887         if (hit == hit1 || hit == hit2) {
1888           nSame++;
1889           if (nSame == 2) return kFALSE;
1890         }
1891       } // for (Int_t j=0;
1892     }
1893   } // for (Int_t i=0;
1894   return kTRUE;
1895 }
1896
1897 //__________________________________________________________________________
1898 void AliMUONEventReconstructor::RemoveDoubleTracksK(void)
1899 {
1900   // Removes double tracks (sharing more than half of their hits). Keeps
1901   // the track with higher quality
1902   AliMUONTrackK *track1, *track2, *trackToKill;
1903
1904   // Sort tracks according to their quality
1905   fRecTracksPtr->Sort();
1906
1907   // Loop over first track of the pair
1908   track1 = (AliMUONTrackK*) fRecTracksPtr->First();
1909   while (track1) {
1910     // Loop over second track of the pair
1911     track2 = (AliMUONTrackK*) fRecTracksPtr->After(track1);
1912     while (track2) {
1913       // Check whether or not to keep track2
1914       if (!track2->KeepTrack(track1)) {
1915         cout << " Killed track: " << 1/(*track2->GetTrackParameters())(4,0) <<
1916           " " << track2->GetTrackQuality() << endl;
1917         trackToKill = track2;
1918         track2 = (AliMUONTrackK*) fRecTracksPtr->After(track2);
1919         trackToKill->Kill();
1920         fRecTracksPtr->Compress();
1921       } else track2 = (AliMUONTrackK*) fRecTracksPtr->After(track2);
1922     } // track2
1923     track1 = (AliMUONTrackK*) fRecTracksPtr->After(track1);
1924   } // track1
1925
1926   fNRecTracks = fRecTracksPtr->GetEntriesFast();
1927   cout << " Number of Kalman tracks: " << fNRecTracks << endl;
1928 }
1929
1930 //__________________________________________________________________________
1931 void AliMUONEventReconstructor::GoToVertex(void)
1932 {
1933   // Propagates track to the vertex thru absorber
1934   // (using Branson correction for now)
1935
1936   Double_t zVertex;
1937   zVertex = 0;
1938   for (Int_t i=0; i<fNRecTracks; i++) {
1939     //((AliMUONTrackK*)(*fRecTracksPtr)[i])->Branson();
1940     //((AliMUONTrackK*)(*fRecTracksPtr)[i])->GoToZ(zVertex); // w/out absorber
1941     ((AliMUONTrackK*)(*fRecTracksPtr)[i])->SetTrackQuality(1); // compute Chi2
1942     ((AliMUONTrackK*)(*fRecTracksPtr)[i])->GoToVertex(); // with absorber
1943   }
1944 }