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