- Adding check and flagging for HG present
[u/mrichter/AliRoot.git] / MUON / AliMUONTrackHitPattern.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 /// \class AliMUONTrackHitPattern
21 ///
22 /// This class propagates tracks to trigger chambers 
23 /// searching for matching trigger tracks and fired strips.
24 ///
25 /// To each track, a hit pattern for trigger chambers is set.
26 /// 
27 /// The main method is:
28 /// * ExecuteValidation
29 ///
30 ///  \author Diego Stocco
31 //-----------------------------------------------------------------------------
32
33
34 #include "AliMUONTrackHitPattern.h"
35
36 #include "AliMUONConstants.h"
37 #include "AliMUONVDigit.h"
38 #include "AliMUONVDigitStore.h"
39 #include "AliMUONGeometryTransformer.h"
40 #include "AliMUONLocalTrigger.h"
41 #include "AliMUONLocalTriggerBoard.h"
42 #include "AliMUONRecoParam.h"
43 #include "AliMUONTrack.h"
44 #include "AliMUONTrackExtrap.h"
45 #include "AliMUONTrackParam.h"
46 #include "AliMUONVTrackStore.h"
47 #include "AliMUONVTriggerStore.h"
48 #include "AliMpPad.h"
49 #include "AliMpSegmentation.h"
50 #include "AliMpVSegmentation.h"
51 #include "AliMpDEManager.h"
52 #include "AliMUONReconstructor.h"
53 #include "AliMUONTriggerTrack.h"
54 #include "AliMUONVTriggerTrackStore.h"
55
56 #include "AliMpConstants.h"
57
58 #include "AliLog.h"
59 #include "AliTracker.h"
60 #include "AliESDMuonTrack.h"
61
62 #include <Riostream.h>
63 #include <TArrayS.h>
64 #include <TClonesArray.h>
65 #include <TMath.h>
66 #include <TMatrixD.h>
67 #include <TROOT.h>
68 #include <TDirectory.h>
69 #include <TFile.h>
70 #include <TSystem.h>
71 #include <TVector2.h>
72
73 #include <cassert>
74
75 /// \cond CLASSIMP
76 ClassImp(AliMUONTrackHitPattern) // Class implementation in ROOT context
77 /// \endcond
78
79
80 //______________________________________________________________________________
81 AliMUONTrackHitPattern::AliMUONTrackHitPattern(const AliMUONRecoParam* recoParam,
82                                                const AliMUONGeometryTransformer& transformer,
83                                                const AliMUONVDigitStore& digitStore)
84 : TObject(),
85 fkRecoParam(recoParam),
86 fkTransformer(transformer),
87 fkDigitStore(digitStore),
88 fkMaxDistance(99999.)
89 {
90     /// Default constructor
91     AliMUONTrackExtrap::SetField();
92 }
93
94
95 //______________________________________________________________________________
96 AliMUONTrackHitPattern::~AliMUONTrackHitPattern(void)
97 {
98   /// Destructor
99 }
100
101 //_____________________________________________________________________________
102 void AliMUONTrackHitPattern::CheckConstants() const
103 {
104 /// Check consistence of redefined constants 
105
106   assert(fgkNcathodes == AliMpConstants::NofCathodes());    
107   assert(fgkNchambers == AliMpConstants::NofTriggerChambers());    
108   assert(fgkNplanes == AliMpConstants::NofTriggerChambers() * fgkNcathodes);    
109 }
110
111
112 //______________________________________________________________________________
113 void AliMUONTrackHitPattern::ExecuteValidation(const AliMUONVTrackStore& trackStore,
114                                                const AliMUONVTriggerTrackStore& triggerTrackStore,
115                                                const AliMUONVTriggerStore& triggerStore) const
116 {
117   //
118   /// Main method:
119   /// Loops on reco tracks, extrapolates them to trigger chambers
120   /// and searches for matching trigger tracks and digits
121   //
122
123   // Get the hit pattern for all trigger tracks
124   AliMUONTriggerTrack* triggerTrack;
125   TIter itTriggerTrack(triggerTrackStore.CreateIterator());
126   while ( ( triggerTrack = static_cast<AliMUONTriggerTrack*>(itTriggerTrack() ) ) ){
127     UShort_t pattern = GetHitPattern(triggerTrack);
128     triggerTrack->SetHitsPatternInTrigCh(pattern);
129     AliDebug(1, Form("Hit pattern: hits 0x%x  slat %2i  board %3i  effFlag %i",
130                      pattern & 0xFF, AliESDMuonTrack::GetSlatOrInfo(pattern),
131                      triggerTrack->GetLoTrgNum(), AliESDMuonTrack::GetEffFlag(pattern)));
132   }
133
134   // Match tracker tracks with trigger tracks.
135   TIter itTrack(trackStore.CreateIterator());
136   AliMUONTrack* track;
137
138   const Int_t kFirstTrigCh = AliMUONConstants::NTrackingCh();
139
140   while ( ( track = static_cast<AliMUONTrack*>(itTrack()) ) )
141   { 
142     AliMUONTrackParam trackParam(*((AliMUONTrackParam*) (track->GetTrackParamAtCluster()->Last())));
143
144     ApplyMCSCorrections(trackParam);
145     AliMUONTrackExtrap::ExtrapToZCov(&trackParam, AliMUONConstants::DefaultChamberZ(kFirstTrigCh)); // extrap to 1st trigger chamber
146
147     AliMUONTriggerTrack *matchedTriggerTrack = MatchTriggerTrack(track, trackParam, triggerTrackStore, triggerStore);
148
149     // Copy trigger tracks hit pattern if there is matching,
150     // otherwise calculate the hit pattern directly from tracker track:
151     // the obtained pattern is good for check, but not good for efficiency determination.
152     UShort_t pattern = matchedTriggerTrack ?
153       matchedTriggerTrack->GetHitsPatternInTrigCh() : 
154       GetHitPattern(&trackParam);
155
156     track->SetHitsPatternInTrigCh(pattern);
157   }
158 }
159
160
161 //______________________________________________________________________________
162 AliMUONTriggerTrack * 
163 AliMUONTrackHitPattern::MatchTriggerTrack(AliMUONTrack* track,
164                                           AliMUONTrackParam& trackParam,
165                                           const AliMUONVTriggerTrackStore& triggerTrackStore,
166                                           const AliMUONVTriggerStore& triggerStore) const
167 {
168   //
169   /// Match track with trigger track
170   //
171
172   Int_t matchTrigger = 0;
173   Int_t loTrgNum(-1);
174   TMatrixD paramDiff(3,1);
175   Double_t chi2;
176   Double_t chi2MatchTrigger = 0., minChi2MatchTrigger = 999.;
177   Int_t doubleMatch = -1; // Check if track matches 2 trigger tracks
178   Double_t doubleChi2 = -1.;
179   AliMUONTriggerTrack* doubleTriggerTrack = 0x0;
180   AliMUONTriggerTrack* matchedTriggerTrack = 0x0;
181     
182
183   // Covariance matrix 3x3 (X,Y,slopeY) for trigger tracks
184   TMatrixD trackCov(3,3);
185
186   AliMUONTriggerTrack *triggerTrack;
187   TIter itTriggerTrack(triggerTrackStore.CreateIterator());
188   while ( ( triggerTrack = static_cast<AliMUONTriggerTrack*>(itTriggerTrack() ) ) )
189   {
190     AliMUONTrackExtrap::LinearExtrapToZCov(&trackParam, triggerTrack->GetZ11());
191     const TMatrixD& kParamCov = trackParam.GetCovariances();
192     
193     Double_t xTrack = trackParam.GetNonBendingCoor();
194     Double_t yTrack = trackParam.GetBendingCoor();
195     Double_t ySlopeTrack = trackParam.GetBendingSlope();
196
197     paramDiff(0,0) = triggerTrack->GetX11() - xTrack;
198     paramDiff(1,0) = triggerTrack->GetY11() - yTrack;
199     paramDiff(2,0) = triggerTrack->GetSlopeY() - ySlopeTrack;
200
201     // Covariance matrix 3x3 (X,Y,slopeY) for tracker tracks
202     trackCov.Zero();
203     trackCov(0,0) = kParamCov(0,0);
204     trackCov(1,1) = kParamCov(2,2);
205     trackCov(2,2) = kParamCov(3,3);
206     trackCov(1,2) = kParamCov(2,3);
207     trackCov(2,1) = kParamCov(3,2);
208
209     // Covariance matrix 3x3 (X,Y,slopeY) for trigger tracks
210     TMatrixD trigCov(triggerTrack->GetCovariances());
211
212     TMatrixD sumCov(trackCov,TMatrixD::kPlus,trigCov);
213     if (sumCov.Determinant() != 0) {
214       sumCov.Invert();
215       
216       TMatrixD tmp(sumCov,TMatrixD::kMult,paramDiff);
217       TMatrixD chi2M(paramDiff,TMatrixD::kTransposeMult,tmp);
218       chi2 = chi2M(0,0);      
219     } else {
220       AliWarning(" Determinant = 0");
221       Double_t sigma2 = 0.;
222       chi2 = 0.;
223       for (Int_t iVar = 0; iVar < 3; iVar++) {
224         sigma2 = trackCov(iVar,iVar) + trigCov(iVar,iVar);
225         chi2 += paramDiff(iVar,0) * paramDiff(iVar,0) / sigma2;
226       }
227     }
228
229     chi2 /= 3.; // Normalized Chi2: 3 degrees of freedom (X,Y,slopeY)
230     if (chi2 < GetRecoParam()->GetMaxNormChi2MatchTrigger()) 
231     {
232       Bool_t isDoubleTrack = (TMath::Abs(chi2 - minChi2MatchTrigger)<1.);
233       if (chi2 < minChi2MatchTrigger && chi2 < GetRecoParam()->GetMaxNormChi2MatchTrigger()) 
234       {
235         if(isDoubleTrack)
236         {
237           doubleMatch = loTrgNum;
238           doubleChi2 = chi2MatchTrigger;
239           doubleTriggerTrack = matchedTriggerTrack;
240         }
241         minChi2MatchTrigger = chi2;
242         chi2MatchTrigger = chi2;
243         loTrgNum = triggerTrack->GetLoTrgNum();
244         matchedTriggerTrack = triggerTrack;
245         AliMUONLocalTrigger* locTrg = triggerStore.FindLocal(loTrgNum);
246         matchTrigger = 1;
247         if(locTrg->LoLpt()>0) matchTrigger = 2;
248         if(locTrg->LoHpt()>0) matchTrigger = 3;
249       }
250       else if(isDoubleTrack) 
251       {
252         doubleMatch = triggerTrack->GetLoTrgNum();
253         doubleChi2 = chi2;
254       }
255     }
256   }
257   if(doubleMatch>=0)
258   { // If two trigger tracks match, select the one passing more trigger cuts
259     AliDebug(1, Form("Two candidates found: %i and %i",loTrgNum,doubleMatch));
260     AliMUONLocalTrigger* locTrg1 = triggerStore.FindLocal(doubleMatch);
261     if((locTrg1->LoLpt()>0 && matchTrigger<2) || (locTrg1->LoHpt() && matchTrigger<3))
262     {
263       if(locTrg1->LoHpt()>0) matchTrigger=3;
264       else matchTrigger = 2;
265       loTrgNum = doubleMatch;
266       chi2MatchTrigger = doubleChi2;
267       matchedTriggerTrack = doubleTriggerTrack;
268     }
269   }
270     
271   track->SetMatchTrigger(matchTrigger);
272   track->SetChi2MatchTrigger(chi2MatchTrigger);
273
274   AliMUONLocalTrigger* locTrg = static_cast<AliMUONLocalTrigger*>(triggerStore.FindLocal(loTrgNum));
275
276   if (locTrg)
277   {    
278     track->SetLocalTrigger(locTrg->LoCircuit(),
279                            locTrg->LoStripX(),
280                            locTrg->LoStripY(),
281                            locTrg->GetDeviation(),
282                            locTrg->LoLpt(),
283                            locTrg->LoHpt(),
284                            locTrg->GetTriggerWithoutChamber());
285   }
286
287   return matchedTriggerTrack;
288 }
289
290
291 //______________________________________________________________________________
292 UShort_t AliMUONTrackHitPattern::GetHitPattern(AliMUONTriggerTrack* matchedTriggerTrack) const
293 {
294   //
295   /// Get hit pattern on trigger chambers for the current trigger track
296   //
297   UShort_t pattern = 0;
298   PerformTrigTrackMatch(pattern, matchedTriggerTrack);
299   return pattern;
300 }
301
302
303 //______________________________________________________________________________
304 UShort_t AliMUONTrackHitPattern::GetHitPattern(AliMUONTrackParam* trackParam) const
305 {
306   //
307   /// Get hit pattern on trigger chambers for the current tracker track
308   //
309   UShort_t pattern = 0;
310   Bool_t isMatch[2];
311   const Int_t kNTrackingCh = AliMUONConstants::NTrackingCh();
312
313   for(Int_t ch=0; ch<4; ++ch)
314   {
315     Int_t iChamber = kNTrackingCh+ch;
316     AliMUONTrackExtrap::ExtrapToZCov(trackParam, AliMUONConstants::DefaultChamberZ(iChamber));
317     FindPadMatchingTrack(*trackParam, isMatch, iChamber);
318     for(Int_t cath=0; cath<2; ++cath)
319     {
320       if(isMatch[cath]) AliESDMuonTrack::SetFiredChamber(pattern, cath, ch);
321     }
322   }
323
324   // pattern obtained by propagation of tracker track
325   // when it does not match the trigger.
326   AliESDMuonTrack::AddEffInfo(pattern, AliESDMuonTrack::kTrackerTrackPattern);
327
328   return pattern;
329 }
330
331 //______________________________________________________________________________
332 void 
333 AliMUONTrackHitPattern::ApplyMCSCorrections(AliMUONTrackParam& trackParam) const
334 {
335   //
336   /// Returns uncertainties on extrapolated position.
337   /// Takes into account Branson plane corrections in the iron wall.
338   //
339
340   const Float_t kZFilterOut = AliMUONConstants::MuonFilterZEnd();
341   const Float_t kFilterThickness = kZFilterOut-AliMUONConstants::MuonFilterZBeg(); // cm
342
343   AliMUONTrackExtrap::ExtrapToZCov(&trackParam, kZFilterOut); // Extrap to muon filter end
344   AliMUONTrackExtrap::AddMCSEffect(&trackParam, kFilterThickness, AliMUONConstants::MuonFilterX0()); // Add MCS effects
345   return;
346 }
347
348
349 //______________________________________________________________________________
350 void 
351 AliMUONTrackHitPattern::FindPadMatchingTrack(const AliMUONTrackParam& trackParam,
352                                              Bool_t isMatch[2], Int_t iChamber) const
353 {
354     //
355     /// Given the tracker track position, searches for matching digits.
356     //
357
358     Float_t minMatchDist[2];
359
360     for(Int_t cath=0; cath<2; ++cath)
361     {
362       isMatch[cath]=kFALSE;
363       minMatchDist[cath]=fkMaxDistance/10.;
364     }
365
366     TIter next(fkDigitStore.CreateTriggerIterator());
367     AliMUONVDigit* mDigit;
368
369     while ( ( mDigit = static_cast<AliMUONVDigit*>(next()) ) )
370     {
371       Int_t currDetElemId = mDigit->DetElemId();
372       Int_t currCh = AliMpDEManager::GetChamberId(currDetElemId);
373       if(currCh!=iChamber) continue;
374       Int_t cathode = mDigit->Cathode();
375       Int_t ix = mDigit->PadX();
376       Int_t iy = mDigit->PadY();
377       Float_t xpad, ypad, zpad;
378       const AliMpVSegmentation* seg = AliMpSegmentation::Instance()
379         ->GetMpSegmentation(currDetElemId,AliMp::GetCathodType(cathode));
380       
381       AliMpPad pad = seg->PadByIndices(ix,iy,kTRUE);
382       Float_t xlocal1 = pad.GetPositionX();
383       Float_t ylocal1 = pad.GetPositionY();
384       Float_t dpx = pad.GetDimensionX();
385       Float_t dpy = pad.GetDimensionY();
386
387       fkTransformer.Local2Global(currDetElemId, xlocal1, ylocal1, 0, xpad, ypad, zpad);
388       Float_t matchDist = MinDistanceFromPad(xpad, ypad, zpad, dpx, dpy, trackParam);
389       if(matchDist>minMatchDist[cathode])continue;
390       isMatch[cathode] = kTRUE;
391       if(isMatch[0] && isMatch[1]) break;
392       minMatchDist[cathode] = matchDist;
393     }
394 }
395
396
397 //______________________________________________________________________________
398 Float_t 
399 AliMUONTrackHitPattern::MinDistanceFromPad(Float_t xPad, Float_t yPad, Float_t zPad,
400                                            Float_t dpx, Float_t dpy, 
401                                            const AliMUONTrackParam& trackParam) const
402 {
403     //
404     /// Decides if the digit belongs to the tracker track.
405     //
406
407     AliMUONTrackParam trackParamAtPadZ(trackParam);
408     AliMUONTrackExtrap::LinearExtrapToZCov(&trackParamAtPadZ, zPad);
409
410     Float_t xTrackAtPad = trackParamAtPadZ.GetNonBendingCoor();
411     Float_t yTrackAtPad = trackParamAtPadZ.GetBendingCoor();
412
413     const Float_t kNSigma = GetRecoParam()->GetSigmaCutForTrigger();
414
415     const TMatrixD& kCovParam = trackParamAtPadZ.GetCovariances();
416     
417     Float_t sigmaX = TMath::Sqrt(kCovParam(0,0));
418     Float_t sigmaY = TMath::Sqrt(kCovParam(2,2));
419
420     Float_t maxDistX = kNSigma * sigmaX; // in cm
421     Float_t maxDistY = kNSigma * sigmaY; // in cm
422
423     Float_t deltaX = TMath::Abs(xPad-xTrackAtPad)-dpx;
424     Float_t deltaY = TMath::Abs(yPad-yTrackAtPad)-dpy;
425
426     Float_t matchDist = fkMaxDistance;
427     if(deltaX<=maxDistX && deltaY<=maxDistY) matchDist = TMath::Max(deltaX, deltaY);
428
429     return matchDist;
430 }
431
432
433 //_____________________________________________________________________________
434 Int_t AliMUONTrackHitPattern::FindPadMatchingTrig(Int_t &detElemId,
435                                                   Float_t coor[2], Bool_t isMatch[2],
436                                                   TArrayI nboard[2], TArrayF &zRealMatch, Float_t y11) const
437 {
438     //
439     /// Check slat and board number of digit matching trigger track
440     //
441
442     enum {kBending, kNonBending};
443
444     Float_t minMatchDist[fgkNcathodes];
445     Int_t padsInCheckArea[fgkNcathodes];
446
447     for(Int_t cath=0; cath<fgkNcathodes; cath++){
448         isMatch[cath] = kFALSE;
449         minMatchDist[cath] = fkMaxDistance/10.;
450         padsInCheckArea[cath] = 0;
451     }
452     Int_t iChamber = AliMpDEManager::GetChamberId(detElemId);
453     Int_t ch = iChamber-10;
454     Float_t oldDeltaZ = AliMUONConstants::DefaultChamberZ(iChamber) - AliMUONConstants::DefaultChamberZ(10);
455     Float_t y = coor[1];
456     Int_t iSlat = detElemId%100;
457     Int_t trigDigitBendPlane = -1;
458     Int_t foundDetElemId = detElemId;
459     Float_t foundZmatch=999.;
460     Float_t yCoorAtPadZ=999.;
461
462     TIter next(fkDigitStore.CreateTriggerIterator());
463     AliMUONVDigit* mDigit;
464     Int_t idigit=0;
465     
466     while ( ( mDigit = static_cast<AliMUONVDigit*>(next()) ) )
467     {
468         idigit++;
469         Int_t currDetElemId = mDigit->DetElemId();
470         Int_t currCh = AliMpDEManager::GetChamberId(currDetElemId);
471         if(currCh!=iChamber) continue;
472         Int_t currSlat = currDetElemId%100;
473         Int_t slatDiff = TMath::Abs(currSlat-iSlat);
474         if(slatDiff>1 && slatDiff<17) continue; // Check neighbour slats
475         Int_t cathode = mDigit->Cathode();
476         Int_t ix = mDigit->PadX();
477         Int_t iy = mDigit->PadY();
478         Float_t xpad, ypad, zpad;
479         const AliMpVSegmentation* seg = AliMpSegmentation::Instance()
480             ->GetMpSegmentation(currDetElemId,AliMp::GetCathodType(cathode));
481
482         AliMpPad pad = seg->PadByIndices(ix,iy,kTRUE);
483         Float_t xlocal1 = pad.GetPositionX();
484         Float_t ylocal1 = pad.GetPositionY();
485         Float_t dpx = pad.GetDimensionX();
486         Float_t dpy = pad.GetDimensionY();
487
488         fkTransformer.Local2Global(currDetElemId, xlocal1, ylocal1, 0, xpad, ypad, zpad);
489         AliDebug(2, Form("\nDetElemId = %i  Cathode = %i  Pad = (%i,%i) = (%.2f,%.2f)  Dim = (%.2f,%.2f)  Track = (%.2f,%.2f)\n",currDetElemId,cathode,ix,iy,xpad,ypad,dpx,dpy,coor[0],coor[1]));
490         // searching track intersection with chambers (second approximation)
491         if(ch%2==1){
492             //if(iChamber%2==1){
493             Float_t deltaZ = zpad - zRealMatch[0];
494             y = (coor[1]-y11)*deltaZ/oldDeltaZ + y11;
495             if(TMath::Abs(y-coor[1])>0.1) AliDebug(3, Form("oldDeltaZ = %7.2f   newDeltaZ = %7.2f\toldY = %7.2f   new y = %7.2f\n",oldDeltaZ,deltaZ,coor[1],y));
496         }
497         Float_t matchDist = PadMatchTrack(xpad, ypad, dpx, dpy, coor[0], y);
498         if(matchDist<fkMaxDistance/2.) padsInCheckArea[cathode]++;
499         if(matchDist>minMatchDist[cathode])continue;
500         isMatch[cathode] = kTRUE;
501         minMatchDist[cathode] = matchDist;
502         foundDetElemId = currDetElemId;
503         foundZmatch=zpad;
504         yCoorAtPadZ=y;
505         if(cathode==kBending) trigDigitBendPlane = idigit;
506         for (Int_t loc=0; loc<pad.GetNofLocations(); loc++){
507             nboard[cathode][loc] = pad.GetLocalBoardId(loc);
508         }
509         for(Int_t loc=pad.GetNofLocations(); loc<fgkNlocations; loc++){
510             nboard[cathode][loc]=-1;
511         }
512     }
513
514     if(isMatch[kBending] || isMatch[kNonBending]){
515         detElemId = foundDetElemId;
516         zRealMatch[ch] = foundZmatch;
517         coor[1] = yCoorAtPadZ;
518     }
519
520     // If track matches many pads, it is not good for effciency determination.
521     // However we still want to calculate the hit pattern.
522     for(Int_t cath=0; cath<fgkNcathodes; cath++){
523       if(padsInCheckArea[cath]>2) {
524         AliDebug(1, Form("padsInCheckArea[%i] = %i\n",cath,padsInCheckArea[cath]));
525         return -500;
526       }
527     }
528
529     return trigDigitBendPlane;
530 }
531
532 //_____________________________________________________________________________
533 Float_t AliMUONTrackHitPattern::PadMatchTrack(Float_t xPad, Float_t yPad,
534                                                 Float_t dpx, Float_t dpy, 
535                                                 Float_t xTrackAtPad, Float_t yTrackAtPad) const
536 {
537     //
538     /// Decides if the digit belongs to the trigger track.
539     //
540
541   Float_t maxDist = GetRecoParam()->GetStripCutForTrigger() * 2. * TMath::Min(dpx,dpy); // cm
542   if(maxDist<2.) maxDist = 2.;
543   Float_t maxDistCheckArea = GetRecoParam()->GetMaxStripAreaForTrigger() * 2. *  TMath::Min(dpx,dpy); // cm
544
545     Float_t matchDist = fkMaxDistance;
546
547     Float_t deltaX = TMath::Abs(xPad-xTrackAtPad)-dpx;
548     Float_t deltaY = TMath::Abs(yPad-yTrackAtPad)-dpy;
549     Float_t maxDistX = maxDist;
550     Float_t maxDistY = maxDist;
551
552     if(deltaX<=maxDistX && deltaY<=maxDistY) matchDist = TMath::Max(deltaX, deltaY);
553     else if(deltaX<=maxDistCheckArea && deltaY<=maxDistCheckArea) matchDist = fkMaxDistance/5.;
554     return matchDist;
555 }
556
557
558 //_____________________________________________________________________________
559 Int_t AliMUONTrackHitPattern::DetElemIdFromPos(Float_t x, Float_t y, 
560                                                  Int_t chamber, Int_t cathode) const
561 {
562     //
563     /// Given the (x,y) position in the chamber,
564     /// it returns the corresponding slat
565     //
566
567     Int_t resultingDetElemId = -1;
568     AliMpDEIterator it;
569     Float_t minDist = 999.;
570     for ( it.First(chamber-1); ! it.IsDone(); it.Next() ){
571         Int_t detElemId = it.CurrentDEId();
572         Int_t ich = detElemId/100-10;
573         Float_t tolerance=0.2*((Float_t)ich);
574         Float_t currDist=9999.;
575
576         const AliMpVSegmentation* seg = 
577             AliMpSegmentation::Instance()
578             ->GetMpSegmentation(detElemId,AliMp::GetCathodType(cathode));
579         if (!seg) continue;
580
581         Float_t deltax = seg->GetDimensionX();
582         Float_t deltay = seg->GetDimensionY();
583         Float_t xlocal1 =  -deltax;
584         Float_t ylocal1 =  -deltay;
585         Float_t xlocal2 =  +deltax;
586         Float_t ylocal2 =  +deltay;
587         Float_t xg01, yg01, zg1, xg02, yg02, zg2;
588         fkTransformer.Local2Global(detElemId, xlocal1, ylocal1, 0, xg01, yg01, zg1);
589         fkTransformer.Local2Global(detElemId, xlocal2, ylocal2, 0, xg02, yg02, zg2);
590
591         Float_t xg1 = xg01, xg2 = xg02, yg1 = yg01, yg2 = yg02;
592
593         if(xg01>xg02){
594             xg1 = xg02;
595             xg2 = xg01;
596         }
597         if(yg01>yg02){
598             yg1 = yg02;
599             yg2 = yg01;
600         }
601
602         if(x>=xg1-tolerance && x<=xg2+tolerance && y>=yg1-tolerance && y<=yg2+tolerance){ // takes into account errors in extrapolation
603             if(y<yg1) currDist = yg1-y;
604             else if(y>yg2) currDist = y-yg2;
605             if(currDist<minDist) {
606                 resultingDetElemId = detElemId;
607                 minDist=currDist;
608                 continue;
609             }
610             resultingDetElemId = detElemId;
611             break;
612         }
613     } // loop on detElemId
614     return resultingDetElemId;
615 }
616
617
618 //_____________________________________________________________________________
619 void AliMUONTrackHitPattern::LocalBoardFromPos(Float_t x, Float_t y,
620                                                  Int_t detElemId, Int_t cathode,
621                                                  Int_t localBoard[4]) const
622 {
623     //
624     /// Given the (x,y) position in the chamber,
625     /// it returns the corresponding local board
626     //
627
628     for(Int_t loc=0; loc<fgkNlocations; loc++){
629         localBoard[loc]=-1;
630     }
631     Float_t xg, yg, zg;
632     fkTransformer.Local2Global(detElemId, 0., 0., 0., xg, yg, zg);
633     Float_t z = zg - (y-yg)*TMath::Tan(TMath::DegToRad()*AliMUONConstants::St345Inclination());
634     Float_t xl, yl, zl;
635     fkTransformer.Global2Local(detElemId, x, y, z, xl, yl, zl);
636     const AliMpVSegmentation* seg = 
637         AliMpSegmentation::Instance()
638           ->GetMpSegmentation(detElemId,AliMp::GetCathodType(cathode));
639     if ( ! seg ) return;
640     AliMpPad pad = seg->PadByPosition(xl,yl,kFALSE);
641     if ( ! pad.IsValid() ){
642       AliWarning(Form("Pad not found! DetElemId %i  position global (%f, %f, %f)  local (%f, %f, %f)\n", detElemId, x, y, z, xl, yl, zl));
643       return;
644     }
645
646     AliDebug(2, Form("\nWould match: DetElemId = %i  Pad = (%i,%i) = (%.2f,%.2f,%.2f)   Board %3i\n",detElemId,pad.GetIx(),pad.GetIy(),xl,yl,zl,pad.GetLocalBoardId(0)));
647
648     for (Int_t loc=0; loc<pad.GetNofLocations(); loc++){
649       localBoard[loc] = pad.GetLocalBoardId(loc);
650     }
651 }
652
653
654 //_____________________________________________________________________________
655 Bool_t AliMUONTrackHitPattern::PerformTrigTrackMatch(UShort_t &pattern,
656                                                      const AliMUONTriggerTrack* matchedTrigTrack) const
657 {
658   //
659   /// It searches for matching digits around the trigger track.
660   //
661
662   enum {kBending, kNonBending};
663
664   Int_t chOrder[fgkNchambers] = {0,2,1,3};
665
666   TArrayF zRealMatch(fgkNchambers);
667
668   Bool_t isMatch[fgkNcathodes];
669   for(Int_t cath=0; cath<fgkNcathodes; cath++){
670     isMatch[cath] = kFALSE;
671   }
672
673   TArrayF zMeanChamber(fgkNchambers);
674   zMeanChamber[0] = matchedTrigTrack->GetZ11();
675   zMeanChamber[1] = matchedTrigTrack->GetZ11() + AliMUONConstants::DefaultChamberZ(11) - AliMUONConstants::DefaultChamberZ(10);
676   zMeanChamber[2] = matchedTrigTrack->GetZ21();
677   zMeanChamber[3] = matchedTrigTrack->GetZ21() + AliMUONConstants::DefaultChamberZ(13) - AliMUONConstants::DefaultChamberZ(12);
678
679   TArrayI digitPerTrack(fgkNcathodes);
680
681   Float_t trackIntersectCh[fgkNchambers][fgkNcathodes];
682
683   TArrayI triggeredDigits;
684   triggeredDigits.Set(fgkNchambers);
685   triggeredDigits.Reset(-1);
686
687   TArrayI trigScheme[fgkNcathodes];
688   TArrayI slatThatTriggered[fgkNcathodes];
689   for(Int_t cath=0; cath<fgkNcathodes; cath++){
690     trigScheme[cath].Set(fgkNchambers);
691     slatThatTriggered[cath].Set(fgkNchambers);
692   }
693
694   Int_t boardThatTriggered[fgkNchambers][fgkNcathodes][fgkNlocations];
695   TArrayI nboard[fgkNcathodes];
696   for(Int_t cath=0; cath<fgkNcathodes; cath++){
697     nboard[cath].Set(fgkNlocations);
698   }
699   Int_t ineffBoard[fgkNlocations];
700   for(Int_t loc=0; loc<fgkNlocations; loc++){
701     ineffBoard[loc] = -1;
702   }
703
704   digitPerTrack.Reset();
705   for(Int_t ch=0; ch<fgkNchambers; ch++){
706     zRealMatch[ch] = zMeanChamber[ch];
707     for(Int_t cath=0; cath<fgkNcathodes; cath++){
708       for(Int_t loc=0; loc<fgkNlocations; loc++){
709         boardThatTriggered[ch][cath][loc]=-1;
710       }
711     }
712   }
713
714   for(Int_t cath=0; cath<fgkNcathodes; cath++){
715     slatThatTriggered[cath].Reset(-1);
716     trigScheme[cath].Reset();
717   }
718
719   Bool_t isClearEvent = kTRUE;
720
721   Float_t y11 = matchedTrigTrack->GetY11();// y position (info from bending plane)
722   Float_t slopeX = matchedTrigTrack->GetSlopeX();
723   Float_t slopeY = matchedTrigTrack->GetSlopeY();
724
725   for(Int_t ch=0; ch<fgkNchambers; ch++) { // chamber loop
726     Int_t currCh = chOrder[ch];
727     AliDebug(3, Form("zMeanChamber[%i] = %.2f\tzRealMatch[0] = %.2f\n",currCh,zMeanChamber[currCh],zRealMatch[0]));
728
729     // searching track intersection with chambers (first approximation)
730     Float_t deltaZ = zMeanChamber[currCh] - zMeanChamber[0];
731     trackIntersectCh[currCh][0] = zMeanChamber[currCh] * slopeX;
732     trackIntersectCh[currCh][1] = y11 + deltaZ * slopeY;
733     Int_t detElemIdFromTrack = DetElemIdFromPos(trackIntersectCh[currCh][0], trackIntersectCh[currCh][1], 11+currCh, 0);
734     if(detElemIdFromTrack<0) {
735       AliDebug(1, "Warning: trigger track outside trigger chamber\n");
736       isClearEvent = kFALSE;
737
738       // track is rejected since the extrapolated track
739       // does not match a slat (border effects)
740       AliESDMuonTrack::AddEffInfo(pattern, AliESDMuonTrack::kTrackOutsideGeometry);
741       continue;
742     }
743                 
744     triggeredDigits[currCh] = FindPadMatchingTrig(detElemIdFromTrack, trackIntersectCh[currCh], isMatch, nboard, zRealMatch, y11);
745
746     // if FindPadMatchingTrig = -500 => too many digits matching pad =>
747     //                               => Event not clear => Do not use for efficiency calculation
748     if(triggeredDigits[currCh]<-100){
749       isClearEvent = kFALSE;
750       // track is rejected since it matches many pads
751       AliESDMuonTrack::AddEffInfo(pattern, AliESDMuonTrack::kTrackMatchesManyPads);
752       AliDebug(1, Form("Warning: track = %p (%i) matches many pads. Rejected!\n",(void *)matchedTrigTrack, detElemIdFromTrack));
753     }
754
755     for(Int_t cath=0; cath<fgkNcathodes; cath++){
756       if(!isMatch[cath]) continue;
757       AliESDMuonTrack::SetFiredChamber(pattern, cath, currCh);
758       digitPerTrack[cath]++;
759       trigScheme[cath][currCh]++;
760       slatThatTriggered[cath][currCh] = detElemIdFromTrack;
761       for(Int_t loc=0; loc<fgkNlocations; loc++){
762         boardThatTriggered[currCh][cath][loc] = nboard[cath][loc];
763       }
764     }
765   } // end chamber loop
766
767   for(Int_t cath=0; cath<fgkNcathodes; cath++){
768     if(digitPerTrack[cath]<3) {
769       isClearEvent = kFALSE;
770       // track is rejected since the number of associated
771       // digits found is less than 3.
772       AliESDMuonTrack::AddEffInfo(pattern, AliESDMuonTrack::kTrackMatchesFewPads);
773       AliDebug(1, Form("Warning: found %i digits for trigger track cathode %i.\nRejecting event\n", digitPerTrack[cath],cath));
774     }
775   }
776
777   if(!isClearEvent) return kFALSE;
778
779   AliESDMuonTrack::EAliTriggerChPatternFlag goodForEff = AliESDMuonTrack::kBoardEff;
780
781   Int_t ineffSlat = -1;
782   Int_t ineffDetElId = -1;
783   Int_t firstSlat = slatThatTriggered[kBending][0]%100;
784   if(firstSlat<0) firstSlat = slatThatTriggered[kBending][1]%100;
785   Int_t firstBoard = boardThatTriggered[0][kBending][0];
786   if(firstBoard<0) firstBoard = boardThatTriggered[1][kBending][0];
787   for(Int_t ch=0; ch<fgkNchambers; ch++){
788     Bool_t isCurrChIneff = kFALSE;
789     Int_t currSlat = slatThatTriggered[kBending][ch]%100;
790     if(currSlat<0){
791       ineffDetElId = DetElemIdFromPos(trackIntersectCh[ch][0], trackIntersectCh[ch][1], 11+ch, kBending);
792       currSlat = ineffDetElId%100;
793       ineffSlat = currSlat;
794       isCurrChIneff = kTRUE;
795     }
796     if(currSlat!=firstSlat) {
797       AliESDMuonTrack::AddEffInfo(pattern,
798                                   AliESDMuonTrack::kCrossDifferentSlats,
799                                   AliESDMuonTrack::kChEff); // track crosses different slats
800       return kTRUE;
801     }
802     Bool_t atLeastOneLoc=kFALSE;
803     if(isCurrChIneff) LocalBoardFromPos(trackIntersectCh[ch][0], trackIntersectCh[ch][1], ineffDetElId, kBending, ineffBoard);
804     for(Int_t loc=0; loc<fgkNlocations; loc++){
805       Int_t currBoard = boardThatTriggered[ch][kBending][loc];
806       if(isCurrChIneff) currBoard = ineffBoard[loc];
807       if(currBoard==firstBoard){
808         atLeastOneLoc=kTRUE;
809         break;
810       }
811     }
812     if(!atLeastOneLoc) goodForEff = AliESDMuonTrack::kSlatEff;
813   } // end chamber loop
814   
815   AliESDMuonTrack::AddEffInfo(pattern, firstSlat, goodForEff);
816   return kTRUE;
817 }