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