]> git.uio.no Git - u/mrichter/AliRoot.git/blob - MUON/AliMUONClusterFinderAZ.cxx
Added a commented out version with new digitizers.
[u/mrichter/AliRoot.git] / MUON / AliMUONClusterFinderAZ.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 // Clusterizer class developed by A. Zinchenko (Dubna)
19
20 #include <stdlib.h>
21 #include <Riostream.h>
22 //#include <TROOT.h>
23 #include <TH2.h>
24 #include <TMinuit.h>
25 #include <TMatrixD.h>
26
27 #include "AliMUONClusterFinderAZ.h"
28 #include "AliMUONClusterDrawAZ.h"
29 #include "AliHeader.h"
30 #include "AliRun.h"
31 #include "AliMUON.h"
32 //#include "AliMUONChamber.h"
33 #include "AliMUONDigit.h"
34 //#include "AliMUONHit.h"
35 #include "AliMUONRawCluster.h"
36 #include "AliMUONClusterInput.h"
37 #include "AliMUONPixel.h"
38 //#include "AliMC.h"
39 //#include "AliMUONLoader.h"
40 #include "AliLog.h"
41
42 ClassImp(AliMUONClusterFinderAZ)
43  
44  const Double_t AliMUONClusterFinderAZ::fgkCouplMin = 1.e-3; // threshold on coupling 
45  AliMUONClusterFinderAZ* AliMUONClusterFinderAZ::fgClusterFinder = 0x0;
46  TMinuit* AliMUONClusterFinderAZ::fgMinuit = 0x0;
47 //FILE *lun1 = fopen("nxny.dat","w");
48
49 //_____________________________________________________________________________
50 AliMUONClusterFinderAZ::AliMUONClusterFinderAZ(Bool_t draw)
51   : AliMUONClusterFinderVS()
52 {
53 // Constructor
54   fnPads[0]=fnPads[1]=0;
55   
56   for (Int_t i=0; i<7; i++)
57     for (Int_t j=0; j<fgkDim; j++)
58       fXyq[i][j]= 9999.;
59
60   for (Int_t i=0; i<2; i++)
61     for (Int_t j=0; j<fgkDim; j++) {
62       fPadIJ[i][j]=-1;
63       fUsed[i][j] = 0;
64     }
65
66   fSegmentation[1] = fSegmentation[0] = 0;
67   fResponse = 0x0;
68
69   fZpad = 100000;
70   fNpar = 0;
71   fQtot = 0;
72   fReco = 1;
73
74   fCathBeg = 0;
75   fPadBeg[0] = fPadBeg[1] = 0;
76   if (!fgMinuit) fgMinuit = new TMinuit(8);
77
78   if (!fgClusterFinder) fgClusterFinder = this;
79   fDraw = 0;
80   fPixArray = new TObjArray(20); 
81   fnCoupled = 0;
82   fDebug = 0; //0;
83
84   if (draw) {
85     fDebug = 1;
86     fReco = 0;
87     fDraw = new AliMUONClusterDrawAZ(this);
88   }
89   cout << " *** Running AZ cluster finder *** " << endl;
90 }
91
92 //_____________________________________________________________________________
93 AliMUONClusterFinderAZ::AliMUONClusterFinderAZ(const AliMUONClusterFinderAZ& rhs)
94   : AliMUONClusterFinderVS(rhs)
95 {
96 // Protected copy constructor
97
98   AliFatal("Not implemented.");
99 }
100
101 //_____________________________________________________________________________
102 AliMUONClusterFinderAZ::~AliMUONClusterFinderAZ()
103 {
104   // Destructor
105   delete fgMinuit; fgMinuit = 0; delete fPixArray; fPixArray = 0;
106   delete fDraw;
107 }
108
109 //_____________________________________________________________________________
110 void AliMUONClusterFinderAZ::FindRawClusters()
111 {
112 // To provide the same interface as in AliMUONClusterFinderVS
113
114   ResetRawClusters(); 
115   EventLoop (gAlice->GetHeader()->GetEvent(), AliMUONClusterInput::Instance()->Chamber());
116 }
117
118 //_____________________________________________________________________________
119 void AliMUONClusterFinderAZ::EventLoop(Int_t nev, Int_t ch)
120 {
121 // Loop over digits
122   
123   if (fDraw && !fDraw->FindEvCh(nev, ch)) return;
124
125   AliMUON *pMuon = (AliMUON*) gAlice->GetModule("MUON");
126   AliMUONChamber *iChamber = &(pMuon->Chamber(ch));
127   fResponse = iChamber->ResponseModel();
128   fSegmentation[0] = AliMUONClusterInput::Instance()->Segmentation2(0);
129   fSegmentation[1] = AliMUONClusterInput::Instance()->Segmentation2(1);
130   //AZ fResponse = AliMUONClusterInput::Instance()->Response();
131     
132   Int_t ndigits[2] = {9,9}, nShown[2] = {0};
133   if (fReco != 2) { // skip initialization for the combined cluster / track
134     fCathBeg = fPadBeg[0] = fPadBeg[1] = 0;
135     for (Int_t i = 0; i < 2; i++) {
136       for (Int_t j = 0; j < fgkDim; j++) { fUsed[i][j] = kFALSE; }
137     }
138   }
139
140 next:
141   if (fReco == 2 && (nShown[0] || nShown[1])) return; // only one precluster for the combined finder
142   if (ndigits[0] == nShown[0] && ndigits[1] == nShown[1]) return;
143
144   Float_t xpad, ypad, zpad, zpad0;
145   Bool_t first = kTRUE;
146   if (fDebug) cout << " *** Event # " << nev << " chamber: " << ch << endl;
147   fnPads[0] = fnPads[1] = 0;
148   for (Int_t i = 0; i < fgkDim; i++) fPadIJ[1][i] = 0; 
149
150   for (Int_t iii = fCathBeg; iii < 2; iii++) { 
151     Int_t cath = TMath::Odd(iii);
152     ndigits[cath] = AliMUONClusterInput::Instance()->NDigits(cath); 
153     if (!ndigits[0] && !ndigits[1]) return;
154     if (ndigits[cath] == 0) continue;
155     if (fDebug) cout << " ndigits: " << ndigits[cath] << " " << cath << endl;
156
157     AliMUONDigit  *mdig;
158     Int_t digit;
159
160     Bool_t eEOC = kTRUE; // end-of-cluster
161     for (digit = fPadBeg[cath]; digit < ndigits[cath]; digit++) {
162       mdig = AliMUONClusterInput::Instance()->Digit(cath,digit); 
163       if (first) {
164         // Find first unused pad
165         if (fUsed[cath][digit]) continue;
166         if (!fSegmentation[cath]->GetPadC(fInput->DetElemId(),mdig->PadX(),mdig->PadY(),xpad,ypad,zpad0)) { 
167           // Handle "non-existing" pads
168           fUsed[cath][digit] = kTRUE; 
169           continue; 
170         } 
171       } else {
172         if (fUsed[cath][digit]) continue;
173         if (!fSegmentation[cath]->GetPadC(fInput->DetElemId(),mdig->PadX(),mdig->PadY(),xpad,ypad,zpad)) {
174           // Handle "non-existing" pads
175           fUsed[cath][digit] = kTRUE; 
176           continue; 
177         } 
178         if (TMath::Abs(zpad-zpad0) > 0.1) continue; // different slats
179         // Find a pad overlapping with the cluster
180         if (!Overlap(cath,mdig)) continue;
181       }
182       // Add pad - recursive call
183       AddPad(cath,digit);
184       //AZ !!!!!! Temporary fix of St1 overlap regions !!!!!!!! 
185       if (cath && ch < 2) {
186         Int_t npads = fnPads[0] + fnPads[1] - 1;
187         Int_t cath1 = fPadIJ[0][npads];
188         Int_t idig = TMath::Nint (fXyq[5][npads]);
189         mdig = AliMUONClusterInput::Instance()->Digit(cath1,idig);
190         fSegmentation[cath1]->GetPadC(fInput->DetElemId(),mdig->PadX(),mdig->PadY(),xpad,ypad,zpad);
191         if (TMath::Abs(zpad-zpad0) > 0.1) zpad0 = zpad;
192       } 
193       eEOC = kFALSE;
194       if (digit >= 0) break;
195     }
196     if (first && eEOC) {
197       // No more unused pads 
198       if (cath == 0) continue; // on cathode #0 - check #1
199       else return; // No more clusters
200     }
201     if (eEOC) break; // cluster found
202     first = kFALSE;
203     if (fDebug) cout << " nPads: " << fnPads[cath] << " " << nShown[cath]+fnPads[cath] << " " << cath << endl;
204   } // for (Int_t iii = 0;
205
206   fZpad = zpad0;
207   if (fDraw) fDraw->DrawCluster(); 
208
209   // Use MLEM for cluster finder
210   Int_t nMax = 1, localMax[100], maxPos[100];
211   Double_t maxVal[100];
212   
213   if (CheckPrecluster(nShown)) {
214     BuildPixArray();
215     if (fnPads[0]+fnPads[1] > 50) nMax = FindLocalMaxima(localMax, maxVal);
216     if (nMax > 1) TMath::Sort(nMax, maxVal, maxPos, kTRUE); // in decreasing order
217     Int_t iSimple = 0, nInX = -1, nInY;
218     PadsInXandY(nInX, nInY);
219     if (fDebug) cout << "Pads in X and Y: " << nInX << " " << nInY << endl;
220     if (nMax == 1 && nInX < 4 && nInY < 4) iSimple = 1; //1; // simple cluster
221     for (Int_t i=0; i<nMax; i++) {
222       if (nMax > 1) FindCluster(localMax, maxPos[i]);
223       if (!MainLoop(iSimple)) cout << " MainLoop failed " << endl;
224       if (i < nMax-1) {
225         for (Int_t j=0; j<fnPads[0]+fnPads[1]; j++) {
226           if (fPadIJ[1][j] == 0) continue; // pad charge was not modified
227           fPadIJ[1][j] = 0;
228           fXyq[2][j] = fXyq[6][j]; // use backup charge value
229         }
230       }
231     }
232   }
233   if (!fDraw || fDraw->Next()) goto next;
234 }
235
236 //_____________________________________________________________________________
237 void AliMUONClusterFinderAZ::AddPad(Int_t cath, Int_t digit)
238 {
239   // Add pad to the cluster
240   AliMUONDigit *mdig = AliMUONClusterInput::Instance()->Digit(cath,digit); //AZ
241
242   Int_t charge = mdig->Signal();
243   // get the center of the pad
244   Float_t xpad, ypad, zpad0; //, zpad;
245   if (!fSegmentation[cath]->GetPadC(fInput->DetElemId(),mdig->PadX(),mdig->PadY(),xpad,ypad,zpad0)) {     // Handle "non-existing" pads
246     fUsed[cath][digit] = kTRUE; 
247     return; 
248   } 
249   Int_t isec = fSegmentation[cath]->Sector(fInput->DetElemId(), mdig->PadX(), mdig->PadY());
250   Int_t nPads = fnPads[0] + fnPads[1];
251   fXyq[0][nPads] = xpad;
252   fXyq[1][nPads] = ypad;
253   fXyq[2][nPads] = charge;
254   fXyq[3][nPads] = fSegmentation[cath]->Dpx(fInput->DetElemId(),isec)/2;
255   fXyq[4][nPads] = fSegmentation[cath]->Dpy(fInput->DetElemId(),isec)/2;
256   fXyq[5][nPads] = digit;
257   fXyq[6][nPads] = 0;
258   fPadIJ[0][nPads] = cath;
259   fPadIJ[1][nPads] = 0;
260   fUsed[cath][digit] = kTRUE;
261   if (fDebug) printf(" bbb %d %d %f %f %f %f %f %4d %3d %3d\n", nPads, cath, xpad, ypad, zpad0, fXyq[3][nPads]*2, fXyq[4][nPads]*2, charge, mdig->PadX(), mdig->PadY());
262   fnPads[cath]++;
263
264   // Check neighbours
265   Int_t nn, ix, iy, xList[10], yList[10];
266   AliMUONDigit  *mdig1;
267
268   Int_t ndigits = AliMUONClusterInput::Instance()->NDigits(cath); 
269   fSegmentation[cath]->Neighbours(fInput->DetElemId(),mdig->PadX(),mdig->PadY(),&nn,xList,yList); 
270   for (Int_t in=0; in<nn; in++) {
271     ix=xList[in];
272     iy=yList[in];
273     for (Int_t digit1 = 0; digit1 < ndigits; digit1++) {
274       if (digit1 == digit) continue;
275       mdig1 = AliMUONClusterInput::Instance()->Digit(cath,digit1); 
276       if (!fUsed[cath][digit1] && mdig1->PadX() == ix && mdig1->PadY() == iy) {
277         //AZ--- temporary fix on edges
278         //fSegmentation[cath]->GetPadC(mdig1->PadX(), mdig1->PadY(), xpad, ypad, zpad);
279         //if (TMath::Abs(zpad-zpad0) > 0.5) continue;
280         //AZ---
281         fUsed[cath][digit1] = kTRUE;
282         // Add pad - recursive call
283         AddPad(cath,digit1);
284       }
285     } //for (Int_t digit1 = 0;
286   } // for (Int_t in=0;
287 }
288
289 //_____________________________________________________________________________
290 Bool_t AliMUONClusterFinderAZ::Overlap(Int_t cath, AliMUONDigit *mdig)
291 {
292   // Check if the pad from one cathode overlaps with a pad 
293   // in the precluster on the other cathode
294
295   Float_t xpad, ypad, zpad;
296   fSegmentation[cath]->GetPadC(fInput->DetElemId(),mdig->PadX(),mdig->PadY(),xpad,ypad,zpad);
297   Int_t   isec = fSegmentation[cath]->Sector(fInput->DetElemId(),mdig->PadX(), mdig->PadY());
298
299   Float_t xy1[4], xy12[4];
300   xy1[0] = xpad - fSegmentation[cath]->Dpx(fInput->DetElemId(),isec)/2;
301   xy1[1] = xy1[0] + fSegmentation[cath]->Dpx(fInput->DetElemId(),isec);
302   xy1[2] = ypad - fSegmentation[cath]->Dpy(fInput->DetElemId(),isec)/2;
303   xy1[3] = xy1[2] + fSegmentation[cath]->Dpy(fInput->DetElemId(),isec);
304   //cout << " ok " << fnPads[0]+fnPads[1] << xy1[0] << xy1[1] << xy1[2] << xy1[3] << endl;
305
306   Int_t cath1 = TMath::Even(cath);
307   for (Int_t i=0; i<fnPads[0]+fnPads[1]; i++) {
308     if (fPadIJ[0][i] != cath1) continue;
309     if (Overlap(xy1, i, xy12, 0)) return kTRUE;
310   }
311   return kFALSE;
312 }
313
314 //_____________________________________________________________________________
315 Bool_t AliMUONClusterFinderAZ::Overlap(Float_t *xy1, Int_t iPad, Float_t *xy12, Int_t iSkip)
316 {
317   // Check if the pads xy1 and iPad overlap and return overlap area
318
319   Float_t xy2[4];
320   xy2[0] = fXyq[0][iPad] - fXyq[3][iPad];
321   xy2[1] = fXyq[0][iPad] + fXyq[3][iPad];
322   if (xy1[0] > xy2[1]-1.e-4 || xy1[1] < xy2[0]+1.e-4) return kFALSE;
323   xy2[2] = fXyq[1][iPad] - fXyq[4][iPad];
324   xy2[3] = fXyq[1][iPad] + fXyq[4][iPad];
325   if (xy1[2] > xy2[3]-1.e-4 || xy1[3] < xy2[2]+1.e-4) return kFALSE;
326   if (!iSkip) return kTRUE; // just check overlap (w/out computing the area)
327   xy12[0] = TMath::Max (xy1[0],xy2[0]);
328   xy12[1] = TMath::Min (xy1[1],xy2[1]);
329   xy12[2] = TMath::Max (xy1[2],xy2[2]);
330   xy12[3] = TMath::Min (xy1[3],xy2[3]);
331   return kTRUE;
332 }
333
334 //_____________________________________________________________________________
335 Bool_t AliMUONClusterFinderAZ::CheckPrecluster(Int_t *nShown)
336 {
337   // Check precluster in order to attempt to simplify it (mostly for
338   // two-cathode preclusters)
339
340   Int_t i1, i2, cath=0, digit=0;
341   Float_t xy1[4], xy12[4];
342   
343   Int_t npad = fnPads[0] + fnPads[1];
344   if (npad == 1) { 
345     // Disregard one-pad clusters (leftovers from splitting)
346     nShown[0] += fnPads[0]; 
347     nShown[1] += fnPads[1]; 
348     return kFALSE;
349   }
350
351   // If pads have the same size take average of pads on both cathodes 
352   Int_t sameSize = (fnPads[0] && fnPads[1]) ? 1 : 0;
353   if (sameSize) {
354     Double_t xSize = -1, ySize = 0;
355     for (Int_t i=0; i<npad; i++) {
356       if (fXyq[2][i] < 0) continue;
357       if (xSize < 0) { xSize = fXyq[3][i]; ySize = fXyq[4][i]; }
358       if (TMath::Abs(xSize-fXyq[3][i]) > 1.e-4 ||  TMath::Abs(ySize-fXyq[4][i]) > 1.e-4) { sameSize = 0; break; }
359     }
360   } // if (sameSize)
361   if (sameSize && fnPads[0] == 1 && fnPads[1] == 1) sameSize = 0; //AZ
362   // Handle shift by half a pad in Station 1
363   if (sameSize) {
364     Int_t cath0 = fPadIJ[0][0];
365     for (Int_t i = 1; i < npad; i++) {
366       if (fPadIJ[0][i] == cath0) continue;
367       Double_t dx = TMath::Abs ((fXyq[0][i] - fXyq[0][0]) / fXyq[3][i] / 2);
368       Int_t idx = (Int_t) TMath::Abs ((fXyq[0][i] - fXyq[0][0]) / fXyq[3][i] / 2);
369       if (TMath::Abs (dx - idx) > 0.001) sameSize = 0;
370       break;
371     }
372   } // if (sameSize)
373    
374   if (sameSize && (fnPads[0] >= 2 || fnPads[1] >= 2)) {
375     nShown[0] += fnPads[0];
376     nShown[1] += fnPads[1];
377     fnPads[0] = fnPads[1] = 0;
378     Int_t div;
379     for (Int_t i=0; i<npad; i++) {
380       if (fXyq[2][i] < 0) continue; // used pad
381       fXyq[2][fnPads[0]] = fXyq[2][i];
382       div = 1;
383       cath = fPadIJ[0][i];
384       for (Int_t j=i+1; j<npad; j++) {
385         if (fPadIJ[0][j] == fPadIJ[0][i]) continue; // same cathode
386         if (TMath::Abs(fXyq[0][j]-fXyq[0][i]) > 1.e-4) continue;
387         if (TMath::Abs(fXyq[1][j]-fXyq[1][i]) > 1.e-4) continue;
388         fXyq[2][fnPads[0]] += fXyq[2][j];
389         div = 2;
390         fXyq[2][j] = -2;
391         if (cath) fXyq[5][fnPads[0]] = fXyq[5][j]; // save digit number for cath 0
392         break;
393       }
394       // Flag that the digit from the other cathode
395       if (cath && div == 1) fXyq[5][fnPads[0]] = -fXyq[5][i] - 1; 
396       // If low pad charge take the other equal to 0 
397       if (div == 1 && fXyq[2][fnPads[0]] < fResponse->ZeroSuppression() + 1.5*3) div = 2;
398       fXyq[2][fnPads[0]] /= div;
399       fXyq[0][fnPads[0]] = fXyq[0][i];
400       fXyq[1][fnPads[0]] = fXyq[1][i];
401       fPadIJ[0][fnPads[0]++] = 0;
402     }
403   } // if (sameSize)
404
405   // Check if one-cathode precluster
406   i1 = fnPads[0]!=0 ? 0 : 1;
407   i2 = fnPads[1]!=0 ? 1 : 0;
408
409   if (i1 != i2) { // two-cathode 
410
411     Int_t *flags = new Int_t[npad];
412     for (Int_t i=0; i<npad; i++) { flags[i] = 0; }
413
414     // Check pad overlaps
415     for (Int_t i=0; i<npad; i++) {
416       if (fPadIJ[0][i] != i1) continue;
417       xy1[0] = fXyq[0][i] - fXyq[3][i];
418       xy1[1] = fXyq[0][i] + fXyq[3][i];
419       xy1[2] = fXyq[1][i] - fXyq[4][i];
420       xy1[3] = fXyq[1][i] + fXyq[4][i];
421       for (Int_t j=0; j<npad; j++) {
422         if (fPadIJ[0][j] != i2) continue;
423         if (!Overlap(xy1, j, xy12, 0)) continue;
424         flags[i] = flags[j] = 1; // mark overlapped pads
425       } // for (Int_t j=0;
426     } // for (Int_t i=0;
427
428     // Check if all pads overlap
429     Int_t nFlags=0;
430     for (Int_t i=0; i<npad; i++) {
431       if (flags[i]) continue;
432       nFlags ++;
433       if (fDebug) cout << i << " " << fPadIJ[0][i] << " " << fXyq[0][i] << " " << fXyq[1][i] << endl;
434     }
435     if (fDebug && nFlags) cout << " nFlags = " << nFlags << endl;
436     //if (nFlags > 2 || (Float_t)nFlags / npad > 0.2) { // why 2 ??? - empirical choice
437     if (nFlags > 1) {
438       for (Int_t i=0; i<npad; i++) {
439         if (flags[i]) continue;
440         digit = TMath::Nint (fXyq[5][i]);
441         cath = fPadIJ[0][i];
442         // Check for edge effect (missing pads on the other cathode)
443         Int_t cath1 = TMath::Even(cath), ix, iy;
444         if (!fSegmentation[cath1]->GetPadI(fInput->DetElemId(),fXyq[0][i],fXyq[1][i],fZpad,ix,iy)) continue;
445         fUsed[cath][digit] = kFALSE; // release pad
446         fXyq[2][i] = -2;
447         fnPads[cath]--;
448       }
449       if (fDraw) fDraw->UpdateCluster(npad);
450     } // if (nFlags > 2)
451
452     // Check correlations of cathode charges
453     if (fnPads[0] && fnPads[1]) { // two-cathode
454       Double_t sum[2]={0};
455       Int_t over[2] = {1, 1};
456       for (Int_t i=0; i<npad; i++) {
457         cath = fPadIJ[0][i];
458         if (fXyq[2][i] > 0) sum[cath] += fXyq[2][i];
459         //AZ if (fXyq[2][i] > fResponse->MaxAdc()-1) over[cath] = 0;
460         if (fXyq[2][i] > fResponse->Saturation()-1) over[cath] = 0;
461       }
462       if (fDebug) cout << " Total charge: " << sum[0] << " " << sum[1] << endl;
463       if ((over[0] || over[1]) && TMath::Abs(sum[0]-sum[1])/(sum[0]+sum[1])*2 > 1) { // 3 times difference
464         if (fDebug) cout << " Release " << endl;
465         // Big difference
466         cath = sum[0] > sum[1] ? 0 : 1;
467         Int_t imax = 0, imin = 0;
468         Double_t cmax = -1, cmin = 9999, dxMin = 0, dyMin = 0;
469         Double_t *dist = new Double_t[npad];
470         for (Int_t i = 0; i < npad; i++) {
471           if (fPadIJ[0][i] != cath || fXyq[2][i] < 0) continue;
472           if (fXyq[2][i] < cmin) {
473             cmin = fXyq[2][i];
474             imin = i;
475           }
476           if (fXyq[2][i] < cmax) continue;
477           cmax = fXyq[2][i];
478           imax = i;
479         }
480         // Arrange pads according to their distance to the max, 
481         // normalized to the pad size
482         for (Int_t i = 0; i < npad; i++) {
483           dist[i] = 0;
484           if (fPadIJ[0][i] != cath || fXyq[2][i] < 0) continue;
485           if (i == imax) continue; 
486           Double_t dx = (fXyq[0][i] - fXyq[0][imax]) / fXyq[3][imax] / 2;
487           Double_t dy = (fXyq[1][i] - fXyq[1][imax]) / fXyq[4][imax] / 2;
488           dist[i] = TMath::Sqrt (dx * dx + dy * dy);
489           if (i == imin) {
490             cmin = dist[i] + 0.001; // distance to the pad with minimum charge 
491             dxMin = dx;
492             dyMin = dy;
493           }
494         }
495         TMath::Sort(npad, dist, flags, kFALSE); // in increasing order
496         Int_t indx;
497         Double_t xmax = -1;
498         for (Int_t i = 0; i < npad; i++) {
499           indx = flags[i];
500           if (fPadIJ[0][indx] != cath || fXyq[2][indx] < 0) continue;
501           if (dist[indx] > cmin) {
502             // Farther than the minimum pad
503             Double_t dx = (fXyq[0][indx] - fXyq[0][imax]) / fXyq[3][imax] / 2;
504             Double_t dy = (fXyq[1][indx] - fXyq[1][imax]) / fXyq[4][imax] / 2;
505             dx *= dxMin;
506             dy *= dyMin;
507             if (dx >= 0 && dy >= 0) continue;
508             if (TMath::Abs(dx) > TMath::Abs(dy) && dx >= 0) continue;
509             if (TMath::Abs(dy) > TMath::Abs(dx) && dy >= 0) continue;
510           }
511           if (fXyq[2][indx] <= cmax || TMath::Abs(dist[indx]-xmax) < 1.e-3) {
512             // Release pads
513             if (TMath::Abs(dist[indx]-xmax) < 1.e-3) 
514                 cmax = TMath::Max((Double_t)(fXyq[2][indx]),cmax);
515             else cmax = fXyq[2][indx];
516             xmax = dist[indx];
517             digit = TMath::Nint (fXyq[5][indx]);
518             fUsed[cath][digit] = kFALSE; 
519             fXyq[2][indx] = -2;
520             fnPads[cath]--;
521           } 
522         } // for (Int_t i = 0; i < npad;
523
524         // Check pad overlaps once more
525         for (Int_t j = 0; j < npad; j++) flags[j] = 0; 
526         for (Int_t k = 0; k < npad; k++) {
527           if (fXyq[2][k] < 0 || fPadIJ[0][k] != i1) continue;
528           xy1[0] = fXyq[0][k] - fXyq[3][k];
529           xy1[1] = fXyq[0][k] + fXyq[3][k];
530           xy1[2] = fXyq[1][k] - fXyq[4][k];
531           xy1[3] = fXyq[1][k] + fXyq[4][k];
532           for (Int_t j = 0; j < npad; j++) {
533             if (fXyq[2][j] < 0) continue;
534             if (fPadIJ[0][j] != i2) continue;
535             if (!Overlap(xy1, j, xy12, 0)) continue;
536             flags[k] = flags[j] = 1; // mark overlapped pads
537           } // for (Int_t j = 0;
538         } // for (Int_t k = 0;
539         nFlags = 0;
540         for (Int_t j = 0; j < npad; j++) {
541           if (fXyq[2][j] < 0 || flags[j]) continue;
542           nFlags ++;
543         }
544         if (nFlags == fnPads[0] + fnPads[1]) {
545           // No overlap
546           for (Int_t j = 0; j < npad; j++) {
547             if (fXyq[2][j] < 0 || fPadIJ[0][j] != cath) continue;
548             fXyq[2][j] = -2;
549             fnPads[cath]--;
550           }
551         }
552         delete [] dist; dist = 0;
553         if (fDraw) fDraw->UpdateCluster(npad);
554       } // TMath::Abs(sum[0]-sum[1])...
555     } // if (fnPads[0] && fnPads[1])
556     delete [] flags; flags = 0;
557   } // if (i1 != i2) 
558
559   if (!sameSize) { nShown[0] += fnPads[0]; nShown[1] += fnPads[1]; }
560
561   // Move released pads to the right
562   Int_t beg = 0, end = npad-1, padij;
563   Double_t xyq;
564   while (beg < end) {
565     if (fXyq[2][beg] > 0) { beg++; continue; }
566     for (Int_t j=end; j>beg; j--) {
567       if (fXyq[2][j] < 0) continue;
568       end = j - 1;
569       for (Int_t j1=0; j1<2; j1++) {
570         padij = fPadIJ[j1][beg]; 
571         fPadIJ[j1][beg] = fPadIJ[j1][j];
572         fPadIJ[j1][j] = padij;
573       }
574       for (Int_t j1=0; j1<6; j1++) {
575         xyq = fXyq[j1][beg]; 
576         fXyq[j1][beg] = fXyq[j1][j];
577         fXyq[j1][j] = xyq;
578       }
579       break;
580     } // for (Int_t j=end;
581     beg++;
582   } // while
583   npad = fnPads[0] + fnPads[1];
584   if (npad > 500) { cout << " ***** Too large cluster. Give up. " << npad << endl; return kFALSE; }
585   // Back up charge value
586   for (Int_t j = 0; j < npad; j++) fXyq[6][j] = fXyq[2][j];
587
588   return kTRUE;
589 }
590
591 //_____________________________________________________________________________
592 void AliMUONClusterFinderAZ::BuildPixArray()
593 {
594   // Build pixel array for MLEM method
595   
596   Int_t nPix=0, i1, i2;
597   Float_t xy1[4], xy12[4];
598   AliMUONPixel *pixPtr=0;
599
600   Int_t npad = fnPads[0] + fnPads[1];
601
602   // One cathode is empty
603   i1 = fnPads[0]!=0 ? 0 : 1;
604   i2 = fnPads[1]!=0 ? 1 : 0;
605
606   // Build array of pixels on anode plane
607   if (i1 == i2) { // one-cathode precluster
608     for (Int_t j=0; j<npad; j++) {
609       pixPtr = new AliMUONPixel();
610       for (Int_t i=0; i<2; i++) {
611         pixPtr->SetCoord(i, fXyq[i][j]); // pixel coordinates
612         pixPtr->SetSize(i, fXyq[i+3][j]); // pixel size
613       }
614       pixPtr->SetCharge(fXyq[2][j]); // charge
615       fPixArray->Add((TObject*)pixPtr);
616       nPix++;
617     }
618   } else { // two-cathode precluster    
619     i1 = fPadIJ[0][0];
620     i2 = TMath::Even (i1);
621     for (Int_t i = 0; i < npad; i++) {
622       if (fPadIJ[0][i] != i1) continue;
623       xy1[0] = fXyq[0][i] - fXyq[3][i];
624       xy1[1] = fXyq[0][i] + fXyq[3][i];
625       xy1[2] = fXyq[1][i] - fXyq[4][i];
626       xy1[3] = fXyq[1][i] + fXyq[4][i];
627       for (Int_t j = 1; j < npad; j++) {
628         if (fPadIJ[0][j] != i2) continue;
629         if (!Overlap(xy1, j, xy12, 1)) continue;
630         pixPtr = new AliMUONPixel();
631         for (Int_t k=0; k<2; k++) {
632           pixPtr->SetCoord(k, (xy12[2*k]+xy12[2*k+1])/2); // pixel coordinates
633           pixPtr->SetSize(k, xy12[2*k+1]-pixPtr->Coord(k)); // size
634         }
635         pixPtr->SetCharge(TMath::Min (fXyq[2][i],fXyq[2][j])); //charge
636         fPixArray->Add((TObject*)pixPtr);
637         //cout << nPix << " " << pixPtr->Coord(0) << " " << pixPtr->Size(0) << " " << pixPtr->Coord(1) << " " << pixPtr->Size(1) << " " << pixPtr->Charge() << endl;
638         nPix++;
639       } // for (Int_t j=0;
640     } // for (Int_t i=0;
641   } // else
642
643   Float_t xPadMin = 999, yPadMin = 999;
644   for (Int_t i = 0; i < npad; i++) {
645     xPadMin = TMath::Min (xPadMin, fXyq[3][i]);
646     yPadMin = TMath::Min (yPadMin, fXyq[4][i]);
647   }
648   if (fDebug) cout << xPadMin << " " << yPadMin << endl;
649
650   Float_t wxmin = 999, wymin = 999;
651   for (Int_t i = 0; i < nPix; i++) {
652     pixPtr = (AliMUONPixel*) fPixArray->UncheckedAt(i);
653     wxmin = TMath::Min ((Double_t)wxmin, pixPtr->Size(0));
654     wymin = TMath::Min ((Double_t)wymin, pixPtr->Size(1));
655   }
656   if (fDebug) cout << wxmin << " " << wymin << endl;
657   wxmin = TMath::Abs (wxmin - xPadMin/2) > 0.001 ? xPadMin : xPadMin / 2;
658   wymin = TMath::Abs (wymin - yPadMin/2) > 0.001 ? yPadMin : yPadMin / 2;
659   //wxmin = xPadMin; wymin = yPadMin;
660
661   // Check if small pixel X-size
662   AdjustPixel(wxmin, 0);
663   // Check if small pixel Y-size
664   AdjustPixel(wymin, 1);
665   // Check if large pixel size
666   AdjustPixel(wxmin, wymin);
667
668   // Remove discarded pixels
669   for (Int_t i=0; i<nPix; i++) {
670     pixPtr = (AliMUONPixel*) fPixArray->UncheckedAt(i);
671     //pixPtr->Print();
672     if (pixPtr->Charge() < 1) { fPixArray->RemoveAt(i); delete pixPtr; }// discarded pixel
673   }
674   fPixArray->Compress();
675   nPix = fPixArray->GetEntriesFast();
676
677   if (nPix > npad) {
678     if (fDebug) cout << nPix << endl;
679     // Too many pixels - sort and remove pixels with the lowest signal
680     fPixArray->Sort();
681     for (Int_t i=npad; i<nPix; i++) {
682       pixPtr = (AliMUONPixel*) fPixArray->UncheckedAt(i);
683       //pixPtr->Print();
684       fPixArray->RemoveAt(i);
685       delete pixPtr;
686     }
687     nPix = npad;
688   } // if (nPix > npad)
689
690   // Set pixel charges to the same value (for MLEM)
691   for (Int_t i=0; i<nPix; i++) {
692     pixPtr = (AliMUONPixel*) fPixArray->UncheckedAt(i);
693     //pixPtr->SetCharge(10);
694     if (fDebug) cout << i+1 << " " << pixPtr->Coord(0) << " " << pixPtr->Coord(1) << " " << pixPtr->Size(0) << " " << pixPtr->Size(1) << endl;
695   }
696 }
697
698 //_____________________________________________________________________________
699 void AliMUONClusterFinderAZ::AdjustPixel(Float_t width, Int_t ixy)
700 {
701   // Check if some pixels have small size (adjust if necessary)
702
703   AliMUONPixel *pixPtr, *pixPtr1 = 0;
704   Int_t ixy1 = TMath::Even(ixy);
705   Int_t nPix = fPixArray->GetEntriesFast();
706
707   for (Int_t i=0; i<nPix; i++) {
708     pixPtr = (AliMUONPixel*) fPixArray->UncheckedAt(i);
709     if (pixPtr->Charge() < 1) continue; // discarded pixel
710     if (pixPtr->Size(ixy)-width < -1.e-4) {
711       // try to merge 
712       if (fDebug) cout << i << " Small X or Y: " << ixy << " " << pixPtr->Size(ixy) << " " << width << " " << pixPtr->Coord(0) << " " << pixPtr->Coord(1) << endl;
713       for (Int_t j=i+1; j<nPix; j++) {
714         pixPtr1 = (AliMUONPixel*) fPixArray->UncheckedAt(j);
715         if (pixPtr1->Charge() < 1) continue; // discarded pixel
716         if (TMath::Abs(pixPtr1->Size(ixy)-width) < 1.e-4) continue; // right size 
717         if (TMath::Abs(pixPtr1->Coord(ixy1)-pixPtr->Coord(ixy1)) > 1.e-4) continue; // different rows/columns
718         if (TMath::Abs(pixPtr1->Coord(ixy)-pixPtr->Coord(ixy)) < 2*width) {
719           // merge
720           //AZ-problem in slats for new segment. pixPtr->SetCoord(ixy, (pixPtr->Coord(ixy)+pixPtr1->Coord(ixy))/2);
721           Double_t tmp = pixPtr->Coord(ixy) + pixPtr1->Size(ixy) * 
722             TMath::Sign (1., pixPtr1->Coord(ixy) - pixPtr->Coord(ixy));
723           pixPtr->SetCoord(ixy, tmp);
724           pixPtr->SetSize(ixy, width);
725           pixPtr->SetCharge(TMath::Min (pixPtr->Charge(),pixPtr1->Charge()));
726           pixPtr1->SetCharge(0);
727           pixPtr1 = 0;
728           break;
729         }
730       } // for (Int_t j=i+1;
731       //if (!pixPtr1) { cout << " I am here!" << endl; pixPtr->SetSize(ixy, width); } // ???
732       //else if (pixPtr1->Charge() > 0.5 || i == nPix-1) {
733       if (pixPtr1 || i == nPix-1) {
734         // edge pixel - just increase its size
735         if (fDebug) cout << " Edge ..." << endl; 
736         for (Int_t j=0; j<fnPads[0]+fnPads[1]; j++) {
737           //if (fPadIJ[0][j] != ixy1) continue;
738           //???-check if (TMath::Abs(pixPtr->Coord(ixy1)-fXyq[ixy1][j]) > 1.e-4) continue;
739           if (pixPtr->Coord(ixy) < fXyq[ixy][j]) 
740             //pixPtr->Shift(ixy, -pixPtr->Size(ixy));
741             pixPtr->Shift(ixy, pixPtr->Size(ixy)-width);
742           //else pixPtr->Shift(ixy, pixPtr->Size(ixy));
743           else pixPtr->Shift(ixy, -pixPtr->Size(ixy)+width);
744           pixPtr->SetSize(ixy, width);
745           break;
746         }
747       }
748     } // if (pixPtr->Size(ixy)-width < -1.e-4)
749   } // for (Int_t i=0; i<nPix;
750   return;
751 }
752   
753 //_____________________________________________________________________________
754 void AliMUONClusterFinderAZ::AdjustPixel(Float_t wxmin, Float_t wymin)
755 {
756   // Check if some pixels have large size (adjust if necessary)
757
758   Int_t n1[2], n2[2], iOK = 1, nPix = fPixArray->GetEntriesFast();
759   AliMUONPixel *pixPtr, pix;
760   Double_t xy0[2] = {9999, 9999}, wxy[2], dist[2];
761
762   // Check if large pixel size
763   for (Int_t i = 0; i < nPix; i++) {
764     pixPtr = (AliMUONPixel*) fPixArray->UncheckedAt(i);
765     if (pixPtr->Charge() < 1) continue; // discarded pixel
766     if (pixPtr->Size(0) - wxmin < 1.e-4) {
767       if (xy0[0] > 9998) xy0[0] = pixPtr->Coord(0); // position of a "normal" pixel
768       if (pixPtr->Size(1) - wymin < 1.e-4) { 
769         if (xy0[1] > 9998) xy0[1] = pixPtr->Coord(1); // position of a "normal" pixel
770         continue;
771       } else iOK = 0; // large pixel
772     } else {
773       iOK = 0; // large pixel
774       if (xy0[1] > 9998 && pixPtr->Size(1) - wymin < 1.e-4) xy0[1] = pixPtr->Coord(1); // "normal" pixel
775     }      
776     if (xy0[0] < 9998 && xy0[1] < 9998) break;
777   }
778   if (iOK) return;
779
780   wxy[0] = wxmin;
781   wxy[1] = wymin;
782   //cout << xy0[0] << " " << xy0[1] << endl;
783   for (Int_t i = 0; i < nPix; i++) {
784     pixPtr = (AliMUONPixel*) fPixArray->UncheckedAt(i);
785     if (pixPtr->Charge() < 1) continue; // discarded pixel
786     n1[0] = n1[1] = 999;
787     n2[0] = n2[1] = 1;
788     for (Int_t j = 0; j < 2; j++) {
789       if (pixPtr->Size(j) - wxy[j] < 1.e-4) continue;
790       dist[j] = (pixPtr->Coord(j) - xy0[j]) / wxy[j] / 2; // normalized distance to "normal" pixel
791       n2[j] = TMath::Nint (pixPtr->Size(j) / wxy[j]);
792       n1[j] = n2[j] == 1 ? TMath::Nint(dist[j]) : (Int_t)dist[j];
793     }
794     if (n1[0] > 998 && n1[1] > 998) continue;
795     if (fDebug) cout << " Different " << pixPtr->Size(0) << " " << wxy[0] << " "
796                      << pixPtr->Size(1) << " " << wxy[1] <<endl;
797     
798     if (n2[0] > 2 || n2[1] > 2) { cout << n2[0] << " " << n2[1] << endl; AliFatal("Too large pixel."); }
799     //cout << n1[0] << " " << n2[0] << " " << n1[1] << " " << n2[1] << endl;
800     pix = *pixPtr;
801     pix.SetSize(0, wxy[0]); pix.SetSize(1, wxy[1]);
802     //pixPtr->Print();
803     for (Int_t ii = 0; ii < n2[0]; ii++) {
804       if (n1[0] < 999) pix.SetCoord(0, xy0[0] + (n1[0] + TMath::Sign(1.,dist[0]) * ii) * 2 * wxy[0]);
805       for (Int_t jj = 0; jj < n2[1]; jj++) {
806         if (n1[1] < 999) pix.SetCoord(1, xy0[1] + (n1[1] + TMath::Sign(1.,dist[1]) * jj) * 2 * wxy[1]);
807         fPixArray->Add(new AliMUONPixel(pix));
808         //pix.Print();
809       }
810     }
811     pixPtr->SetCharge(0);
812   } // for (Int_t i = 0; i < nPix;
813 }
814
815 //_____________________________________________________________________________
816 Bool_t AliMUONClusterFinderAZ::MainLoop(Int_t iSimple)
817 {
818   // Repeat MLEM algorithm until pixel size becomes sufficiently small
819   
820   TH2D *mlem;
821
822   Int_t ix, iy;
823   //Int_t nn, xList[10], yList[10];
824   Int_t nPix = fPixArray->GetEntriesFast();
825   AliMUONPixel *pixPtr = 0;
826   Double_t *coef = 0, *probi = 0; 
827   AddVirtualPad(); // add virtual pads if necessary
828   Int_t npadTot = fnPads[0] + fnPads[1], npadOK = 0;
829   for (Int_t i = 0; i < npadTot; i++) if (fPadIJ[1][i] == 0) npadOK++;
830   if (fDraw) fDraw->ResetMuon();
831
832   while (1) {
833
834     mlem = (TH2D*) gROOT->FindObject("mlem");
835     if (mlem) mlem->Delete();
836     // Calculate coefficients
837     if (fDebug) cout << " nPix, npadTot, npadOK " << nPix << " " << npadTot << " " << npadOK << endl;
838
839     // Calculate coefficients and pixel visibilities
840     coef = new Double_t [npadTot*nPix];
841     probi = new Double_t [nPix];
842     for (Int_t ipix=0; ipix<nPix; ipix++) probi[ipix] = 0;
843     Int_t indx = 0, indx1 = 0, cath = 0;
844
845     for (Int_t j=0; j<npadTot; j++) {
846       indx = j*nPix;
847       if (fPadIJ[1][j] == 0) {
848         cath = fPadIJ[0][j];
849         fSegmentation[cath]->GetPadI(fInput->DetElemId(),fXyq[0][j],fXyq[1][j],fZpad,ix,iy);
850         fSegmentation[cath]->SetPad(fInput->DetElemId(),ix,iy);
851         /*
852           fSegmentation[cath]->Neighbours(fInput->DetElemId(),ix,iy,&nn,xList,yList); 
853           if (nn != 4) {
854           cout << nn << ": ";
855           for (Int_t i=0; i<nn; i++) {cout << xList[i] << " " << yList[i] << ", ";}
856           cout << endl;
857           }
858         */
859       }
860
861       for (Int_t ipix=0; ipix<nPix; ipix++) {
862         indx1 = indx + ipix;
863         if (fPadIJ[1][j] < 0) { coef[indx1] = 0; continue; }
864         pixPtr = (AliMUONPixel*) fPixArray->UncheckedAt(ipix);
865         fSegmentation[cath]->SetHit(fInput->DetElemId(),pixPtr->Coord(0),pixPtr->Coord(1),fZpad);
866         coef[indx1] = fResponse->IntXY(fInput->DetElemId(),fSegmentation[cath]);
867         probi[ipix] += coef[indx1];
868       } // for (Int_t ipix=0;
869     } // for (Int_t j=0;
870     for (Int_t ipix=0; ipix<nPix; ipix++) if (probi[ipix] < 0.01) pixPtr->SetCharge(0); // "invisible" pixel
871
872     // MLEM algorithm
873     Mlem(coef, probi, 15);
874
875     Double_t xylim[4] = {999, 999, 999, 999};
876     for (Int_t ipix=0; ipix<nPix; ipix++) {
877       pixPtr = (AliMUONPixel*) fPixArray->UncheckedAt(ipix);
878       //cout << ipix+1; pixPtr->Print();
879       for (Int_t i=0; i<4; i++) 
880         xylim[i] = TMath::Min (xylim[i], (i%2 ? -1 : 1)*pixPtr->Coord(i/2));
881     }
882     for (Int_t i=0; i<4; i++) {
883       xylim[i] -= pixPtr->Size(i/2); if (fDebug) cout << (i%2 ? -1 : 1)*xylim[i] << " "; }
884     if (fDebug) cout << endl;
885
886     // Adjust histogram to approximately the same limits as for the pads
887     // (for good presentation)
888     if (fDraw) fDraw->AdjustHist(xylim, pixPtr);
889
890     Int_t nx = TMath::Nint ((-xylim[1]-xylim[0])/pixPtr->Size(0)/2);
891     Int_t ny = TMath::Nint ((-xylim[3]-xylim[2])/pixPtr->Size(1)/2);
892     
893     mlem = new TH2D("mlem","mlem",nx,xylim[0],-xylim[1],ny,xylim[2],-xylim[3]);
894     for (Int_t ipix=0; ipix<nPix; ipix++) {
895       pixPtr = (AliMUONPixel*) fPixArray->UncheckedAt(ipix);
896       mlem->Fill(pixPtr->Coord(0),pixPtr->Coord(1),pixPtr->Charge());
897     }
898     if (fDraw) fDraw->DrawHist("c2", mlem);
899
900     // Check if the total charge of pixels is too low
901     Double_t qTot = 0;
902     for (Int_t i=0; i<nPix; i++) {
903       pixPtr = (AliMUONPixel*) fPixArray->UncheckedAt(i);
904       qTot += pixPtr->Charge();
905     }
906     //AZ if (qTot < 1.e-4 || npadOK < 3 && qTot < 50) {
907     if (qTot < 1.e-4 || npadOK < 3 && qTot < 7) {
908       delete [] coef; delete [] probi; coef = 0; probi = 0;
909       fPixArray->Delete(); 
910       for (Int_t i=0; i<npadTot; i++) if (fPadIJ[1][i] == 0) fPadIJ[1][i] = -1;
911       return kFALSE; 
912     }
913
914     // Plot data - expectation
915     /*
916     Double_t x, y, cont;
917     for (Int_t j=0; j<npadTot; j++) {
918       Double_t sum1 = 0;
919       for (Int_t i=0; i<nPix; i++) {
920         // Caculate expectation
921         pixPtr = (AliMUONPixel*) fPixArray->UncheckedAt(i);
922         sum1 += pixPtr->Charge()*coef[j*nPix+i];
923       }
924       //AZsum1 = TMath::Min (sum1,(Double_t)fResponse->MaxAdc());
925       sum1 = TMath::Min (sum1,(Double_t)fResponse->Saturation());
926       x = fXyq[0][j];
927       y = fXyq[1][j];
928       cath = fPadIJ[0][j];
929       Int_t ihist = cath*2;
930       ix = fHist[ihist]->GetXaxis()->FindBin(x);
931       iy = fHist[ihist]->GetYaxis()->FindBin(y);
932       cont = fHist[ihist]->GetCellContent(ix,iy);
933       if (cont == 0 && fHist[ihist+1]) {
934         ihist += 1;
935         ix = fHist[ihist]->GetXaxis()->FindBin(x);
936         iy = fHist[ihist]->GetYaxis()->FindBin(y);
937       }
938       fHist[ihist]->SetBinContent(ix,iy,fXyq[2][j]-sum1);
939     }
940     ((TCanvas*)gROOT->FindObject("c1"))->cd(1);
941     //gPad->SetTheta(55);
942     //gPad->SetPhi(30);
943     //mlem->Draw("lego1");
944     gPad->Modified();
945     ((TCanvas*)gROOT->FindObject("c1"))->cd(2);
946     gPad->Modified();
947     */
948
949     if (iSimple) {
950       // Simple cluster - skip further passes thru EM-procedure
951       //fxyMu[0][6] = fxyMu[1][6] = 9999;
952       Simple();
953       delete [] coef; delete [] probi; coef = 0; probi = 0;
954       fPixArray->Delete(); 
955       return kTRUE;
956     }
957
958     // Calculate position of the center-of-gravity around the maximum pixel
959     Double_t xyCOG[2];
960     FindCOG(mlem, xyCOG);
961
962     if (TMath::Min(pixPtr->Size(0),pixPtr->Size(1)) < 0.07 && pixPtr->Size(0) > pixPtr->Size(1)) break;
963     //if (TMath::Min(pixPtr->Size(0),pixPtr->Size(1)) < 0.007 && pixPtr->Size(0) > pixPtr->Size(1)) break;
964     //if (TMath::Min(pixPtr->Size(0),pixPtr->Size(1)) >= 0.07 || pixPtr->Size(0) < pixPtr->Size(1)) {
965     // Sort pixels according to the charge
966     fPixArray->Sort();
967     /*
968     for (Int_t i=0; i<nPix; i++) {
969       pixPtr = (AliMUONPixel*) fPixArray->UncheckedAt(i);
970       cout << i+1; pixPtr->Print();
971     }
972     */
973     Double_t pixMin = 0.01*((AliMUONPixel*)fPixArray->UncheckedAt(0))->Charge();
974     pixMin = TMath::Min (pixMin,50.);
975
976     // Decrease pixel size and shift pixels to make them centered at 
977     // the maximum one
978     indx = (pixPtr->Size(0)>pixPtr->Size(1)) ? 0 : 1;
979     Double_t width = 0, shift[2]={0};
980     ix = 1;
981     for (Int_t i=0; i<4; i++) xylim[i] = 999;
982     Int_t nPix1 = nPix; nPix = 0;
983     for (Int_t ipix=0; ipix<nPix1; ipix++) {
984       pixPtr = (AliMUONPixel*) fPixArray->UncheckedAt(ipix);
985       if (nPix >= npadOK) { // too many pixels already
986         fPixArray->RemoveAt(ipix); 
987         delete pixPtr; 
988         continue;
989       }
990       if (pixPtr->Charge() < pixMin) { // low charge
991         fPixArray->RemoveAt(ipix); 
992         delete pixPtr; 
993         continue;
994       }
995       for (Int_t i=0; i<2; i++) {
996         if (!i) {
997           pixPtr->SetCharge(10);
998           pixPtr->SetSize(indx, pixPtr->Size(indx)/2);
999           width = -pixPtr->Size(indx);
1000           pixPtr->Shift(indx, width);
1001           // Shift pixel position
1002           if (ix) {
1003             ix = 0;
1004             for (Int_t j=0; j<2; j++) {
1005               shift[j] = pixPtr->Coord(j) - xyCOG[j];
1006               shift[j] -= ((Int_t)(shift[j]/pixPtr->Size(j)/2))*pixPtr->Size(j)*2;
1007             }
1008             //cout << ipix << " " << i << " " << shift[0] << " " << shift[1] << endl;
1009           } // if (ix)
1010           pixPtr->Shift(0, -shift[0]);
1011           pixPtr->Shift(1, -shift[1]);
1012         } else {
1013           pixPtr = new AliMUONPixel(*pixPtr);
1014           pixPtr->Shift(indx, -2*width);
1015           fPixArray->Add((TObject*)pixPtr);
1016         } // else
1017         //pixPtr->Print();
1018         for (Int_t i=0; i<4; i++) 
1019           xylim[i] = TMath::Min (xylim[i], (i%2 ? -1 : 1)*pixPtr->Coord(i/2));
1020       } // for (Int_t i=0; i<2;
1021       nPix += 2;
1022     } // for (Int_t ipix=0;
1023
1024     fPixArray->Compress();
1025     nPix = fPixArray->GetEntriesFast();
1026
1027     // Remove excessive pixels
1028     if (nPix > npadOK) {
1029       for (Int_t ipix=npadOK; ipix<nPix; ipix++) { 
1030         pixPtr = (AliMUONPixel*) fPixArray->UncheckedAt(ipix);
1031         fPixArray->RemoveAt(ipix); 
1032         delete pixPtr;
1033       }
1034     } else {
1035       pixPtr = (AliMUONPixel*) fPixArray->UncheckedAt(0);
1036       // add pixels if the maximum is at the limit of pixel area
1037       // start from Y-direction
1038       Int_t j = 0;
1039       for (Int_t i=3; i>-1; i--) {
1040         if (nPix < npadOK && 
1041             TMath::Abs((i%2 ? -1 : 1)*xylim[i]-xyCOG[i/2]) < pixPtr->Size(i/2)) {
1042           pixPtr = new AliMUONPixel(*pixPtr);
1043           pixPtr->SetCoord(i/2, xyCOG[i/2]+(i%2 ? 2:-2)*pixPtr->Size(i/2));
1044           j = TMath::Even (i/2);
1045           pixPtr->SetCoord(j, xyCOG[j]);
1046           fPixArray->Add((TObject*)pixPtr);
1047           nPix++;
1048         }
1049       }
1050     } // else    
1051
1052     fPixArray->Compress();
1053     nPix = fPixArray->GetEntriesFast();
1054     delete [] coef; delete [] probi; coef = 0; probi = 0;
1055   } // while (1)
1056
1057   // remove pixels with low signal or low visibility
1058   // Cuts are empirical !!!
1059   Double_t thresh = TMath::Max (mlem->GetMaximum()/100.,1.);
1060   thresh = TMath::Min (thresh,50.);
1061   Double_t cmax = -1, charge = 0;
1062   for (Int_t i=0; i<nPix; i++) cmax = TMath::Max (cmax,probi[i]); 
1063   //cout << thresh << " " << cmax << " " << cmax*0.9 << endl;
1064   // Mark pixels which should be removed
1065   for (Int_t i=0; i<nPix; i++) {
1066     pixPtr = (AliMUONPixel*) fPixArray->UncheckedAt(i);
1067     charge = pixPtr->Charge();
1068     if (charge < thresh) pixPtr->SetCharge(-charge);
1069     //else if (cmax > 1.91) {
1070     //  if (probi[i] < 1.9) pixPtr->SetCharge(-charge);
1071     //}
1072     //AZ else if (probi[i] < cmax*0.9) pixPtr->SetCharge(-charge);
1073     else if (probi[i] < cmax*0.8) pixPtr->SetCharge(-charge);
1074     //cout << i << " " << pixPtr->Coord(0) << " " << pixPtr->Coord(1) << " " << charge << " " << probi[i] << endl;
1075   }
1076   // Move charge of removed pixels to their nearest neighbour (to keep total charge the same)
1077   Int_t near = 0;
1078   for (Int_t i=0; i<nPix; i++) {
1079     pixPtr = (AliMUONPixel*) fPixArray->UncheckedAt(i);
1080     charge = pixPtr->Charge();
1081     if (charge > 0) continue;
1082     near = FindNearest(pixPtr);
1083     pixPtr->SetCharge(0);
1084     probi[i] = 0; // make it "invisible"
1085     pixPtr = (AliMUONPixel*) fPixArray->UncheckedAt(near);
1086     pixPtr->SetCharge(pixPtr->Charge() + (-charge));
1087   }
1088   Mlem(coef,probi,2);
1089   // Update histogram
1090   for (Int_t i=0; i<nPix; i++) {
1091     pixPtr = (AliMUONPixel*) fPixArray->UncheckedAt(i);
1092     ix = mlem->GetXaxis()->FindBin(pixPtr->Coord(0));
1093     iy = mlem->GetYaxis()->FindBin(pixPtr->Coord(1));
1094     mlem->SetBinContent(ix, iy, pixPtr->Charge());
1095   }
1096   if (fDraw) fDraw->DrawHist("c2", mlem);
1097
1098   //fxyMu[0][6] = fxyMu[1][6] = 9999;
1099   // Try to split into clusters
1100   Bool_t ok = kTRUE;
1101   if (mlem->GetSum() < 1) ok = kFALSE;
1102   else Split(mlem, coef);
1103   delete [] coef; delete [] probi; coef = 0; probi = 0;
1104   fPixArray->Delete(); 
1105   return ok;
1106 }
1107
1108 //_____________________________________________________________________________
1109 void AliMUONClusterFinderAZ::Mlem(Double_t *coef, Double_t *probi, Int_t nIter)
1110 {
1111   // Use MLEM to find pixel charges
1112   
1113   Int_t nPix = fPixArray->GetEntriesFast();
1114   Int_t npad = fnPads[0] + fnPads[1];
1115   Double_t *probi1 = new Double_t [nPix];
1116   Double_t probMax = 0;
1117   Int_t indx, indx1;
1118   AliMUONPixel *pixPtr;
1119
1120   for (Int_t ipix=0; ipix<nPix; ipix++) if (probi[ipix] > probMax) probMax = probi[ipix];
1121   for (Int_t iter=0; iter<nIter; iter++) {
1122     // Do iterations
1123     for (Int_t ipix=0; ipix<nPix; ipix++) {
1124       // Correct each pixel
1125       if (probi[ipix] < 0.01) continue; // skip "invisible" pixel
1126       Double_t sum = 0;
1127       //probi1[ipix] = probi[ipix];
1128       probi1[ipix] = probMax;
1129       for (Int_t j=0; j<npad; j++) {
1130         if (fPadIJ[1][j] < 0) continue; 
1131         Double_t sum1 = 0;
1132         indx1 = j*nPix;
1133         indx = indx1 + ipix;
1134         for (Int_t i=0; i<nPix; i++) {
1135           // Caculate expectation
1136           pixPtr = (AliMUONPixel*) fPixArray->UncheckedAt(i);
1137           sum1 += pixPtr->Charge()*coef[indx1+i];
1138         } // for (Int_t i=0;
1139         //AZ if (fXyq[2][j] > fResponse->MaxAdc()-1 && sum1 > fResponse->MaxAdc()) { probi1[ipix] -= coef[indx]; continue; } // correct for pad charge overflows
1140         if (fXyq[2][j] > fResponse->Saturation()-1 && sum1 > fResponse->Saturation()) { probi1[ipix] -= coef[indx]; continue; } // correct for pad charge overflows
1141         //cout << sum1 << " " << fXyq[2][j] << " " << coef[j*nPix+ipix] << endl;
1142         if (coef[indx] > 1.e-6) sum += fXyq[2][j]*coef[indx]/sum1;
1143       } // for (Int_t j=0;
1144       pixPtr = (AliMUONPixel*) fPixArray->UncheckedAt(ipix);
1145       if (probi1[ipix] > 1.e-6) pixPtr->SetCharge(pixPtr->Charge()*sum/probi1[ipix]);
1146     } // for (Int_t ipix=0;
1147   } // for (Int_t iter=0;
1148   delete [] probi1;
1149   return;
1150 }
1151
1152 //_____________________________________________________________________________
1153 void AliMUONClusterFinderAZ::FindCOG(TH2D *mlem, Double_t *xyc)
1154 {
1155   // Calculate position of the center-of-gravity around the maximum pixel
1156
1157   Int_t ixmax, iymax, ix, nsumx=0, nsumy=0, nsum=0;
1158   Int_t i1 = -9, j1 = -9;
1159   mlem->GetMaximumBin(ixmax,iymax,ix);
1160   Int_t nx = mlem->GetNbinsX();
1161   Int_t ny = mlem->GetNbinsY();
1162   Double_t thresh = mlem->GetMaximum()/10;
1163   Double_t x, y, cont, xq=0, yq=0, qq=0;
1164
1165   for (Int_t i=TMath::Max(1,iymax-1); i<=TMath::Min(ny,iymax+1); i++) {
1166   //for (Int_t i=TMath::Max(1,iymax-9); i<=TMath::Min(ny,iymax+9); i++) {
1167     y = mlem->GetYaxis()->GetBinCenter(i);
1168     for (Int_t j=TMath::Max(1,ixmax-1); j<=TMath::Min(nx,ixmax+1); j++) {
1169     //for (Int_t j=TMath::Max(1,ixmax-9); j<=TMath::Min(nx,ixmax+9); j++) {
1170       cont = mlem->GetCellContent(j,i);
1171       if (cont < thresh) continue;
1172       if (i != i1) {i1 = i; nsumy++;}
1173       if (j != j1) {j1 = j; nsumx++;}
1174       x = mlem->GetXaxis()->GetBinCenter(j);
1175       xq += x*cont;
1176       yq += y*cont;
1177       qq += cont;
1178       nsum++;
1179     }
1180   }
1181
1182   Double_t cmax = 0;
1183   Int_t i2 = 0, j2 = 0;
1184   x = y = 0;
1185   if (nsumy == 1) {
1186     // one bin in Y - add one more (with the largest signal)
1187     for (Int_t i=TMath::Max(1,iymax-1); i<=TMath::Min(ny,iymax+1); i++) {
1188       if (i == iymax) continue;
1189       for (Int_t j=TMath::Max(1,ixmax-1); j<=TMath::Min(nx,ixmax+1); j++) {
1190         cont = mlem->GetCellContent(j,i);
1191         if (cont > cmax) {
1192           cmax = cont;
1193           x = mlem->GetXaxis()->GetBinCenter(j);
1194           y = mlem->GetYaxis()->GetBinCenter(i);
1195           i2 = i;
1196           j2 = j;
1197         }
1198       }
1199     }
1200     xq += x*cmax;
1201     yq += y*cmax;
1202     qq += cmax;
1203     if (i2 != i1) nsumy++;
1204     if (j2 != j1) nsumx++;
1205     nsum++;
1206   } // if (nsumy == 1)
1207
1208   if (nsumx == 1) {
1209     // one bin in X - add one more (with the largest signal)
1210     cmax = x = y = 0;
1211     for (Int_t j=TMath::Max(1,ixmax-1); j<=TMath::Min(nx,ixmax+1); j++) {
1212       if (j == ixmax) continue;
1213       for (Int_t i=TMath::Max(1,iymax-1); i<=TMath::Min(ny,iymax+1); i++) {
1214         cont = mlem->GetCellContent(j,i);
1215         if (cont > cmax) {
1216           cmax = cont;
1217           x = mlem->GetXaxis()->GetBinCenter(j);
1218           y = mlem->GetYaxis()->GetBinCenter(i);
1219           i2 = i;
1220           j2 = j;
1221         }
1222       }
1223     }
1224     xq += x*cmax;
1225     yq += y*cmax;
1226     qq += cmax;
1227     if (i2 != i1) nsumy++;
1228     if (j2 != j1) nsumx++;
1229     nsum++;
1230   } // if (nsumx == 1)
1231
1232   xyc[0] = xq/qq; xyc[1] = yq/qq;
1233   if (fDebug) cout << xyc[0] << " " << xyc[1] << " " << qq << " " << nsum << " " << nsumx << " " << nsumy << endl;
1234   return;
1235 }
1236
1237 //_____________________________________________________________________________
1238 Int_t AliMUONClusterFinderAZ::FindNearest(AliMUONPixel *pixPtr0)
1239 {
1240   // Find the pixel nearest to the given one
1241   // (algorithm may be not very efficient)
1242
1243   Int_t nPix = fPixArray->GetEntriesFast(), imin = 0;
1244   Double_t rmin = 99999, dx = 0, dy = 0, r = 0;
1245   Double_t xc = pixPtr0->Coord(0), yc = pixPtr0->Coord(1);
1246   AliMUONPixel *pixPtr;
1247
1248   for (Int_t i=0; i<nPix; i++) {
1249     pixPtr = (AliMUONPixel*) fPixArray->UncheckedAt(i);
1250     if (pixPtr->Charge() < 0.5) continue;
1251     dx = (xc - pixPtr->Coord(0)) / pixPtr->Size(0);
1252     dy = (yc - pixPtr->Coord(1)) / pixPtr->Size(1);
1253     r = dx *dx + dy * dy;
1254     if (r < rmin) { rmin = r; imin = i; }
1255   }
1256   return imin;
1257 }
1258
1259 //_____________________________________________________________________________
1260 void AliMUONClusterFinderAZ::Split(TH2D *mlem, Double_t *coef)
1261 {
1262   // The main steering function to work with clusters of pixels in anode
1263   // plane (find clusters, decouple them from each other, merge them (if
1264   // necessary), pick up coupled pads, call the fitting function)
1265   
1266   Int_t nx = mlem->GetNbinsX();
1267   Int_t ny = mlem->GetNbinsY();
1268   Int_t nPix = fPixArray->GetEntriesFast();
1269
1270   Bool_t *used = new Bool_t[ny*nx];
1271   Double_t cont;
1272   Int_t nclust = 0, indx, indx1;
1273
1274   for (Int_t i=0; i<ny*nx; i++) used[i] = kFALSE; 
1275
1276   TObjArray *clusters[200]={0};
1277   TObjArray *pix;
1278
1279   // Find clusters of histogram bins (easier to work in 2-D space)
1280   for (Int_t i=1; i<=ny; i++) {
1281     for (Int_t j=1; j<=nx; j++) {
1282       indx = (i-1)*nx + j - 1;
1283       if (used[indx]) continue;
1284       cont = mlem->GetCellContent(j,i);
1285       if (cont < 0.5) continue;
1286       pix = new TObjArray(20);
1287       used[indx] = 1;
1288       pix->Add(BinToPix(mlem,j,i));
1289       AddBin(mlem, i, j, 0, used, pix); // recursive call
1290       if (nclust >= 200) AliFatal(" Too many clusters !!!");
1291       clusters[nclust++] = pix;
1292     } // for (Int_t j=1; j<=nx; j++) {
1293   } // for (Int_t i=1; i<=ny;
1294   if (fDebug) cout << nclust << endl;
1295   delete [] used; used = 0;
1296   
1297   // Compute couplings between clusters and clusters to pads
1298   Int_t npad = fnPads[0] + fnPads[1];
1299
1300   // Write out some information for algorithm development
1301   Int_t cath=0, npadx[2]={0}, npady[2]={0};
1302   Double_t xlow[2]={9999,9999}, xhig[2]={-9999,-9999};
1303   Double_t ylow[2]={9999,9999}, yhig[2]={-9999,-9999};
1304   for (Int_t j=0; j<npad; j++) {
1305     if (fXyq[3][j] < 0) continue; // exclude virtual pads
1306     cath = fPadIJ[0][j];
1307     if (fXyq[0][j] < xlow[cath]-0.001) { 
1308       if (fXyq[0][j]+fXyq[3][j] <= xlow[cath] && npadx[cath]) npadx[cath]++;
1309       xlow[cath] = fXyq[0][j];
1310     }
1311     if (fXyq[0][j] > xhig[cath]+0.001) { 
1312       if (fXyq[0][j]-fXyq[3][j] >= xhig[cath]) npadx[cath]++; 
1313       xhig[cath] = fXyq[0][j]; 
1314     }
1315     if (fXyq[1][j] < ylow[cath]-0.001) { 
1316       if (fXyq[1][j]+fXyq[4][j] <= ylow[cath] && npady[cath]) npady[cath]++;
1317       ylow[cath] = fXyq[1][j];
1318     }
1319     if (fXyq[1][j] > yhig[cath]+0.001) { 
1320       if (fXyq[1][j]-fXyq[4][j] >= yhig[cath]) npady[cath]++;
1321       yhig[cath] = fXyq[1][j]; 
1322     }
1323   }
1324   //if (lun1) fprintf(lun1," %4d %2d %3d %3d %3d %3d \n",gAlice->GetHeader()->GetEvent(),AliMUONClusterInput::Instance()->Chamber(), npadx[0], npadx[1], npady[0], npady[1]);
1325
1326   // Exclude pads with overflows
1327   for (Int_t j=0; j<npad; j++) {
1328     //AZ if (fXyq[2][j] > fResponse->MaxAdc()-1) fPadIJ[1][j] = -5;
1329     if (fXyq[2][j] > fResponse->Saturation()-1) fPadIJ[1][j] = -5;
1330     else fPadIJ[1][j] = 0;
1331   }
1332
1333   // Compute couplings of clusters to pads
1334   TMatrixD *aijclupad = new TMatrixD(nclust,npad);
1335   *aijclupad = 0;
1336   Int_t npxclu;
1337   for (Int_t iclust=0; iclust<nclust; iclust++) {
1338     pix = clusters[iclust];
1339     npxclu = pix->GetEntriesFast();
1340     for (Int_t i=0; i<npxclu; i++) {
1341       indx = fPixArray->IndexOf(pix->UncheckedAt(i));
1342       for (Int_t j=0; j<npad; j++) {
1343         if (fPadIJ[1][j] < 0 && fPadIJ[1][j] != -5) continue;
1344         if (coef[j*nPix+indx] < fgkCouplMin) continue;
1345         (*aijclupad)(iclust,j) += coef[j*nPix+indx];
1346       }
1347     }
1348   }
1349   // Compute couplings between clusters
1350   TMatrixD *aijcluclu = new TMatrixD(nclust,nclust);
1351   *aijcluclu = 0;
1352   for (Int_t iclust=0; iclust<nclust; iclust++) {
1353     for (Int_t j=0; j<npad; j++) {
1354       // Exclude overflows
1355       if (fPadIJ[1][j] < 0) continue;
1356       if ((*aijclupad)(iclust,j) < fgkCouplMin) continue;
1357       for (Int_t iclust1=iclust+1; iclust1<nclust; iclust1++) {
1358         if ((*aijclupad)(iclust1,j) < fgkCouplMin) continue;
1359         (*aijcluclu)(iclust,iclust1) += 
1360           TMath::Sqrt ((*aijclupad)(iclust,j)*(*aijclupad)(iclust1,j));
1361       }
1362     }
1363   }
1364   for (Int_t iclust=0; iclust<nclust; iclust++) {
1365     for (Int_t iclust1=iclust+1; iclust1<nclust; iclust1++) {
1366       (*aijcluclu)(iclust1,iclust) = (*aijcluclu)(iclust,iclust1);
1367     }
1368   }
1369
1370   if (fDebug && nclust > 1) aijcluclu->Print();
1371
1372   // Find groups of coupled clusters
1373   used = new Bool_t[nclust];
1374   for (Int_t i=0; i<nclust; i++) used[i] = kFALSE;
1375   Int_t *clustNumb = new Int_t[nclust];
1376   Int_t nCoupled, nForFit, minGroup[3], clustFit[3], nfit = 0;
1377   Double_t parOk[8];
1378
1379   for (Int_t igroup=0; igroup<nclust; igroup++) {
1380     if (used[igroup]) continue;
1381     used[igroup] = kTRUE;
1382     clustNumb[0] = igroup;
1383     nCoupled = 1;
1384     // Find group of coupled clusters
1385     AddCluster(igroup, nclust, aijcluclu, used, clustNumb, nCoupled); // recursive
1386     if (fDebug) {
1387       cout << " nCoupled: " << nCoupled << endl;
1388       for (Int_t i=0; i<nCoupled; i++) cout << clustNumb[i] << " "; cout << endl; 
1389     }
1390     fnCoupled = nCoupled;
1391
1392     while (nCoupled > 0) {
1393
1394       if (nCoupled < 4) {
1395         nForFit = nCoupled;
1396         for (Int_t i=0; i<nCoupled; i++) clustFit[i] = clustNumb[i];
1397       } else {
1398         // Too many coupled clusters to fit - try to decouple them
1399         // Find the lowest coupling of 1, 2, min(3,nLinks/2) pixels with 
1400         // all the others in the group 
1401         for (Int_t j=0; j<3; j++) minGroup[j] = -1;
1402         Double_t coupl = MinGroupCoupl(nCoupled, clustNumb, aijcluclu, minGroup);
1403
1404         // Flag clusters for fit
1405         nForFit = 0;
1406         while (minGroup[nForFit] >= 0 && nForFit < 3) {
1407           if (fDebug) cout << clustNumb[minGroup[nForFit]] << " ";
1408           clustFit[nForFit] = clustNumb[minGroup[nForFit]];
1409           clustNumb[minGroup[nForFit]] -= 999;
1410           nForFit++;
1411         }
1412         if (fDebug) cout << nForFit << " " << coupl << endl;
1413       } // else
1414
1415       // Select pads for fit. 
1416       if (SelectPad(nCoupled, nForFit, clustNumb, clustFit, aijclupad) < 3 && nCoupled > 1) {
1417         // Deselect pads
1418         for (Int_t j=0; j<npad; j++) {
1419           if (TMath::Abs(fPadIJ[1][j]) == 1) fPadIJ[1][j] = 0;
1420           if (TMath::Abs(fPadIJ[1][j]) == -9) fPadIJ[1][j] = -5;
1421         }
1422         // Merge the failed cluster candidates (with too few pads to fit) with 
1423         // the one with the strongest coupling
1424         Merge(nForFit, nCoupled, clustNumb, clustFit, clusters, aijcluclu, aijclupad);
1425       } else {
1426         // Do the fit
1427         nfit = Fit(nForFit, clustFit, clusters, parOk);
1428       }
1429
1430       // Subtract the fitted charges from pads with strong coupling and/or
1431       // return pads for further use
1432       UpdatePads(nfit, parOk);
1433
1434       // Mark used pads
1435       for (Int_t j=0; j<npad; j++) {
1436         if (fPadIJ[1][j] == 1) fPadIJ[1][j] = -1;
1437         if (fPadIJ[1][j] == -9) fPadIJ[1][j] = -5;
1438       }
1439
1440       // Sort the clusters (move to the right the used ones)
1441       Int_t beg = 0, end = nCoupled - 1;
1442       while (beg < end) {
1443         if (clustNumb[beg] >= 0) { beg++; continue; }
1444         for (Int_t j=end; j>beg; j--) {
1445           if (clustNumb[j] < 0) continue;
1446           end = j - 1;
1447           indx = clustNumb[beg];
1448           clustNumb[beg] = clustNumb[j];
1449           clustNumb[j] = indx;
1450           break;
1451         }
1452         beg++;
1453       }
1454
1455       nCoupled -= nForFit;
1456       if (nCoupled > 3) {
1457         // Remove couplings of used clusters
1458         for (Int_t iclust=nCoupled; iclust<nCoupled+nForFit; iclust++) {
1459           indx = clustNumb[iclust] + 999;
1460           for (Int_t iclust1=0; iclust1<nCoupled; iclust1++) {
1461             indx1 = clustNumb[iclust1];
1462             (*aijcluclu)(indx,indx1) = (*aijcluclu)(indx1,indx) = 0;
1463           }
1464         }
1465
1466         // Update the remaining clusters couplings (exclude couplings from 
1467         // the used pads)
1468         for (Int_t j=0; j<npad; j++) {
1469           if (fPadIJ[1][j] != -1) continue;
1470           for (Int_t iclust=0; iclust<nCoupled; iclust++) {
1471             indx = clustNumb[iclust];
1472             if ((*aijclupad)(indx,j) < fgkCouplMin) continue;
1473             for (Int_t iclust1=iclust+1; iclust1<nCoupled; iclust1++) {
1474               indx1 = clustNumb[iclust1];
1475               if ((*aijclupad)(indx1,j) < fgkCouplMin) continue;
1476               // Check this
1477               (*aijcluclu)(indx,indx1) -= 
1478                 TMath::Sqrt ((*aijclupad)(indx,j)*(*aijclupad)(indx1,j));
1479               (*aijcluclu)(indx1,indx) = (*aijcluclu)(indx,indx1);
1480             }
1481           }
1482           fPadIJ[1][j] = -8;
1483         } // for (Int_t j=0; j<npad;
1484       } // if (nCoupled > 3)
1485     } // while (nCoupled > 0)
1486   } // for (Int_t igroup=0; igroup<nclust;
1487
1488   //delete aij_clu; aij_clu = 0; delete aijclupad; aijclupad = 0;
1489   aijcluclu->Delete(); aijclupad->Delete();
1490   for (Int_t iclust=0; iclust<nclust; iclust++) {
1491     pix = clusters[iclust]; 
1492     pix->Clear();
1493     delete pix; pix = 0;
1494   }
1495   delete [] clustNumb; clustNumb = 0; delete [] used; used = 0;
1496 }
1497
1498 //_____________________________________________________________________________
1499 void AliMUONClusterFinderAZ::AddBin(TH2D *mlem, Int_t ic, Int_t jc, Int_t mode, Bool_t *used, TObjArray *pix)
1500 {
1501   // Add a bin to the cluster
1502
1503   Int_t nx = mlem->GetNbinsX();
1504   Int_t ny = mlem->GetNbinsY();
1505   Double_t cont1, cont = mlem->GetCellContent(jc,ic);
1506   AliMUONPixel *pixPtr = 0;
1507
1508   for (Int_t i=TMath::Max(ic-1,1); i<=TMath::Min(ic+1,ny); i++) {
1509     for (Int_t j=TMath::Max(jc-1,1); j<=TMath::Min(jc+1,nx); j++) {
1510       if (i != ic && j != jc) continue;
1511       if (used[(i-1)*nx+j-1]) continue;
1512       cont1 = mlem->GetCellContent(j,i);
1513       if (mode && cont1 > cont) continue;
1514       used[(i-1)*nx+j-1] = kTRUE;
1515       if (cont1 < 0.5) continue;
1516       if (pix) pix->Add(BinToPix(mlem,j,i)); 
1517       else {
1518         pixPtr = new AliMUONPixel (mlem->GetXaxis()->GetBinCenter(j), 
1519                                    mlem->GetYaxis()->GetBinCenter(i), 0, 0, cont1);
1520         fPixArray->Add((TObject*)pixPtr);
1521       }
1522       AddBin(mlem, i, j, mode, used, pix); // recursive call
1523     }
1524   }
1525 }
1526
1527 //_____________________________________________________________________________
1528 TObject* AliMUONClusterFinderAZ::BinToPix(TH2D *mlem, Int_t jc, Int_t ic)
1529 {
1530   // Translate histogram bin to pixel 
1531   
1532   Double_t yc = mlem->GetYaxis()->GetBinCenter(ic);
1533   Double_t xc = mlem->GetXaxis()->GetBinCenter(jc);
1534   
1535   Int_t nPix = fPixArray->GetEntriesFast();
1536   AliMUONPixel *pixPtr;
1537
1538   // Compare pixel and bin positions
1539   for (Int_t i=0; i<nPix; i++) {
1540     pixPtr = (AliMUONPixel*) fPixArray->UncheckedAt(i);
1541     if (pixPtr->Charge() < 0.5) continue;
1542     if (TMath::Abs(pixPtr->Coord(0)-xc)<1.e-4 && TMath::Abs(pixPtr->Coord(1)-yc)<1.e-4) return (TObject*) pixPtr;
1543   }
1544   AliWarning(Form(" Something wrong ??? %f %f ", xc, yc));
1545   return NULL;
1546 }
1547
1548 //_____________________________________________________________________________
1549 void AliMUONClusterFinderAZ::AddCluster(Int_t ic, Int_t nclust, TMatrixD *aijcluclu, Bool_t *used, Int_t *clustNumb, Int_t &nCoupled)
1550 {
1551   // Add a cluster to the group of coupled clusters
1552
1553   for (Int_t i=0; i<nclust; i++) {
1554     if (used[i]) continue;
1555     if ((*aijcluclu)(i,ic) < fgkCouplMin) continue;
1556     used[i] = kTRUE;
1557     clustNumb[nCoupled++] = i;
1558     AddCluster(i, nclust, aijcluclu, used, clustNumb, nCoupled);
1559   }
1560 }
1561
1562 //_____________________________________________________________________________
1563 Double_t AliMUONClusterFinderAZ::MinGroupCoupl(Int_t nCoupled, Int_t *clustNumb, TMatrixD *aijcluclu, Int_t *minGroup)
1564 {
1565   // Find group of clusters with minimum coupling to all the others
1566
1567   Int_t i123max = TMath::Min(3,nCoupled/2); 
1568   Int_t indx, indx1, indx2, indx3, nTot = 0;
1569   Double_t *coupl1 = 0, *coupl2 = 0, *coupl3 = 0;
1570
1571   for (Int_t i123=1; i123<=i123max; i123++) {
1572
1573     if (i123 == 1) {
1574       coupl1 = new Double_t [nCoupled];
1575       for (Int_t i=0; i<nCoupled; i++) coupl1[i] = 0;
1576     }
1577     else if (i123 == 2) {
1578       nTot = nCoupled*nCoupled;
1579       coupl2 = new Double_t [nTot];
1580       for (Int_t i=0; i<nTot; i++) coupl2[i] = 9999;
1581     } else {
1582       nTot = nTot*nCoupled;
1583       coupl3 = new Double_t [nTot];
1584       for (Int_t i=0; i<nTot; i++) coupl3[i] = 9999;
1585     } // else
1586
1587     for (Int_t i=0; i<nCoupled; i++) {
1588       indx1 = clustNumb[i];
1589       for (Int_t j=i+1; j<nCoupled; j++) {
1590         indx2 = clustNumb[j];
1591         if (i123 == 1) {
1592           coupl1[i] += (*aijcluclu)(indx1,indx2);
1593           coupl1[j] += (*aijcluclu)(indx1,indx2);
1594         } 
1595         else if (i123 == 2) {
1596           indx = i*nCoupled + j;
1597           coupl2[indx] = coupl1[i] + coupl1[j];
1598           coupl2[indx] -= 2 * ((*aijcluclu)(indx1,indx2));
1599         } else {
1600           for (Int_t k=j+1; k<nCoupled; k++) {
1601             indx3 = clustNumb[k];
1602             indx = i*nCoupled*nCoupled + j*nCoupled + k;
1603             coupl3[indx] = coupl2[i*nCoupled+j] + coupl1[k];
1604             coupl3[indx] -= 2 * ((*aijcluclu)(indx1,indx3)+(*aijcluclu)(indx2,indx3));
1605           }
1606         } // else
1607       } // for (Int_t j=i+1;
1608     } // for (Int_t i=0;
1609   } // for (Int_t i123=1;
1610
1611   // Find minimum coupling
1612   Double_t couplMin = 9999;
1613   Int_t locMin = 0;
1614
1615   for (Int_t i123=1; i123<=i123max; i123++) {
1616     if (i123 == 1) {
1617       locMin = TMath::LocMin(nCoupled, coupl1);
1618       couplMin = coupl1[locMin];
1619       minGroup[0] = locMin;
1620       delete [] coupl1; coupl1 = 0;
1621     } 
1622     else if (i123 == 2) {
1623       locMin = TMath::LocMin(nCoupled*nCoupled, coupl2);
1624       if (coupl2[locMin] < couplMin) {
1625         couplMin = coupl2[locMin];
1626         minGroup[0] = locMin/nCoupled;
1627         minGroup[1] = locMin%nCoupled;
1628       }
1629       delete [] coupl2; coupl2 = 0;
1630     } else {
1631       locMin = TMath::LocMin(nTot, coupl3);
1632       if (coupl3[locMin] < couplMin) {
1633         couplMin = coupl3[locMin];
1634         minGroup[0] = locMin/nCoupled/nCoupled;
1635         minGroup[1] = locMin%(nCoupled*nCoupled)/nCoupled;
1636         minGroup[2] = locMin%nCoupled;
1637       }
1638       delete [] coupl3; coupl3 = 0;
1639     } // else
1640   } // for (Int_t i123=1;
1641   return couplMin;
1642 }
1643
1644 //_____________________________________________________________________________
1645 Int_t AliMUONClusterFinderAZ::SelectPad(Int_t nCoupled, Int_t nForFit, Int_t *clustNumb, Int_t *clustFit, TMatrixD *aijclupad)
1646 {
1647   // Select pads for fit. If too many coupled clusters, find pads giving 
1648   // the strongest coupling with the rest of clusters and exclude them from the fit.
1649
1650   Int_t npad = fnPads[0] + fnPads[1];
1651   Double_t *padpix = 0;
1652
1653   if (nCoupled > 3) {
1654     padpix = new Double_t[npad];
1655     for (Int_t i=0; i<npad; i++) padpix[i] = 0; 
1656   }
1657
1658   Int_t nOK = 0, indx, indx1;
1659   for (Int_t iclust=0; iclust<nForFit; iclust++) {
1660     indx = clustFit[iclust];
1661     for (Int_t j=0; j<npad; j++) {
1662       if ((*aijclupad)(indx,j) < fgkCouplMin) continue;
1663       if (fPadIJ[1][j] == -5) fPadIJ[1][j] = -9; // flag overflow
1664       if (fPadIJ[1][j] < 0) continue; // exclude overflows and used pads
1665       if (!fPadIJ[1][j]) { fPadIJ[1][j] = 1; nOK++; } // pad to be used in fit
1666       if (nCoupled > 3) {
1667         // Check other clusters
1668         for (Int_t iclust1=0; iclust1<nCoupled; iclust1++) {
1669           indx1 = clustNumb[iclust1];
1670           if (indx1 < 0) continue;
1671           if ((*aijclupad)(indx1,j) < fgkCouplMin) continue;
1672           padpix[j] += (*aijclupad)(indx1,j);
1673         }
1674       } // if (nCoupled > 3)
1675     } // for (Int_t j=0; j<npad;
1676   } // for (Int_t iclust=0; iclust<nForFit
1677   if (nCoupled < 4) return nOK;
1678
1679   Double_t aaa = 0;
1680   for (Int_t j=0; j<npad; j++) {
1681     if (padpix[j] < fgkCouplMin) continue;
1682     if (fDebug) cout << j << " " << padpix[j] << " " << fXyq[0][j] << " " << fXyq[1][j] << endl;
1683     aaa += padpix[j];
1684     fPadIJ[1][j] = -1; // exclude pads with strong coupling to the other clusters
1685     nOK--;
1686   }
1687   delete [] padpix; padpix = 0;
1688   return nOK;
1689 }
1690   
1691 //_____________________________________________________________________________
1692 void AliMUONClusterFinderAZ::Merge(Int_t nForFit, Int_t nCoupled, Int_t *clustNumb, Int_t *clustFit, TObjArray **clusters, TMatrixD *aijcluclu, TMatrixD *aijclupad)
1693 {
1694   // Merge the group of clusters with the one having the strongest coupling with them
1695
1696   Int_t indx, indx1, npxclu, npxclu1, imax=0;
1697   TObjArray *pix, *pix1;
1698   Double_t couplMax;
1699
1700   for (Int_t icl=0; icl<nForFit; icl++) {
1701     indx = clustFit[icl];
1702     pix = clusters[indx];
1703     npxclu = pix->GetEntriesFast();
1704     couplMax = -1;
1705     for (Int_t icl1=0; icl1<nCoupled; icl1++) {
1706       indx1 = clustNumb[icl1];
1707       if (indx1 < 0) continue;
1708       if ((*aijcluclu)(indx,indx1) > couplMax) {
1709         couplMax = (*aijcluclu)(indx,indx1);
1710         imax = indx1;
1711       }
1712     } // for (Int_t icl1=0;
1713     /*if (couplMax < fgkCouplMin) {
1714       cout << " Oops " << couplMax << endl;
1715       aijcluclu->Print();
1716       cout << icl << " " << indx << " " << npxclu << " " << nLinks << endl;
1717       ::exit(0);
1718       }*/
1719     // Add to it
1720     pix1 = clusters[imax];
1721     npxclu1 = pix1->GetEntriesFast();
1722     // Add pixels 
1723     for (Int_t i=0; i<npxclu; i++) { pix1->Add(pix->UncheckedAt(i)); pix->RemoveAt(i); }
1724     if (fDebug) cout << " New number of pixels: " << npxclu1 << " " << pix1->GetEntriesFast() << endl;
1725     //Add cluster-to-cluster couplings
1726     //aijcluclu->Print();
1727     for (Int_t icl1=0; icl1<nCoupled; icl1++) {
1728       indx1 = clustNumb[icl1];
1729       if (indx1 < 0 || indx1 == imax) continue;
1730       (*aijcluclu)(indx1,imax) += (*aijcluclu)(indx,indx1);
1731       (*aijcluclu)(imax,indx1) = (*aijcluclu)(indx1,imax);
1732     }
1733     (*aijcluclu)(indx,imax) = (*aijcluclu)(imax,indx) = 0;
1734     //aijcluclu->Print();
1735     //Add cluster-to-pad couplings
1736     for (Int_t j=0; j<fnPads[0]+fnPads[1]; j++) {
1737       if (fPadIJ[1][j] < 0 && fPadIJ[1][j] != -5) continue; // exclude used pads
1738       (*aijclupad)(imax,j) += (*aijclupad)(indx,j);
1739       (*aijclupad)(indx,j) = 0;
1740     }
1741   } // for (Int_t icl=0; icl<nForFit;
1742 }
1743
1744 //_____________________________________________________________________________
1745 Int_t AliMUONClusterFinderAZ::Fit(Int_t nfit, Int_t *clustFit, TObjArray **clusters, Double_t *parOk)
1746 {
1747   // Find selected clusters to selected pad charges
1748   
1749   TH2D *mlem = (TH2D*) gROOT->FindObject("mlem");
1750   //Int_t nx = mlem->GetNbinsX();
1751   //Int_t ny = mlem->GetNbinsY();
1752   Double_t xmin = mlem->GetXaxis()->GetXmin() - mlem->GetXaxis()->GetBinWidth(1);
1753   Double_t xmax = mlem->GetXaxis()->GetXmax() + mlem->GetXaxis()->GetBinWidth(1);
1754   Double_t ymin = mlem->GetYaxis()->GetXmin() - mlem->GetYaxis()->GetBinWidth(1);
1755   Double_t ymax = mlem->GetYaxis()->GetXmax() + mlem->GetYaxis()->GetBinWidth(1);
1756   //Double_t qmin = 0, qmax = 1;
1757   Double_t step[3]={0.01,0.002,0.02}, xPad = 0, yPad = 99999;
1758   Double_t qPad[2] = {0}, xyqPad[2] = {0};
1759
1760   // Number of pads to use and number of virtual pads
1761   Int_t npads = 0, nVirtual = 0;
1762   for (Int_t i=0; i<fnPads[0]+fnPads[1]; i++) {
1763     if (fPadIJ[1][i] == -9 || fPadIJ[1][i] == 1) {
1764       if (fPadIJ[0][i]) xyqPad[1] += fXyq[0][i] * fXyq[2][i];
1765       else xyqPad[0] += fXyq[1][i] * fXyq[2][i];
1766       qPad[fPadIJ[0][i]] += fXyq[2][i];
1767     }
1768     if (fXyq[3][i] < 0) nVirtual++;
1769     if (fPadIJ[1][i] != 1) continue;
1770     if (fXyq[3][i] > 0) npads++;
1771     if (yPad > 9999) { xPad = fXyq[0][i]; yPad = fXyq[1][i]; }
1772     //if (fPadIJ[0][i]) xPad = fXyq[0][i];
1773   }
1774   if (fDebug) {
1775     for (Int_t i=0; i<nfit; i++) {cout << i+1 << " " << clustFit[i] << " ";}
1776     cout << nfit << endl;
1777     cout << " Number of pads to fit: " << npads << endl;
1778   }
1779   fNpar = 0;
1780   fQtot = 0;
1781   if (npads < 2) return 0; 
1782
1783   Int_t digit = 0, nfit0 = nfit;
1784   AliMUONDigit *mdig = 0;
1785   Int_t tracks[3] = {-1, -1, -1};
1786   for (Int_t cath=0; cath<2; cath++) {  
1787     for (Int_t i=0; i<fnPads[0]+fnPads[1]; i++) {
1788       if (fPadIJ[0][i] != cath) continue;
1789       if (fPadIJ[1][i] != 1) continue;
1790       if (fXyq[3][i] < 0) continue; // exclude virtual pads
1791       digit = TMath::Nint (fXyq[5][i]);
1792       if (digit >= 0) mdig = fInput->Digit(cath,digit);
1793       else mdig = fInput->Digit(TMath::Even(cath),-digit-1);
1794       //if (!mdig) mdig = fInput->Digit(TMath::Even(cath),digit);
1795       if (!mdig) continue; // protection for cluster display
1796       if (mdig->Hit() >= 0) {
1797         if (tracks[0] < 0) {
1798           tracks[0] = mdig->Hit();
1799           tracks[1] = mdig->Track(0);
1800         } else if (mdig->Track(0) < tracks[1]) {
1801           tracks[0] = mdig->Hit();
1802           tracks[1] = mdig->Track(0);
1803         }
1804       }
1805       //AZif (mdig->Track(1)) {
1806       if (mdig->Track(1) >= 0 && mdig->Track(1) != tracks[1]) {
1807         if (tracks[2] < 0) tracks[2] = mdig->Track(1);
1808         else tracks[2] = TMath::Min (tracks[2], mdig->Track(1));
1809       }
1810       //if (!mdig) break;
1811       //cout << mdig->Hit() << " " << mdig->Track(0) << " " << mdig->Track(1) <<endl;
1812     } // for (Int_t i=0;
1813   } // for (Int_t cath=0;
1814   //cout << tracks[0] << " " << tracks[1] << " " << tracks[2] <<endl;
1815   
1816   // Get number of pads in X and Y 
1817   Int_t nInX = 0, nInY;
1818   PadsInXandY(nInX, nInY);
1819   //cout << " nInX and Y: " << nInX << " " << nInY << endl;
1820
1821   // Take cluster maxima as fitting seeds
1822   TObjArray *pix;
1823   AliMUONPixel *pixPtr;
1824   Int_t npxclu;
1825   Double_t cont, cmax = 0, xseed = 0, yseed = 0, errOk[8], qq = 0;
1826   Double_t xyseed[3][2], qseed[3], xyCand[3][2] = {{0},{0}}, sigCand[3][2] = {{0},{0}};
1827
1828   for (Int_t ifit=1; ifit<=nfit; ifit++) {
1829     cmax = 0;
1830     pix = clusters[clustFit[ifit-1]];
1831     npxclu = pix->GetEntriesFast();
1832     //qq = 0;
1833     for (Int_t clu=0; clu<npxclu; clu++) {
1834       pixPtr = (AliMUONPixel*) pix->UncheckedAt(clu);
1835       cont = pixPtr->Charge();
1836       fQtot += cont;
1837       if (cont > cmax) { 
1838         cmax = cont; 
1839         xseed = pixPtr->Coord(0);
1840         yseed = pixPtr->Coord(1);
1841       }
1842       qq += cont;
1843       /*
1844       xyCand[ifit-1][0] += pixPtr->Coord(0) * cont;
1845       xyCand[ifit-1][1] += pixPtr->Coord(1) * cont;
1846       sigCand[ifit-1][0] += pixPtr->Coord(0) * pixPtr->Coord(0) * cont;
1847       sigCand[ifit-1][1] += pixPtr->Coord(1) * pixPtr->Coord(1) * cont;
1848       */
1849       xyCand[0][0] += pixPtr->Coord(0) * cont;
1850       xyCand[0][1] += pixPtr->Coord(1) * cont;
1851       sigCand[0][0] += pixPtr->Coord(0) * pixPtr->Coord(0) * cont;
1852       sigCand[0][1] += pixPtr->Coord(1) * pixPtr->Coord(1) * cont;
1853     }
1854     xyseed[ifit-1][0] = xseed;
1855     xyseed[ifit-1][1] = yseed;
1856     qseed[ifit-1] = cmax;
1857     /*
1858     xyCand[ifit-1][0] /= qq; // <x>
1859     xyCand[ifit-1][1] /= qq; // <y>
1860     sigCand[ifit-1][0] = sigCand[ifit-1][0]/qq - xyCand[ifit-1][0]*xyCand[ifit-1][0]; // <x^2> - <x>^2
1861     sigCand[ifit-1][0] = sigCand[ifit-1][0] > 0 ? TMath::Sqrt (sigCand[ifit-1][0]) : 0;
1862     sigCand[ifit-1][1] = sigCand[ifit-1][1]/qq - xyCand[ifit-1][1]*xyCand[ifit-1][1]; // <y^2> - <y>^2
1863     sigCand[ifit-1][1] = sigCand[ifit-1][1] > 0 ? TMath::Sqrt (sigCand[ifit-1][1]) : 0;
1864     cout << xyCand[ifit-1][0] << " " << xyCand[ifit-1][1] << " " << sigCand[ifit-1][0] << " " << sigCand[ifit-1][1] << endl;
1865     */
1866   } // for (Int_t ifit=1;
1867
1868   xyCand[0][0] /= qq; // <x>
1869   xyCand[0][1] /= qq; // <y>
1870   sigCand[0][0] = sigCand[0][0]/qq - xyCand[0][0]*xyCand[0][0]; // <x^2> - <x>^2
1871   sigCand[0][0] = sigCand[0][0] > 0 ? TMath::Sqrt (sigCand[0][0]) : 0;
1872   sigCand[0][1] = sigCand[0][1]/qq - xyCand[0][1]*xyCand[0][1]; // <y^2> - <y>^2
1873   sigCand[0][1] = sigCand[0][1] > 0 ? TMath::Sqrt (sigCand[0][1]) : 0;
1874   if (fDebug) cout << xyCand[0][0] << " " << xyCand[0][1] << " " << sigCand[0][0] << " " << sigCand[0][1] << endl;
1875
1876   Int_t nDof, maxSeed[3];
1877   Double_t fmin, chi2o = 9999, chi2n;
1878
1879   // Try to fit with one-track hypothesis, then 2-track. If chi2/dof is 
1880   // lower, try 3-track (if number of pads is sufficient).
1881   
1882   TMath::Sort(nfit, qseed, maxSeed, kTRUE); // in decreasing order
1883   nfit = TMath::Min (nfit, (npads + 1) / 3);
1884   if (nfit > 1) {
1885     if (nInX < 3 && nInY < 3 || nInX == 3 && nInY < 3 || nInX < 3 && nInY == 3) nfit = 1; // not enough pads in each direction
1886   }
1887   //if (nfit > 1) nfit --;
1888   // One pad per direction 
1889   //if (nInX == 1) { step[0] /= 1; xyseed[0][0] = xPad; }
1890   //if (nInY == 1) { step[1] /= 1; xyseed[0][1] = yPad; }
1891
1892   Double_t *gin = 0, func0, func1, param[8], param0[2][8], deriv[2][8], step0[8];
1893   Double_t shift[8], stepMax, derMax, parmin[8], parmax[8], func2[2], shift0;
1894   Double_t delta[8], scMax, dder[8], estim, shiftSave = 0;
1895   Int_t min, max, nCall = 0, memory[8] = {0}, nLoop, idMax = 0, iestMax = 0, nFail;
1896   Double_t rad, dist[3] = {0};
1897
1898   for (Int_t iseed=0; iseed<nfit; iseed++) {
1899
1900     if (iseed) { for (Int_t j=0; j<fNpar; j++) param[j] = parOk[j]; } // for bounded params
1901     for (Int_t j=0; j<3; j++) step0[fNpar+j] = shift[fNpar+j] = step[j];
1902     param[fNpar] = xyseed[maxSeed[iseed]][0];
1903     parmin[fNpar] = xmin; 
1904     parmax[fNpar++] = xmax; 
1905     param[fNpar] = xyseed[maxSeed[iseed]][1];
1906     parmin[fNpar] = ymin; 
1907     parmax[fNpar++] = ymax; 
1908     if (fNpar > 2) {
1909       param[fNpar] = fNpar == 4 ? 0.5 : 0.3;
1910       parmin[fNpar] = 0; 
1911       parmax[fNpar++] = 1; 
1912     }
1913     if (iseed) { for (Int_t j=0; j<fNpar; j++) param0[1][j] = 0; }
1914
1915     // Try new algorithm
1916     min = nLoop = 1; stepMax = func2[1] = derMax = 999999; nFail = 0;
1917
1918     while (1) {
1919       max = !min;
1920       Fcn1(fNpar, gin, func0, param, 1); nCall++;
1921       //cout << " Func: " << func0 << endl;
1922
1923       func2[max] = func0;
1924       for (Int_t j=0; j<fNpar; j++) {
1925         param0[max][j] = param[j];
1926         delta[j] = step0[j];
1927         param[j] += delta[j] / 10;
1928         if (j > 0) param[j-1] -= delta[j-1] / 10;
1929         Fcn1(fNpar, gin, func1, param, 1); nCall++;
1930         deriv[max][j] = (func1 - func0) / delta[j] * 10; // first derivative
1931         //cout << j << " " << deriv[max][j] << endl;
1932         dder[j] = param0[0][j] != param0[1][j] ? (deriv[0][j] - deriv[1][j]) / 
1933                                                  (param0[0][j] - param0[1][j]) : 0; // second derivative
1934       }
1935       param[fNpar-1] -= delta[fNpar-1] / 10;
1936       if (nCall > 2000) break;
1937
1938       min = func2[0] < func2[1] ? 0 : 1;
1939       nFail = min == max ? 0 : nFail + 1;
1940
1941       stepMax = derMax = estim = 0;
1942       for (Int_t j=0; j<fNpar; j++) { 
1943         // Estimated distance to minimum
1944         shift0 = shift[j];
1945         if (nLoop == 1) shift[j] = TMath::Sign (step0[j], -deriv[max][j]); // first step
1946         else if (TMath::Abs(deriv[0][j]) < 1.e-3 && TMath::Abs(deriv[1][j]) < 1.e-3) shift[j] = 0;
1947         else if (deriv[min][j]*deriv[!min][j] > 0 && TMath::Abs(deriv[min][j]) > TMath::Abs(deriv[!min][j])
1948                  //|| TMath::Abs(deriv[0][j]-deriv[1][j]) < 1.e-3) {
1949           || TMath::Abs(deriv[0][j]-deriv[1][j]) < 1.e-3 || TMath::Abs(dder[j]) < 1.e-6) {
1950           shift[j] = -TMath::Sign (shift[j], (func2[0]-func2[1]) * (param0[0][j]-param0[1][j]));
1951           if (min == max) { 
1952             if (memory[j] > 1) { shift[j] *= 2; } //cout << " Memory " << memory[j] << " " << shift[j] << endl; }
1953             memory[j]++;
1954           }
1955         } else {
1956           shift[j] = dder[j] != 0 ? -deriv[min][j] / dder[j] : 0;
1957           memory[j] = 0;
1958         }
1959         if (TMath::Abs(shift[j])/step0[j] > estim) { 
1960           estim = TMath::Abs(shift[j])/step0[j];
1961           iestMax = j;
1962         }
1963
1964         // Too big step
1965         if (TMath::Abs(shift[j])/step0[j] > 10) shift[j] = TMath::Sign(10.,shift[j]) * step0[j]; // 
1966
1967         // Failed to improve minimum
1968         if (min != max) {
1969           memory[j] = 0;
1970           param[j] = param0[min][j];
1971           if (TMath::Abs(shift[j]+shift0) > 0.1*step0[j]) shift[j] = (shift[j] + shift0) / 2;
1972           else shift[j] /= -2;
1973         } 
1974
1975         // Too big step
1976         if (TMath::Abs(shift[j]*deriv[min][j]) > func2[min]) 
1977           shift[j] = TMath::Sign (func2[min]/deriv[min][j], shift[j]);
1978
1979         // Introduce step relaxation factor
1980         if (memory[j] < 3) {
1981           scMax = 1 + 4 / TMath::Max(nLoop/2.,1.);
1982           if (TMath::Abs(shift0) > 0 && TMath::Abs(shift[j]/shift0) > scMax) 
1983             shift[j] = TMath::Sign (shift0*scMax, shift[j]);
1984         }
1985         param[j] += shift[j]; 
1986         //AZ Check parameter limits 27-12-2004
1987         if (param[j] < parmin[j]) { 
1988           shift[j] = parmin[j] - param[j]; 
1989           param[j] = parmin[j]; 
1990         } else if (param[j] > parmax[j]) {
1991           shift[j] = parmax[j] - param[j];
1992           param[j] = parmax[j];
1993         }
1994         //cout << " xxx " << j << " " << shift[j] << " " << param[j] << endl;
1995         stepMax = TMath::Max (stepMax, TMath::Abs(shift[j]/step0[j]));
1996         if (TMath::Abs(deriv[min][j]) > derMax) {
1997           idMax = j;
1998           derMax = TMath::Abs (deriv[min][j]);
1999         }
2000       } // for (Int_t j=0; j<fNpar;
2001       //cout << max << " " << func2[min] << " " << derMax << " " << stepMax << " " << estim << " " << iestMax << " " << nCall << endl;
2002       if (estim < 1 && derMax < 2 || nLoop > 150) break; // minimum was found
2003
2004       nLoop++;
2005       // Check for small step
2006       if (shift[idMax] == 0) { shift[idMax] = step0[idMax]/10; param[idMax] += shift[idMax]; continue; }
2007       if (!memory[idMax] && derMax > 0.5 && nLoop > 10) {
2008         //cout << " ok " << deriv[min][idMax] << " " << deriv[!min][idMax] << " " << dder[idMax]*shift[idMax] << " " << shift[idMax] << endl;
2009         if (dder[idMax] != 0 && TMath::Abs(deriv[min][idMax]/dder[idMax]/shift[idMax]) > 10) {
2010           if (min == max) dder[idMax] = -dder[idMax];
2011           shift[idMax] = -deriv[min][idMax] / dder[idMax] / 10; 
2012           param[idMax] += shift[idMax];
2013           stepMax = TMath::Max (stepMax, TMath::Abs(shift[idMax])/step0[idMax]);
2014           //cout << shift[idMax] << " " << param[idMax] << endl;
2015           if (min == max) shiftSave = shift[idMax];
2016         }
2017         if (nFail > 10) {
2018           param[idMax] -= shift[idMax];
2019           shift[idMax] = 4 * shiftSave * (gRandom->Rndm(0) - 0.5);
2020           param[idMax] += shift[idMax];
2021           //cout << shift[idMax] << endl;
2022         }
2023       }      
2024     } // while (1)
2025     fmin = func2[min];
2026
2027     nDof = npads - fNpar + nVirtual;
2028     if (!nDof) nDof++;
2029     chi2n = fmin / nDof;
2030     if (fDebug) cout << " Chi2 " << chi2n << " " << fNpar << endl;
2031
2032     if (chi2n*1.2+1.e-6 > chi2o ) { fNpar -= 3; break; }
2033
2034     // Save parameters and errors
2035
2036     if (nInX == 1 && qPad[1] > 1) {
2037       // One pad per direction 
2038       xPad = xyqPad[1] / qPad[1]; // take COG for this case
2039       for (Int_t i=0; i<fNpar; i++) if (i == 0 || i == 2 || i == 5) param0[min][i] = xPad;
2040     }
2041     if (nInY == 1 && qPad[0] > 1) {
2042       // One pad per direction 
2043       yPad = xyqPad[0] / qPad[0]; // take COG for this case
2044       for (Int_t i=0; i<fNpar; i++) if (i == 1 || i == 3 || i == 6) param0[min][i] = yPad;
2045     }
2046
2047     /*
2048     if (iseed > 0) {
2049       // Find distance to the nearest neighbour
2050       dist[0] = dist[1] = TMath::Sqrt ((param0[min][0]-param0[min][2])*
2051                                        (param0[min][0]-param0[min][2])
2052                                       +(param0[min][1]-param0[min][3])*
2053                                        (param0[min][1]-param0[min][3]));
2054       if (iseed > 1) {
2055         dist[2] = TMath::Sqrt ((param0[min][0]-param0[min][5])*
2056                                (param0[min][0]-param0[min][5])
2057                               +(param0[min][1]-param0[min][6])*
2058                                (param0[min][1]-param0[min][6]));
2059         rad = TMath::Sqrt ((param0[min][2]-param0[min][5])*
2060                            (param0[min][2]-param0[min][5])
2061                           +(param0[min][3]-param0[min][6])*
2062                            (param0[min][3]-param0[min][6]));
2063         if (dist[2] < dist[0]) dist[0] = dist[2];
2064         if (rad < dist[1]) dist[1] = rad;
2065         if (rad < dist[2]) dist[2] = rad;
2066       }
2067       cout << dist[0] << " " << dist[1] << " " << dist[2] << endl;
2068       if (dist[TMath::LocMin(iseed+1,dist)] < 1.) { fNpar -= 3; break; }
2069     }
2070     */
2071
2072     for (Int_t i=0; i<fNpar; i++) {
2073       parOk[i] = param0[min][i];
2074       errOk[i] = fmin;
2075       // Bounded params
2076       parOk[i] = TMath::Max (parOk[i], parmin[i]);
2077       parOk[i] = TMath::Min (parOk[i], parmax[i]);
2078     }
2079
2080     chi2o = chi2n;
2081     if (fmin < 0.1) break; // !!!???
2082   } // for (Int_t iseed=0; 
2083
2084   if (fDebug) {
2085     for (Int_t i=0; i<fNpar; i++) {
2086       //if (i == 4 || i == 7) continue;
2087       if (i == 4 || i == 7) {
2088         if (i == 7 || i == 4 && fNpar < 7) cout << parOk[i] << endl;
2089         else cout << parOk[i] * (1-parOk[7]) << endl;
2090         continue;
2091       }
2092       cout << parOk[i] << " " << errOk[i] << endl;
2093     }
2094   }
2095   nfit = (fNpar + 1) / 3;
2096   dist[0] = dist[1] = dist[2] = 0;
2097
2098   if (nfit > 1) {
2099     // Find distance to the nearest neighbour
2100     dist[0] = dist[1] = TMath::Sqrt ((parOk[0]-parOk[2])*
2101                                      (parOk[0]-parOk[2])
2102                                     +(parOk[1]-parOk[3])*
2103                                      (parOk[1]-parOk[3]));
2104     if (nfit > 2) {
2105       dist[2] = TMath::Sqrt ((parOk[0]-parOk[5])*
2106                              (parOk[0]-parOk[5])
2107                             +(parOk[1]-parOk[6])*
2108                              (parOk[1]-parOk[6]));
2109       rad = TMath::Sqrt ((parOk[2]-parOk[5])*
2110                          (parOk[2]-parOk[5])
2111                         +(parOk[3]-parOk[6])*
2112                          (parOk[3]-parOk[6]));
2113       if (dist[2] < dist[0]) dist[0] = dist[2];
2114       if (rad < dist[1]) dist[1] = rad;
2115       if (rad < dist[2]) dist[2] = rad;
2116     }
2117   }
2118
2119   Int_t indx;
2120   fnPads[1] -= nVirtual;
2121   if (!fDraw) {
2122     Double_t coef = 0;
2123     //for (Int_t j=0; j<nfit; j++) {
2124     for (Int_t j=nfit-1; j>=0; j--) {
2125       indx = j<2 ? j*2 : j*2+1;  
2126       if (nfit == 1) coef = 1;
2127       else coef = j==nfit-1 ? parOk[indx+2] : 1-coef;
2128       coef = TMath::Max (coef, 0.);
2129       if (nfit == 3 && j < 2) coef = j==1 ? coef*parOk[indx+2] : coef - parOk[7];
2130       coef = TMath::Max (coef, 0.);
2131       AddRawCluster (parOk[indx], parOk[indx+1], coef*fQtot, errOk[indx], nfit0+10*nfit, tracks,
2132                      //sigCand[maxSeed[j]][0], sigCand[maxSeed[j]][1]);
2133                      //sigCand[0][0], sigCand[0][1], dist[j]);
2134                      sigCand[0][0], sigCand[0][1], dist[TMath::LocMin(nfit,dist)]);
2135     }
2136   } else fDraw->FillMuon(nfit, parOk, errOk);
2137   return nfit;
2138 }  
2139
2140 //_____________________________________________________________________________
2141 void AliMUONClusterFinderAZ::Fcn1(Int_t & /*npar*/, Double_t * /*gin*/, Double_t &f, Double_t *par, Int_t /*iflag*/)
2142 {
2143   // Fit for one track
2144   //AZ for Muinuit AliMUONClusterFinderAZ& c = *(AliMUONClusterFinderAZ::fgClusterFinder);    
2145   AliMUONClusterFinderAZ& c = *this; //AZ
2146   
2147   Int_t cath, ix, iy, indx, npads=0;
2148   Double_t charge, delta, coef=0, chi2=0, qTot = 0;
2149   for (Int_t j=0; j<c.fnPads[0]+c.fnPads[1]; j++) {
2150     if (c.fPadIJ[1][j] != 1) continue;
2151     cath = c.fPadIJ[0][j];
2152     if (c.fXyq[3][j] > 0) npads++; // exclude virtual pads
2153     qTot += c.fXyq[2][j];
2154     c.fSegmentation[cath]->GetPadI(fInput->DetElemId(),c.fXyq[0][j],c.fXyq[1][j],c.fZpad,ix,iy);
2155     c.fSegmentation[cath]->SetPad(fInput->DetElemId(),ix,iy);
2156     charge = 0;
2157     for (Int_t i=c.fNpar/3; i>=0; i--) { // sum over tracks
2158       indx = i<2 ? 2*i : 2*i+1;
2159       c.fSegmentation[cath]->SetHit(fInput->DetElemId(),par[indx],par[indx+1],c.fZpad);
2160       //charge += c.fResponse->IntXY(fInput->DetElemId(),c.fSegmentation[cath])*par[icl*3+2];
2161       if (c.fNpar == 2) coef = 1;
2162       else coef = i==c.fNpar/3 ? par[indx+2] : 1-coef;
2163       coef = TMath::Max (coef, 0.);
2164       if (c.fNpar == 8 && i < 2) coef = i==1 ? coef*par[indx+2] : coef - par[7];
2165       coef = TMath::Max (coef, 0.);
2166       charge += c.fResponse->IntXY(fInput->DetElemId(),c.fSegmentation[cath])*coef;
2167     }
2168     charge *= c.fQtot;
2169     //if (c.fXyq[2][j] > c.fResponse->MaxAdc()-1 && charge > 
2170     //  c.fResponse->MaxAdc()) charge = c.fResponse->MaxAdc(); 
2171     delta = charge - c.fXyq[2][j];
2172     delta *= delta;
2173     delta /= c.fXyq[2][j];
2174     //if (cath) delta /= 5; // just for test
2175     chi2 += delta;
2176   } // for (Int_t j=0;
2177   f = chi2; 
2178   Double_t qAver = qTot/npads; //(c.fnPads[0]+c.fnPads[1]);
2179   f = chi2/qAver;
2180 }
2181
2182 //_____________________________________________________________________________
2183 void AliMUONClusterFinderAZ::UpdatePads(Int_t /*nfit*/, Double_t *par)
2184 {
2185   // Subtract the fitted charges from pads with strong coupling
2186
2187   Int_t cath, ix, iy, indx;
2188   Double_t charge, coef=0;
2189   for (Int_t j=0; j<fnPads[0]+fnPads[1]; j++) {
2190     if (fPadIJ[1][j] != -1) continue;
2191     if (fNpar != 0) {
2192       cath = fPadIJ[0][j];
2193       fSegmentation[cath]->GetPadI(fInput->DetElemId(),fXyq[0][j],fXyq[1][j],fZpad,ix,iy);
2194       fSegmentation[cath]->SetPad(fInput->DetElemId(),ix,iy);
2195       charge = 0;
2196       for (Int_t i=fNpar/3; i>=0; i--) { // sum over tracks
2197         indx = i<2 ? 2*i : 2*i+1;
2198         fSegmentation[cath]->SetHit(fInput->DetElemId(),par[indx],par[indx+1],fZpad);
2199         if (fNpar == 2) coef = 1;
2200         else coef = i==fNpar/3 ? par[indx+2] : 1-coef;
2201         coef = TMath::Max (coef, 0.);
2202         if (fNpar == 8 && i < 2) coef = i==1 ? coef*par[indx+2] : coef - par[7];
2203         coef = TMath::Max (coef, 0.);
2204         charge += fResponse->IntXY(fInput->DetElemId(),fSegmentation[cath])*coef;
2205       }
2206       charge *= fQtot;
2207       fXyq[2][j] -= charge;
2208     } // if (fNpar != 0)
2209     if (fXyq[2][j] > fResponse->ZeroSuppression()) fPadIJ[1][j] = 0; // return pad for further using
2210   } // for (Int_t j=0;
2211 }  
2212
2213 //_____________________________________________________________________________
2214 Bool_t AliMUONClusterFinderAZ::TestTrack(Int_t /*t*/) const {
2215 // Test if track was user selected
2216   return kTRUE;
2217   /*
2218     if (fTrack[0]==-1 || fTrack[1]==-1) {
2219         return kTRUE;
2220     } else if (t==fTrack[0] || t==fTrack[1]) {
2221         return kTRUE;
2222     } else {
2223         return kFALSE;
2224     }
2225   */
2226 }
2227
2228 //_____________________________________________________________________________
2229 void AliMUONClusterFinderAZ::AddRawCluster(Double_t x, Double_t y, Double_t qTot, Double_t fmin, Int_t nfit, Int_t *tracks, Double_t /*sigx*/, Double_t /*sigy*/, Double_t /*dist*/)
2230 {
2231   //
2232   // Add a raw cluster copy to the list
2233   //
2234   if (qTot <= 0.501) return; 
2235   AliMUONRawCluster cnew;
2236   AliMUON *pMUON=(AliMUON*)gAlice->GetModule("MUON");
2237   pMUON=0; //AZ
2238   //pMUON->AddRawCluster(fInput->Chamber(),c); 
2239
2240   Int_t cath, npads[2] = {0}, nover[2] = {0};
2241   for (Int_t j=0; j<fnPads[0]+fnPads[1]; j++) {
2242     cath = fPadIJ[0][j];
2243     // There was an overflow
2244     if (fPadIJ[1][j] == -9) nover[cath]++;
2245     if (fPadIJ[1][j] != 1 && fPadIJ[1][j] != -9) continue;
2246     cnew.SetMultiplicity(cath,cnew.GetMultiplicity(cath)+1);
2247     if (fXyq[2][j] > cnew.GetPeakSignal(cath)) cnew.SetPeakSignal(cath,TMath::Nint (fXyq[2][j]));
2248     //cnew.SetCharge(cath,cnew.GetCharge(cath) + TMath::Nint (fXyq[2][j]));
2249     cnew.SetContrib(npads[cath],cath,fXyq[2][j]);
2250     cnew.SetIndex(npads[cath],cath,TMath::Nint (fXyq[5][j]));
2251     cnew.SetDetElemId(fInput->DetElemId());
2252     npads[cath]++;
2253   }
2254
2255   cnew.SetClusterType(nover[0] + nover[1] * 100);
2256   for (Int_t j=0; j<3; j++) cnew.SetTrack(j,tracks[j]);
2257
2258   for (cath=0; cath<2; cath++) {
2259     cnew.SetX(cath, x);
2260     cnew.SetY(cath, y);
2261     cnew.SetZ(cath, fZpad);
2262     cnew.SetCharge(cath, TMath::Nint(qTot));
2263     //cnew.SetPeakSignal(cath,20);
2264     //cnew.SetMultiplicity(cath, 5);
2265     cnew.SetNcluster(cath, nfit);
2266     cnew.SetChi2(cath, fmin); //0.;1
2267   } 
2268   // Evaluate measurement errors
2269   //AZ Errors(&cnew);
2270
2271   cnew.SetGhost(nfit); //cnew.SetX(1,sigx); cnew.SetY(1,sigy); cnew.SetZ(1,dist);
2272   //cnew.fClusterType=cnew.PhysicsContribution();
2273   //AZ pMUON->GetMUONData()->AddRawCluster(AliMUONClusterInput::Instance()->Chamber(),cnew); 
2274   new((*fRawClusters)[fNRawClusters++]) AliMUONRawCluster(cnew); //AZ
2275   if (fDebug) cout << fNRawClusters << " " << AliMUONClusterInput::Instance()->Chamber() << endl;
2276   //fNPeaks++;
2277 }
2278
2279 //_____________________________________________________________________________
2280 Int_t AliMUONClusterFinderAZ::FindLocalMaxima(Int_t *localMax, Double_t *maxVal)
2281 {
2282   // Find local maxima in pixel space for large preclusters in order to
2283   // try to split them into smaller pieces (to speed up the MLEM procedure)
2284
2285   TH2D *hist = (TH2D*) gROOT->FindObject("anode");
2286   if (hist) hist->Delete();
2287
2288   Double_t xylim[4] = {999, 999, 999, 999};
2289   Int_t nPix = fPixArray->GetEntriesFast();
2290   AliMUONPixel *pixPtr = 0;
2291   for (Int_t ipix=0; ipix<nPix; ipix++) {
2292     pixPtr = (AliMUONPixel*) fPixArray->UncheckedAt(ipix);
2293     for (Int_t i=0; i<4; i++) 
2294          xylim[i] = TMath::Min (xylim[i], (i%2 ? -1 : 1)*pixPtr->Coord(i/2));
2295   }
2296   for (Int_t i=0; i<4; i++) xylim[i] -= pixPtr->Size(i/2); 
2297
2298   Int_t nx = TMath::Nint ((-xylim[1]-xylim[0])/pixPtr->Size(0)/2);
2299   Int_t ny = TMath::Nint ((-xylim[3]-xylim[2])/pixPtr->Size(1)/2);
2300   hist = new TH2D("anode","anode",nx,xylim[0],-xylim[1],ny,xylim[2],-xylim[3]);
2301   for (Int_t ipix=0; ipix<nPix; ipix++) {
2302     pixPtr = (AliMUONPixel*) fPixArray->UncheckedAt(ipix);
2303     hist->Fill(pixPtr->Coord(0), pixPtr->Coord(1), pixPtr->Charge());
2304   }
2305   if (fDraw) fDraw->DrawHist("c2", hist);
2306
2307   Int_t nMax = 0, indx;
2308   Int_t *isLocalMax = new Int_t[ny*nx];
2309   for (Int_t i=0; i<ny*nx; i++) isLocalMax[i] = 0;
2310
2311   for (Int_t i=1; i<=ny; i++) {
2312     indx = (i-1) * nx;
2313     for (Int_t j=1; j<=nx; j++) {
2314       if (hist->GetCellContent(j,i) < 0.5) continue;
2315       //if (isLocalMax[indx+j-1] < 0) continue;
2316       if (isLocalMax[indx+j-1] != 0) continue;
2317       FlagLocalMax(hist, i, j, isLocalMax);
2318     }
2319   }
2320
2321   for (Int_t i=1; i<=ny; i++) {
2322     indx = (i-1) * nx;
2323     for (Int_t j=1; j<=nx; j++) {
2324       if (isLocalMax[indx+j-1] > 0) { 
2325         localMax[nMax] = indx + j - 1; 
2326         maxVal[nMax++] = hist->GetCellContent(j,i);
2327         if (nMax > 99) AliFatal(" Too many local maxima !!!");
2328       }
2329     }
2330   }
2331   if (fDebug) cout << " Local max: " << nMax << endl;
2332   delete [] isLocalMax; isLocalMax = 0;
2333   return nMax;
2334 }
2335
2336 //_____________________________________________________________________________
2337 void AliMUONClusterFinderAZ::FlagLocalMax(TH2D *hist, Int_t i, Int_t j, Int_t *isLocalMax)
2338 {
2339   // Flag pixels (whether or not local maxima)
2340
2341   Int_t nx = hist->GetNbinsX();
2342   Int_t ny = hist->GetNbinsY();
2343   Int_t cont = TMath::Nint (hist->GetCellContent(j,i));
2344   Int_t cont1 = 0;
2345
2346   for (Int_t i1=i-1; i1<i+2; i1++) {
2347     if (i1 < 1 || i1 > ny) continue;
2348     for (Int_t j1=j-1; j1<j+2; j1++) {
2349       if (j1 < 1 || j1 > nx) continue;
2350       if (i == i1 && j == j1) continue;
2351       cont1 = TMath::Nint (hist->GetCellContent(j1,i1));
2352       if (cont < cont1) { isLocalMax[(i-1)*nx+j-1] = -1; return; }
2353       else if (cont > cont1) isLocalMax[(i1-1)*nx+j1-1] = -1;
2354       else { // the same charge
2355         isLocalMax[(i-1)*nx+j-1] = 1; 
2356         if (isLocalMax[(i1-1)*nx+j1-1] == 0) {
2357           FlagLocalMax(hist, i1, j1, isLocalMax);
2358           if (isLocalMax[(i1-1)*nx+j1-1] < 0) { isLocalMax[(i-1)*nx+j-1] = -1; return; }
2359           else isLocalMax[(i1-1)*nx+j1-1] = -1;
2360         }
2361       } 
2362     }
2363   }
2364   isLocalMax[(i-1)*nx+j-1] = 1; // local maximum
2365 }
2366
2367 //_____________________________________________________________________________
2368 void AliMUONClusterFinderAZ::FindCluster(Int_t *localMax, Int_t iMax)
2369 {
2370   // Find pixel cluster around local maximum #iMax and pick up pads
2371   // overlapping with it
2372
2373   TH2D *hist = (TH2D*) gROOT->FindObject("anode");
2374   Int_t nx = hist->GetNbinsX();
2375   Int_t ny = hist->GetNbinsY();
2376   Int_t ic = localMax[iMax] / nx + 1;
2377   Int_t jc = localMax[iMax] % nx + 1;
2378   Bool_t *used = new Bool_t[ny*nx];
2379   for (Int_t i=0; i<ny*nx; i++) used[i] = kFALSE;
2380
2381   // Drop all pixels from the array - pick up only the ones from the cluster
2382   fPixArray->Delete();
2383
2384   Double_t wx = hist->GetXaxis()->GetBinWidth(1)/2; 
2385   Double_t wy = hist->GetYaxis()->GetBinWidth(1)/2;  
2386   Double_t yc = hist->GetYaxis()->GetBinCenter(ic);
2387   Double_t xc = hist->GetXaxis()->GetBinCenter(jc);
2388   Double_t cont = hist->GetCellContent(jc,ic);
2389   AliMUONPixel *pixPtr = new AliMUONPixel (xc, yc, wx, wy, cont);
2390   fPixArray->Add((TObject*)pixPtr);
2391   used[(ic-1)*nx+jc-1] = kTRUE;
2392   AddBin(hist, ic, jc, 1, used, (TObjArray*)0); // recursive call
2393
2394   Int_t nPix = fPixArray->GetEntriesFast(), npad = fnPads[0] + fnPads[1];
2395   for (Int_t i=0; i<nPix; i++) {
2396     ((AliMUONPixel*)fPixArray->UncheckedAt(i))->SetSize(0,wx); 
2397     ((AliMUONPixel*)fPixArray->UncheckedAt(i))->SetSize(1,wy); 
2398   }
2399   if (fDebug) cout << iMax << " " << nPix << endl;
2400
2401   Float_t xy[4], xy12[4];
2402   // Pick up pads which overlap with found pixels
2403   for (Int_t i=0; i<npad; i++) fPadIJ[1][i] = -1;
2404   for (Int_t i=0; i<nPix; i++) {
2405     pixPtr = (AliMUONPixel*) fPixArray->UncheckedAt(i);
2406     for (Int_t j=0; j<4; j++) 
2407       xy[j] = pixPtr->Coord(j/2) + (j%2 ? 1 : -1)*pixPtr->Size(j/2);
2408     for (Int_t j=0; j<npad; j++) 
2409       if (Overlap(xy, j, xy12, 0)) fPadIJ[1][j] = 0; // flag for use
2410   }
2411
2412   delete [] used; used = 0;
2413 }
2414
2415 //_____________________________________________________________________________
2416 AliMUONClusterFinderAZ&  
2417 AliMUONClusterFinderAZ::operator=(const AliMUONClusterFinderAZ& rhs)
2418 {
2419 // Protected assignement operator
2420
2421   if (this == &rhs) return *this;
2422
2423   AliFatal("Not implemented.");
2424     
2425   return *this;  
2426 }    
2427           
2428 //_____________________________________________________________________________
2429 void AliMUONClusterFinderAZ::AddVirtualPad()
2430 {
2431   // Add virtual pad (with small charge) to improve fit for some
2432   // clusters (when pad with max charge is at the extreme of the cluster)
2433
2434   // Get number of pads in X and Y-directions
2435   Int_t nInX = -1, nInY;
2436   PadsInXandY(nInX, nInY);
2437   //return;
2438
2439   //nInY = npady[0];
2440   //nInX = npadx[1] ? npadx[1] : npadx[0];
2441   // Add virtual pads only if number of pads per direction == 2
2442   //if (!npadx[1] && npady[0] != 2 && npadx[0] != 2) return 0; // one-sided
2443   //if (npadx[1] && npady[0] != 2 && npadx[1] != 2) return 0;
2444   if (nInX != 2 && nInY != 2) return;
2445
2446   // Find pads with max charge
2447   Int_t maxpad[2][2] = {{-1, -1}, {-1, -1}}, cath;
2448   Double_t sigmax[2] = {0}, aamax[2] = {0};
2449   for (Int_t j=0; j<fnPads[0]+fnPads[1]; j++) {
2450     if (fPadIJ[1][j] != 0) continue;
2451     cath = fPadIJ[0][j];
2452     if (fXyq[2][j] > sigmax[cath]) {
2453       maxpad[cath][1] = maxpad[cath][0];
2454       aamax[cath] = sigmax[cath];
2455       sigmax[cath] = fXyq[2][j];
2456       maxpad[cath][0] = j;
2457     }
2458   }
2459   if (maxpad[0][0] >= 0 && maxpad[0][1] < 0 || maxpad[1][0] >= 0 && maxpad[1][1] < 0) {
2460     for (Int_t j=0; j<fnPads[0]+fnPads[1]; j++) {
2461       if (fPadIJ[1][j] != 0) continue;
2462       cath = fPadIJ[0][j];
2463       if (j == maxpad[cath][0] || j == maxpad[cath][1]) continue;
2464       if (fXyq[2][j] > aamax[cath]) {
2465         aamax[cath] = fXyq[2][j];
2466         maxpad[cath][1] = j;
2467       }
2468     }
2469   }
2470   // Check for mirrors (side X on cathode 0) 
2471   Bool_t mirror = kFALSE;
2472   if (maxpad[0][0] >= 0 && maxpad[1][0] >= 0) 
2473     mirror = fXyq[3][maxpad[0][0]] < fXyq[4][maxpad[0][0]]; 
2474
2475   // Find neughbours of pads with max charges
2476   Int_t nn, xList[10], yList[10], ix0, iy0, ix, iy, neighb;
2477   for (cath=0; cath<2; cath++) {
2478     if (!cath && maxpad[0][0] < 0) continue; // one-sided cluster - cathode 1
2479     if (cath && maxpad[1][0] < 0) break; // one-sided cluster - cathode 0
2480     if (maxpad[1][0] >= 0) {
2481       if (!mirror) {
2482         if (!cath && nInY != 2) continue;
2483         //AZ if (cath && nInX != 2) continue;
2484         if (cath && nInX != 2 && (maxpad[0][0] >= 0 || nInY != 2)) continue;
2485       } else {
2486         if (!cath && nInX != 2) continue;
2487         if (cath && nInY != 2 && (maxpad[0][0] >= 0 || nInX != 2)) continue;
2488       }
2489     }
2490
2491     Int_t iAddX = 0, iAddY = 0, ix1 = 0, iy1 = 0, iPad = 0;
2492     if (maxpad[0][0] < 0) iPad = 1;
2493
2494     /*
2495     // This part of code to take care of edge effect (problems in MC)
2496     Float_t sprX = fResponse->SigmaIntegration()*fResponse->ChargeSpreadX();
2497     Float_t sprY = fResponse->SigmaIntegration()*fResponse->ChargeSpreadY();
2498     Double_t rmin = 9999, rad2;
2499     Int_t border = 0, iYlow = 0, iMuon = 0;
2500
2501     if (fDraw) {
2502       for (Int_t i=0; i<2; i++) {
2503         rad2 = (fXyq[0][maxpad[iPad][0]]-fxyMu[i][0]) * (fXyq[0][maxpad[iPad][0]]-fxyMu[i][0]);
2504         rad2 += (fXyq[1][maxpad[iPad][0]]-fxyMu[i][1]) * (fXyq[1][maxpad[iPad][0]]-fxyMu[i][1]);
2505         if (rad2 < rmin) { iMuon = i; rmin = rad2; }
2506       }
2507       fSegmentation[cath]->FirstPad(fInput->DetElemId(),(Float_t)fxyMu[iMuon][0], (Float_t)fxyMu[iMuon][1], fZpad, sprX, sprY);  
2508       if (fSegmentation[cath]->Sector(fInput->DetElemId(),fSegmentation[cath]->Ix(),fSegmentation[cath]->Iy()) <= 0) {
2509         fSegmentation[cath]->NextPad(fInput->DetElemId());
2510         border = 1; 
2511         iYlow = fSegmentation[cath]->Iy();
2512       }
2513     }
2514     */
2515     
2516     for (iPad=0; iPad<2; iPad++) {
2517       if (iPad && !iAddX && !iAddY) break;
2518       if (iPad && fXyq[2][maxpad[cath][1]] / sigmax[cath] < 0.5) break;
2519
2520       Int_t neighbx = 0, neighby = 0;
2521       fSegmentation[cath]->GetPadI(fInput->DetElemId(),fXyq[0][maxpad[cath][iPad]],fXyq[1][maxpad[cath][iPad]],fZpad,ix0,iy0);
2522       fSegmentation[cath]->Neighbours(fInput->DetElemId(),ix0,iy0,&nn,xList,yList); 
2523       Float_t zpad; //, xpad, ypad;
2524       for (Int_t j=0; j<nn; j++) {
2525         /*
2526         if (border && yList[j] < iYlow) { xList[j] = yList[j] = 0; continue; }
2527         fSegmentation[cath]->GetPadC(fInput->DetElemId(),xList[j],yList[j],xpad,ypad,zpad);
2528         if (TMath::Abs(xpad) < 1 && TMath::Abs(ypad) < 1) 
2529           { xList[j] = yList[j] = 0; continue; } // strange case (something with pad mapping)
2530         */
2531         if (TMath::Abs(xList[j]-ix0) == 1 || TMath::Abs(xList[j]*ix0) == 1) neighbx++;
2532         if (TMath::Abs(yList[j]-iy0) == 1 || TMath::Abs(yList[j]*iy0) == 1) neighby++;
2533       }
2534       if (!mirror) {
2535         if (cath) neighb = neighbx; 
2536         else neighb = neighby;
2537         if (maxpad[0][0] < 0) neighb += neighby;
2538         else if (maxpad[1][0] < 0) neighb += neighbx;
2539       } else {
2540         if (!cath) neighb = neighbx; 
2541         else neighb = neighby;
2542         if (maxpad[0][0] < 0) neighb += neighbx;
2543         else if (maxpad[1][0] < 0) neighb += neighby;
2544       }
2545
2546       for (Int_t j=0; j<fnPads[0]+fnPads[1]; j++) {
2547         if (fPadIJ[0][j] != cath) continue;
2548         fSegmentation[cath]->GetPadI(fInput->DetElemId(),fXyq[0][j],fXyq[1][j],fZpad,ix,iy);
2549         if (iy == iy0 && ix == ix0) continue; 
2550         for (Int_t k=0; k<nn; k++) {
2551           if (xList[k] != ix || yList[k] != iy) continue;
2552           if (!mirror) {
2553             if ((!cath || maxpad[0][0] < 0) && 
2554                 //(TMath::Abs(iy-iy0) == 1 || TMath::Abs(iy*iy0) == 1)) {
2555                 (TMath::Abs(iy-iy0) == 1 || iy*iy0 == -1)) {
2556               xList[k] = yList[k] = 0; 
2557               neighb--;
2558               break;
2559             }
2560             if ((cath || maxpad[1][0] < 0) && 
2561                 //(TMath::Abs(ix-ix0) == 1 || TMath::Abs(ix*ix0) == 1)) {
2562                 (TMath::Abs(ix-ix0) == 1 || ix*ix0 == -1)) {
2563               xList[k] = yList[k] = 0; 
2564               neighb--;
2565             }
2566           } else {
2567             if ((!cath || maxpad[0][0] < 0) && 
2568                 //(TMath::Abs(ix-ix0) == 1 || TMath::Abs(ix*ix0) == 1)) {
2569                 (TMath::Abs(ix-ix0) == 1 || ix*ix0 == -1)) {
2570               xList[k] = yList[k] = 0; 
2571               neighb--;
2572               break;
2573             }
2574             if ((cath || maxpad[1][0] < 0) && 
2575                 //(TMath::Abs(iy-iy0) == 1 || TMath::Abs(iy*iy0) == 1)) {
2576                 (TMath::Abs(iy-iy0) == 1 || iy*iy0 == -1)) {
2577               xList[k] = yList[k] = 0; 
2578               neighb--;
2579             }
2580           }
2581           break;
2582         } // for (Int_t k=0; k<nn;
2583         if (!neighb) break;
2584       } // for (Int_t j=0; j<fnPads[0]+fnPads[1];
2585       if (!neighb) continue;
2586       
2587       // Add virtual pad
2588       Int_t npads, isec;
2589       isec = 0;
2590       for (Int_t j=0; j<nn; j++) {
2591         if (xList[j] == 0 && yList[j] == 0) continue;
2592         npads = fnPads[0] + fnPads[1];
2593         fPadIJ[0][npads] = cath;
2594         fPadIJ[1][npads] = 0;
2595         ix = xList[j]; 
2596         iy = yList[j];
2597         //if (TMath::Abs(ix-ix0) == 1 || TMath::Abs(ix*ix0) == 1) {
2598         if (TMath::Abs(ix-ix0) == 1 || ix*ix0 == -1) {
2599           if (iy != iy0) continue; // new segmentation - check
2600           if (nInX != 2) continue; // new
2601           if (!mirror) {
2602             if (!cath && maxpad[1][0] >= 0) continue;
2603             //if (maxpad[1][0] < 0 && nInX != 2) continue;
2604           } else {
2605             if (cath && maxpad[0][0] >= 0) continue;
2606             //if (maxpad[0][0] < 0 && nInX != 2) continue;
2607           }
2608           if (iPad && !iAddX) continue;
2609           fSegmentation[cath]->GetPadC(fInput->DetElemId(),ix,iy,fXyq[0][npads],fXyq[1][npads],zpad);
2610           if (fXyq[0][npads] > 1.e+5) continue; // temporary fix
2611           if (ix1 == ix0) continue;
2612           //if (iPad && ix1 == ix0) continue;
2613           //if (iPad && TMath::Abs(fXyq[0][npads]-fXyq[0][iAddX]) < fXyq[3][iAddX]) continue;
2614           //if (TMath::Abs(fXyq[0][npads]) < 1 && TMath::Abs(fXyq[1][npads]) < 1) continue; // strange case (something with pad mapping)
2615           if (maxpad[1][0] < 0 || mirror && maxpad[0][0] >= 0) {
2616             if (!iPad) fXyq[2][npads] = TMath::Min (sigmax[0]/100, 5.);
2617             else fXyq[2][npads] = TMath::Min (aamax[0]/100, 5.);
2618           }
2619           else {
2620             if (!iPad) fXyq[2][npads] = TMath::Min (sigmax[1]/100, 5.);
2621             else fXyq[2][npads] = TMath::Min (aamax[1]/100, 5.);
2622           }
2623           fXyq[2][npads] = TMath::Max (fXyq[2][npads], (float)1);
2624           //fXyq[2][npads] = 1; 
2625           //isec = fSegmentation[cath]->Sector(fInput->DetElemId(),ix, iy);
2626           //fXyq[3][npads] = fSegmentation[cath]->Dpx(fInput->DetElemId(),isec)/2;
2627           fXyq[3][npads] = -2; // flag
2628           fnPads[1]++;
2629           iAddX = npads;
2630           if (fDebug) printf(" ***** Add virtual pad in X ***** %f %f %f %3d %3d \n", fXyq[2][npads],
2631                              fXyq[0][npads], fXyq[1][npads], ix, iy);
2632           ix1 = ix0;
2633           continue;
2634         } 
2635         if (nInY != 2) continue;
2636         if (!mirror && cath && maxpad[0][0] >= 0) continue;
2637         if (mirror && !cath && maxpad[1][0] >= 0) continue;
2638         if (TMath::Abs(iy-iy0) == 1 || TMath::Abs(iy*iy0) == 1) {
2639           if (ix != ix0) continue; // new segmentation - check
2640           if (iPad && !iAddY) continue;
2641           fSegmentation[cath]->GetPadC(fInput->DetElemId(),ix,iy,fXyq[0][npads],fXyq[1][npads],zpad);
2642           if (iy1 == iy0) continue;
2643           //if (iPad && iy1 == iy0) continue;
2644           //if (iPad && TMath::Abs(fXyq[1][npads]-fXyq[1][iAddY]) < fXyq[4][iAddY]) continue;
2645           //if (TMath::Abs(fXyq[0][npads]) < 1 && TMath::Abs(fXyq[1][npads]) < 1) continue; // strange case (something with pad mapping)
2646           if (maxpad[0][0] < 0 || mirror && maxpad[1][0] >= 0) {
2647             //if (!iPad) fXyq[2][npads] = TMath::Min (sigmax[1]/20, 5.);
2648             //else fXyq[2][npads] = TMath::Min (aamax[1]/20, 5.);
2649             if (!iPad) fXyq[2][npads] = TMath::Min (sigmax[1]/15, (double)fResponse->ZeroSuppression());
2650             else fXyq[2][npads] = TMath::Min (aamax[1]/15, (double)fResponse->ZeroSuppression());
2651           }
2652           else {
2653             //if (!iPad) fXyq[2][npads] = TMath::Min (sigmax[0]/20, 5.);
2654             //else fXyq[2][npads] = TMath::Min (aamax[0]/20, 5.);
2655             if (!iPad) fXyq[2][npads] = TMath::Min (sigmax[0]/15, (double)fResponse->ZeroSuppression());
2656             else fXyq[2][npads] = TMath::Min (aamax[0]/15, (double)fResponse->ZeroSuppression());
2657           }
2658           fXyq[2][npads] = TMath::Max (fXyq[2][npads], (float)1);
2659           //isec = fSegmentation[cath]->Sector(fInput->DetElemId(),ix, iy);
2660           //fXyq[4][npads] = fSegmentation[cath]->Dpy(isec)/2;
2661           fXyq[3][npads] = -2; // flag
2662           fnPads[1]++;
2663           iAddY = npads;
2664           if (fDebug) printf(" ***** Add virtual pad in Y ***** %f %f %f %3d %3d \n", fXyq[2][npads],
2665                              fXyq[0][npads], fXyq[1][npads], ix, iy);
2666           iy1 = iy0;
2667         }
2668       } // for (Int_t j=0; j<nn;
2669     } // for (Int_t iPad=0;
2670   } // for (cath=0; cath<2;
2671   return;
2672 }
2673
2674 //_____________________________________________________________________________
2675 void AliMUONClusterFinderAZ::PadsInXandY(Int_t &nInX, Int_t &nInY)
2676 {
2677   // Find number of pads in X and Y-directions (excluding virtual ones and
2678   // overflows)
2679
2680   static Int_t nXsaved = 0, nYsaved = 0;
2681   nXsaved = nYsaved = 0;
2682   //if (nInX >= 0) {nInX = nXsaved; nInY = nYsaved; return; }
2683   Float_t *xPad0 = NULL, *yPad0 = NULL, *xPad1 = NULL, *yPad1 = NULL;
2684   Float_t wMinX[2] = {99, 99}, wMinY[2] = {99, 99};
2685   Int_t *nPad0 = NULL, *nPad1 = NULL;
2686   Int_t nPads = fnPads[0] + fnPads[1];
2687   if (fnPads[0]) {
2688     xPad0 = new Float_t[nPads];
2689     yPad0 = new Float_t[nPads];
2690     nPad0 = new Int_t[nPads];
2691   }
2692   if (fnPads[1]) {
2693     xPad1 = new Float_t[nPads];
2694     yPad1 = new Float_t[nPads];
2695     nPad1 = new Int_t[nPads];
2696   }
2697   Int_t n0 = 0, n1 = 0, cath, npadx[2] = {1, 1}, npady[2] = {1, 1};
2698   for (Int_t j = 0; j < nPads; j++) {
2699     //if (fPadIJ[1][j] != 0) continue;
2700     //if (fXyq[3][j] < 0) continue; // virtual pad
2701     if (nInX < 0 && fPadIJ[1][j] != 0) continue; // before fit
2702     else if (nInX == 0 && fPadIJ[1][j] != 1) continue; // fit - exclude overflows
2703     else if (nInX > 0 && fPadIJ[1][j] != 1 && fPadIJ[1][j] != -9) continue; // exclude non-marked
2704     if (nInX <= 0 && fXyq[2][j] > fResponse->Saturation()-1) continue; // skip overflows
2705     cath = fPadIJ[0][j];
2706     if (fXyq[3][j] > 0) { // exclude virtual pads
2707       wMinX[cath] = TMath::Min (wMinX[cath], fXyq[3][j]);
2708       wMinY[cath] = TMath::Min (wMinY[cath], fXyq[4][j]);
2709     }
2710     if (cath) { xPad1[n1] = fXyq[0][j]; yPad1[n1++] = fXyq[1][j]; }
2711     else { xPad0[n0] = fXyq[0][j]; yPad0[n0++] = fXyq[1][j]; }
2712   }
2713
2714   // Sort
2715   if (n0) { 
2716     TMath::Sort (n0, xPad0, nPad0); // in X
2717     for (Int_t i = 1; i < n0; i++) 
2718       if (xPad0[nPad0[i]] - xPad0[nPad0[i-1]] < -0.01) npadx[0]++;
2719     TMath::Sort (n0, yPad0, nPad0); // in Y
2720     for (Int_t i = 1; i < n0; i++) 
2721       if (yPad0[nPad0[i]] - yPad0[nPad0[i-1]] < -0.01) npady[0]++;
2722   }
2723   
2724   if (n1) { 
2725     TMath::Sort (n1, xPad1, nPad1); // in X
2726     for (Int_t i = 1; i < n1; i++) 
2727       if (xPad1[nPad1[i]] - xPad1[nPad1[i-1]] < -0.01) npadx[1]++;
2728     TMath::Sort (n1, yPad1, nPad1); // in Y
2729     for (Int_t i = 1; i < n1; i++) 
2730       if (yPad1[nPad1[i]] - yPad1[nPad1[i-1]] < -0.01) npady[1]++;
2731   }
2732   if (fnPads[0]) { delete [] xPad0; delete [] yPad0; delete [] nPad0; }
2733   if (fnPads[1]) { delete [] xPad1; delete [] yPad1; delete [] nPad1; }
2734   //nInY = TMath::Max (npady[0], npady[1]);
2735   //nInX = TMath::Max (npadx[0], npadx[1]);
2736   if (TMath::Abs (wMinY[0] - wMinY[1]) < 1.e-3) nInY = TMath::Max (npady[0], npady[1]);
2737   else nInY = wMinY[0] < wMinY[1] ? npady[0] : npady[1];
2738   if (TMath::Abs (wMinX[0] - wMinX[1]) < 1.e-3) nInX = TMath::Max (npadx[0], npadx[1]);
2739   else nInX = wMinX[0] < wMinX[1] ? npadx[0] : npadx[1];
2740 }
2741
2742 //_____________________________________________________________________________
2743 void AliMUONClusterFinderAZ::Simple()
2744 {
2745   // Process simple cluster (small number of pads) without EM-procedure
2746
2747   Int_t nForFit = 1, clustFit[1] = {0}, nfit;
2748   Double_t parOk[3] = {0.}; 
2749   TObjArray *clusters[1]; 
2750   clusters[0] = fPixArray;
2751   for (Int_t i = 0; i < fnPads[0]+fnPads[1]; i++) {
2752     if (fXyq[2][i] > fResponse->Saturation()-1) fPadIJ[1][i] = -9;
2753     else fPadIJ[1][i] = 1;
2754   }
2755   nfit = Fit(nForFit, clustFit, clusters, parOk);
2756 }
2757
2758 //_____________________________________________________________________________
2759 void AliMUONClusterFinderAZ::Errors(AliMUONRawCluster *clus)
2760 {
2761   // Correct reconstructed coordinates for some clusters and evaluate errors
2762
2763   Double_t qTot = clus->GetCharge(0), fmin = clus->GetChi2(0);
2764   Double_t xreco = clus->GetX(0), yreco = clus->GetY(0), zreco = clus->GetZ(0);
2765   Double_t sigmax[2] = {0};
2766
2767   Int_t nInX = 1, nInY, maxdig[2] ={-1, -1}, digit, cath1, isec;
2768   PadsInXandY(nInX, nInY);
2769
2770   // Find pad with maximum signal
2771   for (Int_t cath = 0; cath < 2; cath++) {
2772     for (Int_t j = 0; j < clus->GetMultiplicity(cath); j++) {
2773       cath1 = cath;
2774       digit = clus->GetIndex(j, cath);
2775       if (digit < 0) { cath1 = TMath::Even(cath); digit = -digit - 1; } // from the other cathode
2776
2777       if (clus->GetContrib(j,cath) > sigmax[cath1]) {
2778         sigmax[cath1] = clus->GetContrib(j,cath);
2779         maxdig[cath1] = digit;
2780       }
2781     }
2782   }
2783
2784   // Size of pad with maximum signal and reco coordinate distance from the pad center
2785   AliMUONDigit *mdig = 0;
2786   Double_t wx[2], wy[2], dxc[2], dyc[2];
2787   Float_t xpad, ypad, zpad;
2788   Int_t ix, iy;
2789   for (Int_t cath = 0; cath < 2; cath++) {
2790     if (maxdig[cath] < 0) continue;
2791     mdig = fInput->Digit(cath,maxdig[cath]);
2792     isec = fSegmentation[cath]->Sector(fInput->DetElemId(),mdig->PadX(), mdig->PadY());
2793     wx[cath] = fSegmentation[cath]->Dpx(fInput->DetElemId(),isec);
2794     wy[cath] = fSegmentation[cath]->Dpy(fInput->DetElemId(),isec);
2795     fSegmentation[cath]->GetPadI(fInput->DetElemId(),xreco, yreco, zreco, ix, iy);
2796     isec = fSegmentation[cath]->Sector(fInput->DetElemId(),ix,iy);
2797     if (isec > 0) {
2798       fSegmentation[cath]->GetPadC(fInput->DetElemId(), ix, iy, xpad, ypad, zpad);
2799       dxc[cath] = xreco - xpad;
2800       dyc[cath] = yreco - ypad;
2801     }
2802   }
2803
2804   // Check if pad with max charge at the edge (number of neughbours)
2805   Int_t nn, xList[10], yList[10], neighbx[2][2] = {{0,0}, {0,0}}, neighby[2][2]= {{0,0}, {0,0}};
2806   for (Int_t cath = 0; cath < 2; cath++) {
2807     if (maxdig[cath] < 0) continue;
2808     mdig = fInput->Digit(cath,maxdig[cath]);
2809     fSegmentation[cath]->Neighbours(fInput->DetElemId(),mdig->PadX(),mdig->PadY(),&nn,xList,yList); 
2810     isec = fSegmentation[cath]->Sector(fInput->DetElemId(),mdig->PadX(), mdig->PadY());
2811     //*??
2812     Float_t sprX = fResponse->SigmaIntegration() * fResponse->ChargeSpreadX();
2813     Float_t sprY = fResponse->SigmaIntegration() * fResponse->ChargeSpreadY();
2814     //fSegmentation[cath]->FirstPad(fInput->DetElemId(),muons[ihit][1], muons[ihit][2], muons[ihit][3], sprX, sprY);  
2815     fSegmentation[cath]->FirstPad(fInput->DetElemId(),xreco, yreco, zreco, sprX, sprY);  
2816     Int_t border = 0;
2817     if (fSegmentation[cath]->Sector(fInput->DetElemId(),fSegmentation[cath]->Ix(),fSegmentation[cath]->Iy()) <= 0) {
2818       fSegmentation[cath]->NextPad(fInput->DetElemId());
2819       border = 1;
2820     } 
2821     //*/
2822     for (Int_t j=0; j<nn; j++) {
2823       if (border && yList[j] < fSegmentation[cath]->Iy()) continue;
2824       fSegmentation[cath]->GetPadC (fInput->DetElemId(), xList[j], yList[j], xpad, ypad, zpad);
2825       //cout << ch << " " << xList[j] << " " << yList[j] << " " << border << " " << x << " " << y << " " << xpad << " " << ypad << endl;
2826       if (TMath::Abs(xpad) < 1 && TMath::Abs(ypad) < 1) continue;
2827       if (xList[j] == mdig->PadX()-1 || mdig->PadX() == 1 && 
2828           xList[j] == -1) neighbx[cath][0] = 1;
2829       else if (xList[j] == mdig->PadX()+1 || mdig->PadX() == -1 && 
2830                xList[j] == 1) neighbx[cath][1] = 1;
2831       if (yList[j] == mdig->PadY()-1 || mdig->PadY() == 1 &&
2832           yList[j] == -1) neighby[cath][0] = 1;
2833       else if (yList[j] == mdig->PadY()+1 || mdig->PadY() == -1 &&
2834                yList[j] == 1) neighby[cath][1] = 1;
2835     } // for (Int_t j=0; j<nn;
2836     if (neighbx[cath][0] && neighbx[cath][1]) neighbx[cath][0] = 0;
2837     else if (neighbx[cath][1]) neighbx[cath][0] = -1;
2838     else neighbx[cath][0] = 1;
2839     if (neighby[cath][0] && neighby[cath][1]) neighby[cath][0] = 0;
2840     else if (neighby[cath][1]) neighby[cath][0] = -1;
2841     else neighby[cath][0] = 1;
2842   }
2843
2844   Int_t iOver = clus->GetClusterType();
2845   // One-sided cluster
2846   if (!clus->GetMultiplicity(0)) {
2847     neighby[0][0] = neighby[1][0];
2848     wy[0] = wy[1];
2849     if (iOver < 99) iOver += 100 * iOver;
2850     dyc[0] = dyc[1];
2851   } else if (!clus->GetMultiplicity(1)) {
2852     neighbx[1][0] = neighbx[0][0];
2853     wx[1] = wx[0];
2854     if (iOver < 99) iOver += 100 * iOver;
2855     dxc[1] = dxc[0];
2856   }
2857
2858   // Apply corrections and evaluate errors
2859   Double_t errY, errX;
2860   Errors(nInY, nInX, neighby[0][0],neighbx[1][0], fmin, wy[0]*10, wx[1]*10, iOver, 
2861          dyc[0], dxc[1], qTot, yreco, xreco, errY, errX);
2862   errY = TMath::Max (errY, 0.01);
2863   //errY = 0.01;
2864   //errX = TMath::Max (errX, 0.144);
2865   clus->SetX(0, xreco); clus->SetY(0, yreco);
2866   clus->SetErrX(errX); clus->SetErrY(errY);
2867 }
2868
2869 //_____________________________________________________________________________
2870 void AliMUONClusterFinderAZ::Errors(Int_t ny, Int_t nx, Int_t iby, Int_t ibx, Double_t fmin,
2871                                     Double_t wy, Double_t wx, Int_t iover, 
2872                                     Double_t dyc, Double_t /*dxc*/, Double_t qtot, 
2873                                     Double_t &yrec, Double_t &xrec, Double_t &erry, Double_t &errx)
2874 {
2875   // Correct reconstructed coordinates for some clusters and evaluate errors
2876
2877     erry = 0.01;
2878     errx = 0.144;
2879     Int_t iovery = iover % 100;
2880     Double_t corr = 0;
2881
2882 /* ---> Ny = 1 */
2883     if (ny == 1) {
2884       if (iby != 0) {
2885         // edge effect 
2886         yrec += iby * (0.1823+0.2008)/2;
2887         erry = 0.04587;
2888       } else {
2889         // Find "effective pad width" 
2890         Double_t width = 0.218 / (1.31e-4 * TMath::Exp (2.688 * TMath::Log(qtot)) + 1) * 2;
2891         width = TMath::Min (width, 0.4);
2892         erry = width / TMath::Sqrt(12.);
2893         erry = TMath::Max (erry, 0.01293);
2894       }
2895       goto x; //return;
2896     }
2897
2898 /* ---> "Bad" fit */
2899     if (fmin > 0.4) {
2900       erry = 0.1556;
2901       if (ny == 5) erry = 0.06481;
2902       goto x; //return;
2903     }
2904
2905 /* ---> By != 0 */
2906     if (iby != 0) {
2907       if (ny > 2) {
2908         erry = 0.00417; //0.01010
2909       } else {
2910         // ny = 2 
2911         if (dyc * iby > -0.05) {
2912           Double_t dyc2 = dyc * dyc;
2913           if (iby < 0) {
2914             corr = 0.019 - 0.602 * dyc + 8.739 * dyc2 - 44.209 * dyc2 * dyc;
2915             corr = TMath::Min (corr, TMath::Abs(-0.25-dyc));
2916             yrec -= corr;
2917             //dyc -= corr;
2918             erry = 0.00814;
2919           } else {
2920             corr = 0.006 + 0.300 * dyc + 6.147 * dyc2 + 42.039 * dyc2 * dyc;
2921             corr = TMath::Min (corr, 0.25-dyc);
2922             yrec += corr;
2923             //dyc += corr;
2924             erry = 0.01582;
2925           }
2926         } else {
2927           erry = (0.00303 + 0.00296) / 2;
2928         }
2929       }
2930       goto x; //return;
2931     }
2932
2933 /* ---> Overflows */
2934     if (iovery != 0) {
2935       if (qtot < 3000) {
2936         erry = 0.0671;
2937       } else {
2938         if (iovery > 1) {
2939           erry = 0.09214;
2940         } else if (TMath::Abs(wy - 5) < 0.1) {
2941           erry = 0.061; //0.06622
2942         } else {
2943           erry = 0.00812; // 0.01073 
2944         }
2945       }
2946       goto x; //return;
2947     }
2948
2949 /* ---> "Good" but very high signal */
2950     if (qtot > 4000) {
2951       if (TMath::Abs(wy - 4) < 0.1) {
2952         erry = 0.00117;
2953       } else if (fmin < 0.03 && qtot < 6000) {
2954         erry = 0.01003;
2955       } else {
2956         erry = 0.1931;
2957       }
2958       goto x; //return;
2959     }
2960
2961 /* ---> "Good" clusters */
2962     if (ny > 3) {
2963       if (TMath::Abs(wy - 5) < 0.1) {
2964         erry = 0.0011; //0.00304 
2965       } else if (qtot < 400.) {
2966         erry = 0.0165;
2967       } else {
2968         erry = 0.00135; // 0.00358 
2969       }
2970     } else if (ny == 3) {
2971       if (TMath::Abs(wy - 4) < 0.1) {
2972         erry = 35.407 / (1 + TMath::Exp(5.511*TMath::Log(qtot/265.51))) + 11.564;
2973         //erry = 83.512 / (1 + TMath::Exp(3.344*TMath::Log(qtot/211.58))) + 12.260;
2974       } else {
2975         erry = 147.03 / (1 + TMath::Exp(1.713*TMath::Log(qtot/73.151))) + 9.575;
2976         //erry = 91.743 / (1 + TMath::Exp(2.332*TMath::Log(qtot/151.67))) + 11.453;
2977       }
2978       erry *= 1.e-4;
2979     } else {
2980       // ny = 2 
2981       if (TMath::Abs(wy - 4) < 0.1) {
2982         erry = 60.800 / (1 + TMath::Exp(3.305*TMath::Log(qtot/104.53))) + 11.702;
2983         //erry = 73.128 / (1 + TMath::Exp(5.676*TMath::Log(qtot/120.93))) + 17.839;
2984       } else {
2985         erry = 117.98 / (1 + TMath::Exp(2.005*TMath::Log(qtot/37.649))) + 21.431;
2986         //erry = 99.066 / (1 + TMath::Exp(4.900*TMath::Log(qtot/107.57))) + 25.315;
2987       }
2988       erry *= 1.e-4;
2989     }
2990     //return;
2991
2992  x:
2993 /* ---> X-coordinate */
2994 /* ---> Y-side */    
2995     if (wx > 11) { 
2996       errx = 0.0036;
2997       xrec -= 0.1385;
2998       return;
2999     }
3000 /* ---> Nx = 1 */
3001     if (nx == 1) {
3002       if (TMath::Abs(wx - 6) < 0.1) {
3003         if (qtot < 40) errx = 0.1693;
3004         else errx = 0.06241;
3005       } else if (TMath::Abs(wx - 7.5) < 0.1) {
3006         if (qtot < 40) errx = 0.2173;
3007         else errx = 0.07703;
3008       } else if (TMath::Abs(wx - 10) < 0.1) {
3009         if (ibx == 0) {
3010           if (qtot < 40) errx = 0.2316;
3011           else errx = 0.1426;
3012         } else {
3013           xrec += (0.2115 + 0.1942) / 2 * ibx;
3014           errx = 0.1921;
3015         }
3016       }
3017       return;
3018     }
3019 /* ---> "Bad" fit */
3020     if (fmin > 0.5) {
3021       errx = 0.1591;
3022       return;
3023     }
3024 /* ---> Bx != 0 */
3025     if (ibx != 0) {
3026       if (ibx > 0) { errx = 0.06761; xrec -= 0.03832; }
3027       else { errx = 0.06653; xrec += 0.02581; }
3028       return;
3029     }
3030 /* ---> Overflows */
3031     if (iover != 0) {
3032       if (TMath::Abs(wx - 6) < 0.1) errx = 0.06979;
3033       else if (TMath::Abs(wx - 7.5) < 0.1) errx = 0.1089;
3034       else if (TMath::Abs(wx - 10) < 0.1) errx = 0.09847;
3035       return;
3036     }
3037 /* ---> Good */
3038     if (TMath::Abs(wx - 6) < 0.1) errx = 0.06022;
3039     else if (TMath::Abs(wx - 7.5) < 0.1) errx = 0.07247;
3040     else if (TMath::Abs(wx - 10) < 0.1) errx = 0.07359;
3041 }
3042