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