]> git.uio.no Git - u/mrichter/AliRoot.git/blob - MUON/AliMUONClusterFinderPeakCOG.cxx
New LinkDef (cmake)
[u/mrichter/AliRoot.git] / MUON / AliMUONClusterFinderPeakCOG.cxx
1 /**************************************************************************
2  * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
3  *                                                                        *
4  * Author: The ALICE Off-line Project.                                    *
5  * Contributors are mentioned in the code where appropriate.              *
6  *                                                                        *
7  * Permission to use, copy, modify and distribute this software and its   *
8  * documentation strictly for non-commercial purposes is hereby granted   *
9  * without fee, provided that the above copyright notice appears in all   *
10  * copies and that both the copyright notice and this permission notice   *
11  * appear in the supporting documentation. The authors make no claims     *
12  * about the suitability of this software for any purpose. It is          *
13  * provided "as is" without express or implied warranty.                  *
14  **************************************************************************/
15
16 /* $Id$ */
17
18 //-----------------------------------------------------------------------------
19 /// \class AliMUONClusterFinderPeakCOG
20 /// 
21 /// Clusterizer class based on simple peak finder
22 ///
23 /// Pre-clustering is handled by AliMUONPreClusterFinder
24 /// From a precluster a pixel array is built, and its local maxima are used
25 /// to get pads and compute pad center of gravity.
26 ///
27 /// \author Laurent Aphecetche (for the "new" C++ structure) and 
28 /// Alexander Zinchenko, JINR Dubna, for the hardcore of it ;-)
29 //-----------------------------------------------------------------------------
30
31 #include "AliMUONClusterFinderPeakCOG.h"
32 #include "AliMUONCluster.h"
33 #include "AliMUONPad.h"
34
35 #include "AliMpPad.h"
36 #include "AliMpVSegmentation.h"
37 #include "AliMpEncodePair.h"
38
39 #include "AliLog.h"
40 #include "AliRunLoader.h"
41 //#include "AliCodeTimer.h"
42
43 #include <Riostream.h>
44 #include <TH2.h>
45 //#include <TCanvas.h>
46 #include <TMath.h>
47
48 /// \cond CLASSIMP
49 ClassImp(AliMUONClusterFinderPeakCOG)
50 /// \endcond
51  
52 const Double_t AliMUONClusterFinderPeakCOG::fgkZeroSuppression = 6; // average zero suppression value
53 //const Double_t AliMUONClusterFinderMLEM::fgkDistancePrecision = 1e-6; // (cm) used to check overlaps and so on
54 const Double_t AliMUONClusterFinderPeakCOG::fgkDistancePrecision = 1e-3; // (cm) used to check overlaps and so on
55 const TVector2 AliMUONClusterFinderPeakCOG::fgkIncreaseSize(-AliMUONClusterFinderPeakCOG::fgkDistancePrecision,-AliMUONClusterFinderPeakCOG::fgkDistancePrecision);
56 const TVector2 AliMUONClusterFinderPeakCOG::fgkDecreaseSize(AliMUONClusterFinderPeakCOG::fgkDistancePrecision,AliMUONClusterFinderPeakCOG::fgkDistancePrecision);
57
58 // Status flags for pads
59 const Int_t AliMUONClusterFinderPeakCOG::fgkZero = 0x0; ///< pad "basic" state
60 const Int_t AliMUONClusterFinderPeakCOG::fgkMustKeep = 0x1; ///< do not kill (for pixels)
61 const Int_t AliMUONClusterFinderPeakCOG::fgkUseForFit = 0x10; ///< should be used for fit
62 const Int_t AliMUONClusterFinderPeakCOG::fgkOver = 0x100; ///< processing is over
63 const Int_t AliMUONClusterFinderPeakCOG::fgkModified = 0x1000; ///< modified pad charge 
64 const Int_t AliMUONClusterFinderPeakCOG::fgkCoupled = 0x10000; ///< coupled pad  
65
66 //_____________________________________________________________________________
67 AliMUONClusterFinderPeakCOG::AliMUONClusterFinderPeakCOG(Bool_t plot, AliMUONVClusterFinder* clusterFinder)
68   : AliMUONVClusterFinder(),
69 fPreClusterFinder(clusterFinder),
70 fPreCluster(0x0),
71 fClusterList(),
72 fEventNumber(0),
73 fDetElemId(-1),
74 fClusterNumber(0),
75 fHistAnode(0x0),
76 fPixArray(new TObjArray(20)),
77 fDebug(0),
78 fPlot(plot),
79 fNClusters(0),
80 fNAddVirtualPads(0)
81 {
82   /// Constructor
83  
84   fkSegmentation[1] = fkSegmentation[0] = 0x0; 
85
86   if (fPlot) fDebug = 1;
87 }
88
89 //_____________________________________________________________________________
90 AliMUONClusterFinderPeakCOG::~AliMUONClusterFinderPeakCOG()
91 {
92 /// Destructor
93   delete fPixArray; fPixArray = 0;
94   delete fPreClusterFinder;
95   AliInfo(Form("Total clusters %d AddVirtualPad needed %d",
96                fNClusters,fNAddVirtualPads));
97 }
98
99 //_____________________________________________________________________________
100 Bool_t 
101 AliMUONClusterFinderPeakCOG::Prepare(Int_t detElemId, TClonesArray* pads[2],
102                                      const AliMpArea& area, const AliMpVSegmentation* seg[2])
103 {
104   /// Prepare for clustering
105 //  AliCodeTimerAuto("")
106   
107   for ( Int_t i = 0; i < 2; ++i )
108   {
109     fkSegmentation[i] = seg[i];
110   }
111   
112   // Find out the DetElemId
113   fDetElemId = detElemId;
114   
115   // find out current event number, and reset the cluster number
116   AliRunLoader *runLoader = AliRunLoader::Instance();
117   fEventNumber = runLoader ? runLoader->GetEventNumber() : 0;
118   fClusterNumber = -1;
119   fClusterList.Delete();
120   
121   AliDebug(3,Form("EVT %d DE %d",fEventNumber,fDetElemId));
122   
123   if ( fPreClusterFinder->NeedSegmentation() )
124   {
125     return fPreClusterFinder->Prepare(detElemId,pads,area,seg);
126   }
127   else
128   {
129     return fPreClusterFinder->Prepare(detElemId,pads,area);
130   }
131 }
132
133 //_____________________________________________________________________________
134 AliMUONCluster* 
135 AliMUONClusterFinderPeakCOG::NextCluster()
136 {
137   /// Return next cluster
138 //  AliCodeTimerAuto("")
139   
140   // if the list of clusters is not void, pick one from there
141   TObject* o = fClusterList.At(++fClusterNumber);
142   if ( o != 0x0 ) return static_cast<AliMUONCluster*>(o);
143   
144   //FIXME : at this point, must check whether we've used all the digits
145   //from precluster : if not, let the preclustering know about those unused
146   //digits, so it can reuse them
147   
148   // if the cluster list is exhausted, we need to go to the next
149   // pre-cluster and treat it
150
151   fPreCluster = fPreClusterFinder->NextCluster();
152   
153   if (!fPreCluster)
154   {
155     // we are done
156     return 0x0;
157   }
158     
159   fClusterList.Delete(); // reset the list of clusters for this pre-cluster
160   fClusterNumber = -1; 
161   
162   WorkOnPreCluster();
163
164   // WorkOnPreCluster may have used only part of the pads, so we check that
165   // now, and let the unused pads be reused by the preclustering...
166   
167   Int_t mult = fPreCluster->Multiplicity();
168   for ( Int_t i = 0; i < mult; ++i )
169   {
170     AliMUONPad* pad = fPreCluster->Pad(i);
171     if ( !pad->IsUsed() )
172     {
173       fPreClusterFinder->UsePad(*pad);
174     }
175   }
176   
177   return NextCluster();
178 }
179
180 //_____________________________________________________________________________
181 Bool_t
182 AliMUONClusterFinderPeakCOG::WorkOnPreCluster()
183 {
184   /// Starting from a precluster, builds a pixel array, and then
185   /// extract clusters from this array
186   
187   //  AliCodeTimerAuto("")      
188
189   if (fDebug) {
190     cout << " *** Event # " << fEventNumber 
191          << " det. elem.: " << fDetElemId << endl;
192     for (Int_t j = 0; j < fPreCluster->Multiplicity(); ++j) {
193       AliMUONPad* pad = fPreCluster->Pad(j);
194       printf(" bbb %3d %1d %8.4f %8.4f %8.4f %8.4f %6.1f %3d %3d %2d %1d %1d \n",
195              j, pad->Cathode(), pad->Coord(0), pad->Coord(1), pad->DX()*2, pad->DY()*2,
196              pad->Charge(), pad->Ix(), pad->Iy(), pad->Status(), pad->IsReal(), pad->IsSaturated());
197     }
198   }
199
200   AliMUONCluster* cluster = CheckPrecluster(*fPreCluster);
201   if (!cluster) return kFALSE;
202
203   BuildPixArray(*cluster);
204   
205   if ( fPixArray->GetLast() < 0 )
206   {
207     AliDebug(1,"No pixel for the above cluster");
208     delete cluster;
209     return kFALSE;
210   }
211   
212   Int_t nMax = 1, localMax[100], maxPos[100] = {0};
213   Double_t maxVal[100];
214   
215   nMax = FindLocalMaxima(fPixArray, localMax, maxVal); // find local maxima
216
217   if (nMax > 1) TMath::Sort(nMax, maxVal, maxPos, kTRUE); // in descending order
218   
219   for (Int_t i = 0; i < nMax; ++i) 
220   {
221     FindCluster(*cluster,localMax, maxPos[i]);
222   }
223
224   delete cluster;
225   if (fPlot == 0) {
226     delete fHistAnode;
227     fHistAnode = 0x0;
228   }
229   return kTRUE;
230 }
231
232 //_____________________________________________________________________________
233 Bool_t 
234 AliMUONClusterFinderPeakCOG::Overlap(const AliMUONPad& pad, const AliMUONPad& pixel)
235 {
236   /// Check if the pad and the pixel overlaps
237
238   // make a fake pad from the pixel
239   AliMUONPad tmp(pad.DetElemId(),pad.Cathode(),pad.Ix(),pad.Iy(),
240                  pixel.Coord(0),pixel.Coord(1),
241                  pixel.Size(0),pixel.Size(1),0);
242   
243   return AliMUONPad::AreOverlapping(pad,tmp,fgkDecreaseSize);
244 }
245
246 //_____________________________________________________________________________
247 AliMUONCluster* 
248 AliMUONClusterFinderPeakCOG::CheckPrecluster(const AliMUONCluster& origCluster)
249 {
250   /// Check precluster in order to attempt to simplify it (mostly for
251   /// two-cathode preclusters)
252     
253   //  AliCodeTimerAuto("")
254
255   // Disregard small clusters (leftovers from splitting or noise)
256   if ((origCluster.Multiplicity()==1 || origCluster.Multiplicity()==2) &&
257       origCluster.Charge(0)+origCluster.Charge(1) < 10) 
258   { 
259     return 0x0;
260   }
261
262   AliMUONCluster* cluster = new AliMUONCluster(origCluster);
263
264   AliDebug(2,"Start of CheckPreCluster=");
265   //StdoutToAliDebug(2,cluster->Print("full"));
266
267   AliMUONCluster* rv(0x0);
268   
269   if (cluster->Multiplicity(0) && cluster->Multiplicity(1))
270   { 
271     rv = CheckPreclusterTwoCathodes(cluster);
272   }
273   else
274   {
275     rv = cluster;
276   }
277   return rv;
278 }
279
280 //_____________________________________________________________________________
281 AliMUONCluster*
282 AliMUONClusterFinderPeakCOG::CheckPreclusterTwoCathodes(AliMUONCluster* cluster)
283 {
284   /// Check two-cathode cluster
285   
286   Int_t npad = cluster->Multiplicity();
287   Int_t* flags = new Int_t[npad];
288   for (Int_t j = 0; j < npad; ++j) flags[j] = 0;
289   
290   // Check pad overlaps
291   for ( Int_t i = 0; i < npad; ++i) 
292   {
293     AliMUONPad* padi = cluster->Pad(i);
294     if ( padi->Cathode() != 0 ) continue;
295     for (Int_t j = i+1; j < npad; ++j) 
296     {
297       AliMUONPad* padj = cluster->Pad(j);
298       if ( padj->Cathode() != 1 ) continue;
299       if ( !AliMUONPad::AreOverlapping(*padi,*padj,fgkDecreaseSize) ) continue;
300       flags[i] = flags[j] = 1; // mark overlapped pads
301     } 
302   } 
303   
304   // Check if all pads overlap
305   Int_t nFlags=0;
306   for (Int_t i = 0; i < npad; ++i) 
307   {
308     if (!flags[i]) ++nFlags;
309   }
310   
311   if (nFlags > 0) 
312   {
313     // not all pads overlap.
314     if (fDebug) cout << " nFlags: " << nFlags << endl;
315     TObjArray toBeRemoved;
316     for (Int_t i = 0; i < npad; ++i) 
317     {
318       AliMUONPad* pad = cluster->Pad(i);
319       if (flags[i]) continue;
320       Int_t cath = pad->Cathode();
321       Int_t cath1 = TMath::Even(cath);
322       // Check for edge effect (missing pads on the _other_ cathode)
323       AliMpPad mpPad = fkSegmentation[cath1]->PadByPosition(pad->Position(),kFALSE);
324       if (!mpPad.IsValid()) continue;
325       //if (nFlags == 1 && pad->Charge() < fgkZeroSuppression * 3) continue;
326       if (nFlags == 1 && pad->Charge() < 20) continue;
327       AliDebug(2,Form("Releasing the following pad : de,cath,ix,iy %d,%d,%d,%d charge %e",
328                       fDetElemId,pad->Cathode(),pad->Ix(),pad->Iy(),pad->Charge()));
329       toBeRemoved.AddLast(pad);
330       fPreCluster->Pad(i)->Release();
331     }
332     Int_t nRemove = toBeRemoved.GetEntriesFast();
333     for ( Int_t i = 0; i < nRemove; ++i )
334     {
335       cluster->RemovePad(static_cast<AliMUONPad*>(toBeRemoved.UncheckedAt(i)));
336     }
337   } 
338   
339   // Check correlations of cathode charges
340   if ( !cluster->IsSaturated() && cluster->ChargeAsymmetry() > 1 )
341   {
342     // big difference
343     Int_t cathode = cluster->MaxRawChargeCathode();
344     Int_t imin(-1);
345     Int_t imax(-1);
346     Double_t cmax(0);
347     Double_t cmin(1E9);
348     
349     // get min and max pad charges on the cathode opposite to the 
350     // max pad (given by MaxRawChargeCathode())
351     //
352     Int_t mult = cluster->Multiplicity();
353     for ( Int_t i = 0; i < mult; ++i )
354     {
355       AliMUONPad* pad = cluster->Pad(i);
356       if ( pad->Cathode() != cathode || !pad->IsReal() )
357       {
358         // only consider pads in the opposite cathode, and
359         // only consider real pads (i.e. exclude the virtual ones)
360         continue;
361       }
362       if ( pad->Charge() < cmin )
363       {
364         cmin = pad->Charge();
365         imin = i;
366         if (imax < 0) {
367           imax = imin;
368           cmax = cmin;
369         }
370       }
371       else if ( pad->Charge() > cmax )
372       {
373         cmax = pad->Charge();
374         imax = i;
375       }      
376     }
377     AliDebug(2,Form("Pad imin,imax %d,%d cmin,cmax %e,%e",
378                     imin,imax,cmin,cmax));
379     //
380     // arrange pads according to their distance to the max, normalized
381     // to the pad size
382     Double_t* dist = new Double_t[mult];
383     Double_t dxMin(1E9);
384     Double_t dyMin(1E9);
385     Double_t dmin(0);
386     
387     AliMUONPad* padmax = cluster->Pad(imax);
388     
389     for ( Int_t i = 0; i < mult; ++i )
390     {
391       dist[i] = 0.0;
392       if ( i == imax) continue;
393       AliMUONPad* pad = cluster->Pad(i);
394       if ( pad->Cathode() != cathode || !pad->IsReal() ) continue;
395       Double_t dx = (pad->X()-padmax->X())/padmax->DX()/2.0;
396       Double_t dy = (pad->Y()-padmax->Y())/padmax->DY()/2.0;
397       dist[i] = TMath::Sqrt(dx*dx+dy*dy);
398       if ( i == imin )
399       {
400         dmin = dist[i] + 1E-3; // distance to the pad with minimum charge
401         dxMin = dx;
402         dyMin = dy;
403       }      
404     }
405     
406     TMath::Sort(mult,dist,flags,kFALSE); // in ascending order
407     Double_t xmax(-1), distPrev(999);
408     TObjArray toBeRemoved;
409     
410     for ( Int_t i = 0; i < mult; ++i )
411     {
412       Int_t indx = flags[i];
413       AliMUONPad* pad = cluster->Pad(indx);
414       if ( pad->Cathode() != cathode || !pad->IsReal() ) continue;
415       if ( dist[indx] > dmin )
416       {
417         // farther than the minimum pad
418         Double_t dx = (pad->X()-padmax->X())/padmax->DX()/2.0;
419         Double_t dy = (pad->Y()-padmax->Y())/padmax->DY()/2.0;
420         dx *= dxMin;
421         dy *= dyMin;
422         if (dx >= 0 && dy >= 0) continue;
423         if (TMath::Abs(dx) > TMath::Abs(dy) && dx >= 0) continue;
424         if (TMath::Abs(dy) > TMath::Abs(dx) && dy >= 0) continue;        
425       }
426       if (dist[indx] > distPrev + 1) break; // overstepping empty pads
427       if ( pad->Charge() <= cmax || TMath::Abs(dist[indx]-xmax) < 1E-3 )
428       {
429         // release pad
430         if (TMath::Abs(dist[indx]-xmax) < 1.e-3) 
431         {
432           cmax = TMath::Max(pad->Charge(),cmax);
433         }
434         else
435         {
436           cmax = pad->Charge();
437         }
438         xmax = dist[indx];
439         distPrev = dist[indx];
440         AliDebug(2,Form("Releasing the following pad : de,cath,ix,iy %d,%d,%d,%d charge %e",
441                         fDetElemId,pad->Cathode(),pad->Ix(),pad->Iy(),
442                         pad->Charge()));
443   
444         toBeRemoved.AddLast(pad);
445         fPreCluster->Pad(indx)->Release();
446       }
447     }
448     Int_t nRemove = toBeRemoved.GetEntriesFast();
449     for ( Int_t i = 0; i < nRemove; ++i )
450     {
451       cluster->RemovePad(static_cast<AliMUONPad*>(toBeRemoved.UncheckedAt(i)));
452     }    
453     delete[] dist;
454   } // if ( !cluster->IsSaturated() && 
455   
456   delete[] flags;
457   
458   AliDebug(2,"End of CheckPreClusterTwoCathodes=");
459   //StdoutToAliDebug(2,cluster->Print("full"));
460
461   return cluster;    
462 }
463
464 //_____________________________________________________________________________
465 void
466 AliMUONClusterFinderPeakCOG::CheckOverlaps()
467 {
468   /// For debug only : check if some pixels overlap...
469   
470   Int_t nPix = fPixArray->GetLast()+1;
471   Int_t dummy(0);
472   
473   for ( Int_t i = 0; i < nPix; ++i )
474   {
475     AliMUONPad* pixelI = Pixel(i);
476     AliMUONPad pi(dummy,dummy,dummy,dummy,
477                   pixelI->Coord(0),pixelI->Coord(1),
478                   pixelI->Size(0),pixelI->Size(1),0.0);
479     
480     for ( Int_t j = i+1; j < nPix; ++j )
481     {
482       AliMUONPad* pixelJ = Pixel(j);
483       AliMUONPad pj(dummy,dummy,dummy,dummy,
484                     pixelJ->Coord(0),pixelJ->Coord(1),
485                     pixelJ->Size(0),pixelJ->Size(1),0.0);  
486       AliMpArea area;
487       
488       if ( AliMUONPad::AreOverlapping(pi,pj,fgkDecreaseSize,area) )
489       {
490         AliInfo(Form("The following 2 pixels (%d and %d) overlap !",i,j));
491         /*
492         StdoutToAliInfo(pixelI->Print();
493                         cout << " Surface = " << pixelI->Size(0)*pixelI->Size(1)*4 << endl;
494                         pixelJ->Print();
495                         cout << " Surface = " << pixelJ->Size(0)*pixelJ->Size(1)*4 << endl;
496                         cout << " Area surface = " << area.Dimensions().X()*area.Dimensions().Y()*4 << endl;
497                         cout << "-------" << endl;
498                         );
499         */        
500       }
501     }    
502   }
503 }
504
505 //_____________________________________________________________________________
506 void AliMUONClusterFinderPeakCOG::BuildPixArray(AliMUONCluster& cluster)
507 {
508   /// Build pixel array 
509   
510   Int_t npad = cluster.Multiplicity();
511   if (npad<=0) 
512   {
513     AliWarning("Got no pad at all ?!");
514   }
515   
516   fPixArray->Delete();
517   BuildPixArrayOneCathode(cluster);
518   
519 //  StdoutToAliDebug(2,cout << "End of BuildPixelArray:" << endl;
520 //                   fPixArray->Print(););
521   //CheckOverlaps();//FIXME : this is for debug only. Remove it.
522 }
523
524 //_____________________________________________________________________________
525 void AliMUONClusterFinderPeakCOG::BuildPixArrayOneCathode(AliMUONCluster& cluster)
526 {
527   /// Build the pixel array
528
529 //  AliDebug(2,Form("cluster.Multiplicity=%d",cluster.Multiplicity()));
530
531   TVector2 dim = cluster.MinPadDimensions (-1, kFALSE);
532   Double_t width[2] = {dim.X(), dim.Y()}, xy0[2];
533   Int_t found[2] = {0}, mult = cluster.Multiplicity();
534
535   for ( Int_t i = 0; i < mult; ++i) {
536     AliMUONPad* pad = cluster.Pad(i);
537     for (Int_t j = 0; j < 2; ++j) {
538       if (found[j] == 0 && TMath::Abs(pad->Size(j)-width[j]) < fgkDistancePrecision) { 
539         xy0[j] = pad->Coord(j);
540         found[j] = 1;
541       }
542     }
543     if (found[0] && found[1]) break;
544   }
545
546   Double_t min[2], max[2];
547   Int_t cath0 = 0, cath1 = 1;
548   if (cluster.Multiplicity(0) == 0) cath0 = 1;
549   else if (cluster.Multiplicity(1) == 0) cath1 = 0;
550
551   TVector2 leftDown = cluster.Area(cath0).LeftDownCorner();
552   TVector2 rightUp = cluster.Area(cath0).RightUpCorner();
553   min[0] = leftDown.X();
554   min[1] = leftDown.Y();
555   max[0] = rightUp.X();
556   max[1] = rightUp.Y();
557   if (cath1 != cath0) {
558     leftDown = cluster.Area(cath1).LeftDownCorner();
559     rightUp = cluster.Area(cath1).RightUpCorner();
560     min[0] = TMath::Max (min[0], leftDown.X());
561     min[1] = TMath::Max (min[1], leftDown.Y());
562     max[0] = TMath::Min (max[0], rightUp.X());
563     max[1] = TMath::Min (max[1], rightUp.Y());
564   }
565
566   // Adjust limits
567   //width[0] /= 2; width[1] /= 2; // just for check
568   Int_t nbins[2];
569   for (Int_t i = 0; i < 2; ++i) {
570     Double_t dist = (min[i] - xy0[i]) / width[i] / 2;
571     if (TMath::Abs(dist) < 1.e-6) dist = -1.e-6;
572     min[i] = xy0[i] + (TMath::Nint(dist-TMath::Sign(1.e-6,dist)) 
573                        + TMath::Sign(0.5,dist)) * width[i] * 2;
574     nbins[i] = TMath::Nint ((max[i] - min[i]) / width[i] / 2);
575     if (nbins[i] == 0) ++nbins[i];
576     max[i] = min[i] + nbins[i] * width[i] * 2;
577     //cout << dist << " " << min[i] << " " << max[i] << " " << nbins[i] << endl;
578   }
579
580   // Book histogram
581   TH2D *hist1 = new TH2D ("Grid", "", nbins[0], min[0], max[0], nbins[1], min[1], max[1]);
582   TH2D *hist2 = new TH2D ("Entries", "", nbins[0], min[0], max[0], nbins[1], min[1], max[1]);
583   TAxis *xaxis = hist1->GetXaxis();
584   TAxis *yaxis = hist1->GetYaxis();
585
586   // Fill histogram
587   for ( Int_t i = 0; i < mult; ++i) {
588     AliMUONPad* pad = cluster.Pad(i);
589     Int_t ix0 = xaxis->FindBin(pad->X());
590     Int_t iy0 = yaxis->FindBin(pad->Y());
591     PadOverHist(0, ix0, iy0, pad, hist1, hist2);
592   }
593
594   // Store pixels
595   for (Int_t i = 1; i <= nbins[0]; ++i) {
596     Double_t x = xaxis->GetBinCenter(i);
597     for (Int_t j = 1; j <= nbins[1]; ++j) {
598       if (hist2->GetCellContent(i,j) < 0.1) continue;
599       if (cath0 != cath1) {
600         // Two-sided cluster
601         Double_t cont = hist2->GetCellContent(i,j);
602         if (cont < 999.) continue;
603         if (cont-Int_t(cont/1000.)*1000. < 0.5) continue;
604       }
605       //if (hist2->GetCellContent(i,j) < 1.1 && cluster.Multiplicity(0) && 
606       //  cluster.Multiplicity(1)) continue;
607       Double_t y = yaxis->GetBinCenter(j);
608       Double_t charge = hist1->GetCellContent(i,j);
609       AliMUONPad* pixPtr = new AliMUONPad(x, y, width[0], width[1], charge);
610       fPixArray->Add(pixPtr);
611     }  
612   }
613   /*
614   if (fPixArray->GetEntriesFast() == 1) {
615     // Split pixel into 2
616     AliMUONPad* pixPtr = static_cast<AliMUONPad*> (fPixArray->UncheckedAt(0));
617     pixPtr->SetSize(0,width[0]/2.);
618     pixPtr->Shift(0,-width[0]/4.);
619     pixPtr = new AliMUONPad(pixPtr->X()+width[0], pixPtr->Y(), width[0]/2., width[1], pixPtr->Charge());
620     fPixArray->Add(pixPtr);
621   }
622   */
623   //fPixArray->Print();
624   delete hist1;
625   delete hist2;
626 }
627
628 //_____________________________________________________________________________
629 void AliMUONClusterFinderPeakCOG::PadOverHist(Int_t idir, Int_t ix0, Int_t iy0, AliMUONPad *pad,
630                                               TH2D *hist1, TH2D *hist2)
631 {
632   /// "Span" pad over histogram in the direction idir
633
634   TAxis *axis = idir == 0 ? hist1->GetXaxis() : hist1->GetYaxis();
635   Int_t nbins = axis->GetNbins(), cath = pad->Cathode();
636   Double_t bin = axis->GetBinWidth(1), amask = TMath::Power(1000.,cath*1.);
637
638   Int_t nbinPad = (Int_t)(pad->Size(idir)/bin*2+fgkDistancePrecision) + 1; // number of bins covered by pad
639
640   for (Int_t i = 0; i < nbinPad; ++i) {
641     Int_t ixy = idir == 0 ? ix0 + i : iy0 + i;
642     if (ixy > nbins) break;
643     Double_t lowEdge = axis->GetBinLowEdge(ixy);
644     if (lowEdge + fgkDistancePrecision > pad->Coord(idir) + pad->Size(idir)) break;
645     if (idir == 0) PadOverHist(1, ixy, iy0, pad, hist1, hist2); // span in the other direction
646     else {
647       // Fill histogram
648       Double_t cont = pad->Charge();
649       if (hist2->GetCellContent(ix0, ixy) > 0.1) 
650         cont = TMath::Min (hist1->GetCellContent(ix0, ixy), cont) 
651              + TMath::Min (TMath::Max(hist1->GetCellContent(ix0, ixy),cont)*0.1, 10.);
652       hist1->SetCellContent(ix0, ixy, cont);
653       hist2->SetCellContent(ix0, ixy, hist2->GetCellContent(ix0, ixy)+amask);
654     }
655   }
656
657   for (Int_t i = -1; i > -nbinPad; --i) {
658     Int_t ixy = idir == 0 ? ix0 + i : iy0 + i;
659     if (ixy < 1) break;
660     Double_t upEdge = axis->GetBinUpEdge(ixy);
661     if (upEdge - fgkDistancePrecision < pad->Coord(idir) - pad->Size(idir)) break;
662     if (idir == 0) PadOverHist(1, ixy, iy0, pad, hist1, hist2); // span in the other direction
663     else {
664       // Fill histogram
665       Double_t cont = pad->Charge();
666       if (hist2->GetCellContent(ix0, ixy) > 0.1) 
667         cont = TMath::Min (hist1->GetCellContent(ix0, ixy), cont)
668              + TMath::Min (TMath::Max(hist1->GetCellContent(ix0, ixy),cont)*0.1,10.);
669       hist1->SetCellContent(ix0, ixy, cont);
670       hist2->SetCellContent(ix0, ixy, hist2->GetCellContent(ix0, ixy)+amask);
671     }
672   }
673 }
674
675 //_____________________________________________________________________________
676 Int_t AliMUONClusterFinderPeakCOG::FindLocalMaxima(TObjArray *pixArray, Int_t *localMax, Double_t *maxVal)
677 {
678 /// Find local maxima in pixel space 
679
680   AliDebug(1,Form("nPix=%d",pixArray->GetLast()+1));
681
682   //TH2D *hist = NULL;
683   //delete ((TH2D*) gROOT->FindObject("anode"));
684   //if (pixArray == fPixArray) hist = (TH2D*) gROOT->FindObject("anode");
685   //else { hist = (TH2D*) gROOT->FindObject("anode1"); cout << hist << endl; }
686   //if (hist) hist->Delete();
687   delete fHistAnode;
688  
689   Double_t xylim[4] = {999, 999, 999, 999};
690
691   Int_t nPix = pixArray->GetEntriesFast();
692   AliMUONPad *pixPtr = 0;
693   for (Int_t ipix = 0; ipix < nPix; ++ipix) {
694     pixPtr = (AliMUONPad*) pixArray->UncheckedAt(ipix);
695     for (Int_t i = 0; i < 4; ++i) 
696          xylim[i] = TMath::Min (xylim[i], (i%2 ? -1 : 1)*pixPtr->Coord(i/2));
697   }
698   for (Int_t i = 0; i < 4; ++i) xylim[i] -= pixPtr->Size(i/2); 
699
700   Int_t nx = TMath::Nint ((-xylim[1]-xylim[0])/pixPtr->Size(0)/2);
701   Int_t ny = TMath::Nint ((-xylim[3]-xylim[2])/pixPtr->Size(1)/2);
702   if (pixArray == fPixArray) fHistAnode = new TH2D("anode","anode",nx,xylim[0],-xylim[1],ny,xylim[2],-xylim[3]);
703   else fHistAnode = new TH2D("anode1","anode1",nx,xylim[0],-xylim[1],ny,xylim[2],-xylim[3]);
704   for (Int_t ipix = 0; ipix < nPix; ++ipix) {
705     pixPtr = (AliMUONPad*) pixArray->UncheckedAt(ipix);
706     fHistAnode->Fill(pixPtr->Coord(0), pixPtr->Coord(1), pixPtr->Charge());
707   }
708 //  if (fDraw && pixArray == fPixArray) fDraw->DrawHist("c2", hist);
709
710   Int_t nMax = 0, indx, nxy = ny * nx;
711   Int_t *isLocalMax = new Int_t[nxy];
712   for (Int_t i = 0; i < nxy; ++i) isLocalMax[i] = 0; 
713
714   for (Int_t i = 1; i <= ny; ++i) {
715     indx = (i-1) * nx;
716     for (Int_t j = 1; j <= nx; ++j) {
717       if (fHistAnode->GetCellContent(j,i) < 0.5) continue;
718       //if (isLocalMax[indx+j-1] < 0) continue;
719       if (isLocalMax[indx+j-1] != 0) continue;
720       FlagLocalMax(fHistAnode, i, j, isLocalMax);
721     }
722   }
723
724   for (Int_t i = 1; i <= ny; ++i) {
725     indx = (i-1) * nx;
726     for (Int_t j = 1; j <= nx; ++j) {
727       if (isLocalMax[indx+j-1] > 0) { 
728         localMax[nMax] = indx + j - 1; 
729         maxVal[nMax++] = fHistAnode->GetCellContent(j,i);
730         if (nMax > 99) break;
731       }
732     }
733     if (nMax > 99) {
734       AliError(" Too many local maxima !!!");
735       break;
736     }
737   }
738   if (fDebug) cout << " Local max: " << nMax << endl;
739   delete [] isLocalMax; 
740   return nMax;
741 }
742
743 //_____________________________________________________________________________
744 void AliMUONClusterFinderPeakCOG::FlagLocalMax(TH2D *hist, Int_t i, Int_t j, Int_t *isLocalMax)
745 {
746 /// Flag pixels (whether or not local maxima)
747
748   Int_t nx = hist->GetNbinsX();
749   Int_t ny = hist->GetNbinsY();
750   Int_t cont = TMath::Nint (hist->GetCellContent(j,i));
751   Int_t cont1 = 0, indx = (i-1)*nx+j-1, indx1 = 0, indx2 = 0;
752
753   Int_t ie = i + 2, je = j + 2;
754   for (Int_t i1 = i-1; i1 < ie; ++i1) {
755     if (i1 < 1 || i1 > ny) continue;
756     indx1 = (i1 - 1) * nx;
757     for (Int_t j1 = j-1; j1 < je; ++j1) {
758       if (j1 < 1 || j1 > nx) continue;
759       if (i == i1 && j == j1) continue;
760       indx2 = indx1 + j1 - 1;
761       cont1 = TMath::Nint (hist->GetCellContent(j1,i1));
762       if (cont < cont1) { isLocalMax[indx] = -1; return; }
763       else if (cont > cont1) isLocalMax[indx2] = -1;
764       else { // the same charge
765         isLocalMax[indx] = 1; 
766         if (isLocalMax[indx2] == 0) {
767           FlagLocalMax(hist, i1, j1, isLocalMax);
768           if (isLocalMax[indx2] < 0) { isLocalMax[indx] = -1; return; }
769           else isLocalMax[indx2] = -1;
770         }
771       } 
772     }
773   }
774   isLocalMax[indx] = 1; // local maximum
775 }
776
777 //_____________________________________________________________________________
778 void AliMUONClusterFinderPeakCOG::FindCluster(AliMUONCluster& cluster, 
779                                               const Int_t *localMax, Int_t iMax)
780 {
781 /// Find pixel cluster around local maximum \a iMax and pick up pads
782 /// overlapping with it
783
784   //TH2D *hist = (TH2D*) gROOT->FindObject("anode");
785   /* Just for check
786   TCanvas* c = new TCanvas("Anode","Anode",800,600);
787   c->cd();
788   hist->Draw("lego1Fb"); // debug
789   c->Update();
790   Int_t tmp;
791   cin >> tmp;
792   */
793   Int_t nx = fHistAnode->GetNbinsX();
794   //Int_t ny = hist->GetNbinsY();
795   Int_t ic = localMax[iMax] / nx + 1;
796   Int_t jc = localMax[iMax] % nx + 1;
797
798   // Get min pad dimensions for the precluster
799   Int_t nSides = 2;
800   if (cluster.Multiplicity(0) == 0 || cluster.Multiplicity(1) == 0) nSides = 1;
801   TVector2 dim0 = cluster.MinPadDimensions(0, -1, kFALSE);
802   TVector2 dim1 = cluster.MinPadDimensions(1, -1, kFALSE);
803   //Double_t width[2][2] = {{dim0.X(), dim0.Y()},{dim1.X(),dim1.Y()}};
804   Int_t nonb[2] = {1, 0}; // coordinate index vs cathode
805   if (nSides == 1 || dim0.X() < dim1.X() - fgkDistancePrecision) {
806     nonb[0] = 0;
807     nonb[1] = 1;
808   }
809   Bool_t samex = kFALSE, samey = kFALSE;
810   if (TMath::Abs(dim0.X()-dim1.X()) < fgkDistancePrecision) samex = kTRUE; // the same X pad size on both planes 
811   if (TMath::Abs(dim0.Y()-dim1.Y()) < fgkDistancePrecision) samey = kTRUE; // the same Y pad size on both planes 
812
813   // Drop all pixels from the array - pick up only the ones from the cluster
814   //fPixArray->Delete();
815
816   Double_t wx = fHistAnode->GetXaxis()->GetBinWidth(1)/2; 
817   Double_t wy = fHistAnode->GetYaxis()->GetBinWidth(1)/2;  
818   Double_t yc = fHistAnode->GetYaxis()->GetBinCenter(ic);
819   Double_t xc = fHistAnode->GetXaxis()->GetBinCenter(jc);
820   Double_t cont = fHistAnode->GetCellContent(jc,ic);
821   AliMUONPad* pixPtr = new AliMUONPad (xc, yc, wx, wy, cont);
822   if (fDebug) pixPtr->Print("full"); 
823
824   Int_t npad = cluster.Multiplicity();
825   
826   // Pick up pads which overlap with the maximum pixel and find pads with the max signal
827   Double_t qMax[2] = {0}; 
828   AliMUONPad *matrix[2][3] = {{0x0,0x0,0x0},{0x0,0x0,0x0}};
829   for (Int_t j = 0; j < npad; ++j) 
830   {
831     AliMUONPad* pad = cluster.Pad(j);
832     if ( Overlap(*pad,*pixPtr) )
833     {
834       if (fDebug) { cout << j << " "; pad->Print("full"); }
835       if (pad->Charge() > qMax[pad->Cathode()]) {
836         qMax[pad->Cathode()] = pad->Charge();
837         matrix[pad->Cathode()][1] = pad;
838         if (nSides == 1) matrix[!pad->Cathode()][1] = pad;
839       }
840     }
841   }
842   //if (nSides == 2 && (matrix[0][1] == 0x0 || matrix[1][1] == 0x0)) return; // ???
843
844   // Find neighbours of maxima to have 3 pads per direction (if possible)
845   for (Int_t j = 0; j < npad; ++j) 
846   {
847     AliMUONPad* pad = cluster.Pad(j);
848     Int_t cath = pad->Cathode();
849     if (pad == matrix[cath][1]) continue;
850     Int_t nLoops = 3 - nSides;
851
852     for (Int_t k = 0; k < nLoops; ++k) {
853       Int_t cath1 = cath;
854       if (k) cath1 = !cath;
855
856       // Check the coordinate corresponding to the cathode (bending or non-bending case)
857       Double_t dist = pad->Coord(nonb[cath1]) - matrix[cath][1]->Coord(nonb[cath1]);
858       Double_t dir = TMath::Sign (1., dist);
859       dist = TMath::Abs(dist) - pad->Size(nonb[cath1]) - matrix[cath][1]->Size(nonb[cath1]);
860
861       if (TMath::Abs(dist) < fgkDistancePrecision) {
862         // Check the other coordinate
863         dist = pad->Coord(!nonb[cath1]) - matrix[cath1][1]->Coord(!nonb[cath1]);
864         if (TMath::Abs(dist) > 
865             TMath::Max(pad->Size(!nonb[cath1]), matrix[cath1][1]->Size(!nonb[cath1])) - fgkDistancePrecision) break;
866         Int_t idir = TMath::Nint (dir);
867         if (matrix[cath1][1+idir] == 0x0) matrix[cath1][1+idir] = pad;
868         else if (pad->Charge() > matrix[cath1][1+idir]->Charge()) matrix[cath1][1+idir] = pad; // diff. segmentation
869         //cout << pad->Coord(nonb[cath1]) << " " << pad->Coord(!nonb[cath1]) << " " << pad->Size(nonb[cath1]) << " " << pad->Size(!nonb[cath1]) << " " << pad->Charge() << endl ;
870         break;
871       }
872     }
873   }
874
875   Double_t coord[2] = {0.}, qAver = 0.;
876   for (Int_t i = 0; i < 2; ++i) {
877     Double_t q = 0.;
878     Double_t coordQ = 0.;
879     Int_t cath = matrix[i][1]->Cathode();
880     if (i && nSides == 1) cath = !cath;
881     for (Int_t j = 0; j < 3; ++j) {
882       if (matrix[i][j] == 0x0) continue;
883       Double_t dq = matrix[i][j]->Charge();
884       q += dq;
885       coordQ += dq * matrix[i][j]->Coord(nonb[cath]);
886       //coordQ += (matrix[i][j]->Charge() * matrix[i][j]->Coord(nonb[cath]));
887     }
888     coord[cath] = coordQ / q;
889     qAver = TMath::Max (qAver, q);
890   }
891
892   //qAver = TMath::Sqrt(qAver);
893   if ( qAver >= 14 )
894   {
895     
896     AliMUONCluster* cluster1 = new AliMUONCluster(cluster);
897       
898     cluster1->SetCharge(qAver,qAver);
899     if (nonb[0] == 1) 
900       cluster1->SetPosition(TVector2(coord[1],coord[0]),TVector2(0.,0.));
901     else 
902       cluster1->SetPosition(TVector2(coord[0],coord[1]),TVector2(0.,0.));
903
904     cluster1->SetChi2(0.);
905       
906     // FIXME: we miss some information in this cluster, as compared to 
907     // the original AddRawCluster code.
908       
909     AliDebug(2,Form("Adding RawCluster detElemId %4d mult %2d charge %5d (xl,yl)=(%9.6g,%9.6g)",
910                     fDetElemId,cluster1->Multiplicity(),(Int_t)cluster1->Charge(),
911                     cluster1->Position().X(),cluster1->Position().Y()));
912         
913     fClusterList.Add(cluster1);
914   }
915 }
916
917 //_____________________________________________________________________________
918 AliMUONClusterFinderPeakCOG&  
919 AliMUONClusterFinderPeakCOG::operator=(const AliMUONClusterFinderPeakCOG& rhs)
920 {
921 /// Protected assignement operator
922
923   if (this == &rhs) return *this;
924
925   AliFatal("Not implemented.");
926     
927   return *this;  
928 }    
929
930 //_____________________________________________________________________________
931 void AliMUONClusterFinderPeakCOG::PadsInXandY(AliMUONCluster& cluster,
932                                            Int_t &nInX, Int_t &nInY) const
933 {
934   /// Find number of pads in X and Y-directions (excluding virtual ones and
935   /// overflows)
936
937   //Int_t statusToTest = 1;
938   Int_t statusToTest = fgkUseForFit;
939   
940   //if ( nInX < 0 ) statusToTest = 0;
941   if ( nInX < 0 ) statusToTest = fgkZero;
942        
943   Bool_t mustMatch(kTRUE);
944
945   Long_t cn = cluster.NofPads(statusToTest,mustMatch);
946   
947   nInX = AliMp::PairFirst(cn);
948   nInY = AliMp::PairSecond(cn);
949 }
950
951 //_____________________________________________________________________________
952 void AliMUONClusterFinderPeakCOG::RemovePixel(Int_t i)
953 {
954   /// Remove pixel at index i
955   AliMUONPad* pixPtr = Pixel(i);
956   fPixArray->RemoveAt(i); 
957   delete pixPtr;
958 }
959
960 //_____________________________________________________________________________
961 AliMUONPad* 
962 AliMUONClusterFinderPeakCOG::Pixel(Int_t i) const
963 {
964   /// Returns pixel at index i
965   return static_cast<AliMUONPad*>(fPixArray->UncheckedAt(i));
966 }
967
968 //_____________________________________________________________________________
969 void 
970 AliMUONClusterFinderPeakCOG::Print(Option_t* what) const
971 {
972   /// printout
973   TString swhat(what);
974   swhat.ToLower();
975   if ( swhat.Contains("precluster") )
976   {
977     if ( fPreCluster) fPreCluster->Print();
978   }
979 }
980
981