ce3272d643daf0258fad175620b3ce950d493381
[u/mrichter/AliRoot.git] / ITS / AliITSClusterFinderSDD.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 //  Cluster finder 
20 //  for Silicon
21 //  Drift Detector
22 //
23 #include <Riostream.h>
24
25 #include <TMath.h>
26 #include <math.h>
27
28 #include "AliITSClusterFinderSDD.h"
29 #include "AliITSMapA1.h"
30 #include "AliITS.h"
31 #include "AliITSdigit.h"
32 #include "AliITSRawCluster.h"
33 #include "AliITSRecPoint.h"
34 #include "AliITSsegmentation.h"
35 #include "AliITSresponseSDD.h"
36 #include "AliRun.h"
37
38 ClassImp(AliITSClusterFinderSDD)
39
40 //______________________________________________________________________
41 AliITSClusterFinderSDD::AliITSClusterFinderSDD(AliITSsegmentation *seg,
42                                                AliITSresponse *response,
43                                                TClonesArray *digits,
44                                                TClonesArray *recp){
45     // standard constructor
46
47     fSegmentation = seg;
48     fResponse     = response;
49     fDigits       = digits;
50     fClusters     = recp;
51     fNclusters    = fClusters->GetEntriesFast();
52     SetCutAmplitude();
53     SetDAnode();
54     SetDTime();
55     SetMinPeak((Int_t)(((AliITSresponseSDD*)fResponse)->GetNoiseAfterElectronics()*5));
56     //    SetMinPeak();
57     SetMinNCells();
58     SetMaxNCells();
59     SetTimeCorr();
60     SetMinCharge();
61     fMap = new AliITSMapA1(fSegmentation,fDigits,fCutAmplitude);
62 }
63 //______________________________________________________________________
64 AliITSClusterFinderSDD::AliITSClusterFinderSDD(){
65     // default constructor
66
67     fSegmentation = 0;
68     fResponse     = 0;
69     fDigits       = 0;
70     fClusters     = 0;
71     fNclusters    = 0;
72     fMap          = 0;
73     fCutAmplitude = 0;
74     fDAnode = 0;
75     fDTime = 0;
76     fMinPeak = 0;
77     fMinNCells = 0;
78     fMaxNCells = 0;
79     fTimeCorr = 0;
80     fMinCharge = 0;
81     /*
82     SetDAnode();
83     SetDTime();
84     SetMinPeak((Int_t)(((AliITSresponseSDD*)fResponse)->GetNoiseAfterElectronics()*5));
85     SetMinNCells();
86     SetMaxNCells();
87     SetTimeCorr();
88     SetMinCharge();
89     */
90 }
91 //____________________________________________________________________________
92 AliITSClusterFinderSDD::~AliITSClusterFinderSDD(){
93     // destructor
94
95     if(fMap) delete fMap;
96 }
97 //______________________________________________________________________
98 void AliITSClusterFinderSDD::SetCutAmplitude(Float_t nsigma){
99     // set the signal threshold for cluster finder
100     Float_t baseline,noise,noiseAfterEl;
101
102     fResponse->GetNoiseParam(noise,baseline);
103     noiseAfterEl = ((AliITSresponseSDD*)fResponse)->GetNoiseAfterElectronics();
104     fCutAmplitude = (Int_t)((baseline + nsigma*noiseAfterEl));
105 }
106 //______________________________________________________________________
107 void AliITSClusterFinderSDD::Find1DClusters(){
108     // find 1D clusters
109     static AliITS *iTS = (AliITS*)gAlice->GetModule("ITS");
110   
111     // retrieve the parameters 
112     Int_t fNofMaps       = fSegmentation->Npz();
113     Int_t fMaxNofSamples = fSegmentation->Npx();
114     Int_t fNofAnodes     = fNofMaps/2;
115     Int_t dummy          = 0;
116     Float_t fTimeStep    = fSegmentation->Dpx(dummy);
117     Float_t fSddLength   = fSegmentation->Dx();
118     Float_t fDriftSpeed  = fResponse->DriftSpeed();  
119     Float_t anodePitch   = fSegmentation->Dpz(dummy);
120
121     // map the signal
122     fMap->ClearMap();
123     fMap->SetThreshold(fCutAmplitude);
124     fMap->FillMap();
125   
126     Float_t noise;
127     Float_t baseline;
128     fResponse->GetNoiseParam(noise,baseline);
129   
130     Int_t nofFoundClusters = 0;
131     Int_t i;
132     Float_t **dfadc = new Float_t*[fNofAnodes];
133     for(i=0;i<fNofAnodes;i++) dfadc[i] = new Float_t[fMaxNofSamples];
134     Float_t fadc  = 0.;
135     Float_t fadc1 = 0.;
136     Float_t fadc2 = 0.;
137     Int_t j,k,idx,l,m;
138     for(j=0;j<2;j++) {
139         for(k=0;k<fNofAnodes;k++) {
140             idx = j*fNofAnodes+k;
141             // signal (fadc) & derivative (dfadc)
142             dfadc[k][255]=0.;
143             for(l=0; l<fMaxNofSamples; l++) {
144                 fadc2=(Float_t)fMap->GetSignal(idx,l);
145                 if(l>0) fadc1=(Float_t)fMap->GetSignal(idx,l-1);
146                 if(l>0) dfadc[k][l-1] = fadc2-fadc1;
147             } // samples
148         } // anodes
149
150         for(k=0;k<fNofAnodes;k++) {
151         //cout << "Anode: " << k+1 << ", Wing: " << j+1 << endl;
152             idx = j*fNofAnodes+k;
153             Int_t imax  = 0;
154             Int_t imaxd = 0;
155             Int_t it    = 0;
156             while(it <= fMaxNofSamples-3) {
157                 imax  = it;
158                 imaxd = it;
159                 // maximum of signal          
160                 Float_t fadcmax  = 0.;
161                 Float_t dfadcmax = 0.;
162                 Int_t lthrmina   = 1;
163                 Int_t lthrmint   = 3;
164                 Int_t lthra      = 1;
165                 Int_t lthrt      = 0;
166                 for(m=0;m<20;m++) {
167                     Int_t id = it+m;
168                     if(id>=fMaxNofSamples) break;
169                     fadc=(float)fMap->GetSignal(idx,id);
170                     if(fadc > fadcmax) { fadcmax = fadc; imax = id;}
171                     if(fadc > (float)fCutAmplitude) { 
172                         lthrt++; 
173                     } // end if
174                     if(dfadc[k][id] > dfadcmax) {
175                         dfadcmax = dfadc[k][id];
176                         imaxd    = id;
177                     } // end if
178                 } // end for m
179                 it = imaxd;
180                 if(fMap->TestHit(idx,imax) == kEmpty) {it++; continue;}
181                 // cluster charge
182                 Int_t tstart = it-2;
183                 if(tstart < 0) tstart = 0;
184                 Bool_t ilcl = 0;
185                 if(lthrt >= lthrmint && lthra >= lthrmina) ilcl = 1;
186                 if(ilcl) {
187                     nofFoundClusters++;
188                     Int_t tstop      = tstart;
189                     Float_t dfadcmin = 10000.;
190                     Int_t ij;
191                     for(ij=0; ij<20; ij++) {
192                         if(tstart+ij > 255) { tstop = 255; break; }
193                         fadc=(float)fMap->GetSignal(idx,tstart+ij);
194                         if((dfadc[k][tstart+ij] < dfadcmin) && 
195                            (fadc > fCutAmplitude)) {
196                             tstop = tstart+ij+5;
197                             if(tstop > 255) tstop = 255;
198                             dfadcmin = dfadc[k][it+ij];
199                         } // end if
200                     } // end for ij
201
202                     Float_t clusterCharge = 0.;
203                     Float_t clusterAnode  = k+0.5;
204                     Float_t clusterTime   = 0.;
205                     Int_t   clusterMult   = 0;
206                     Float_t clusterPeakAmplitude = 0.;
207                     Int_t its,peakpos     = -1;
208                     Float_t n, baseline;
209                     fResponse->GetNoiseParam(n,baseline);
210                     for(its=tstart; its<=tstop; its++) {
211                         fadc=(float)fMap->GetSignal(idx,its);
212                         if(fadc>baseline) fadc -= baseline;
213                         else fadc = 0.;
214                         clusterCharge += fadc;
215                         // as a matter of fact we should take the peak
216                         // pos before FFT
217                         // to get the list of tracks !!!
218                         if(fadc > clusterPeakAmplitude) {
219                             clusterPeakAmplitude = fadc;
220                             //peakpos=fMap->GetHitIndex(idx,its);
221                             Int_t shift = (int)(fTimeCorr/fTimeStep);
222                             if(its>shift && its<(fMaxNofSamples-shift))
223                                 peakpos  = fMap->GetHitIndex(idx,its+shift);
224                             else peakpos = fMap->GetHitIndex(idx,its);
225                             if(peakpos<0) peakpos =fMap->GetHitIndex(idx,its);
226                         } // end if
227                         clusterTime += fadc*its;
228                         if(fadc > 0) clusterMult++;
229                         if(its == tstop) {
230                             clusterTime /= (clusterCharge/fTimeStep);   // ns
231                             if(clusterTime>fTimeCorr) clusterTime -=fTimeCorr;
232                             //ns
233                         } // end if
234                     } // end for its
235
236                     Float_t clusteranodePath = (clusterAnode - fNofAnodes/2)*
237                                                anodePitch;
238                     Float_t clusterDriftPath = clusterTime*fDriftSpeed;
239                     clusterDriftPath = fSddLength-clusterDriftPath;
240                     if(clusterCharge <= 0.) break;
241                     AliITSRawClusterSDD clust(j+1,//i
242                                               clusterAnode,clusterTime,//ff
243                                               clusterCharge, //f
244                                               clusterPeakAmplitude, //f
245                                               peakpos, //i
246                                               0.,0.,clusterDriftPath,//fff
247                                               clusteranodePath, //f
248                                               clusterMult, //i
249                                               0,0,0,0,0,0,0);//7*i
250                     iTS->AddCluster(1,&clust);
251                     it = tstop;
252                 } // ilcl
253                 it++;
254             } // while (samples)
255         } // anodes
256     } // detectors (2)
257
258     for(i=0;i<fNofAnodes;i++) delete[] dfadc[i];
259     delete [] dfadc;
260
261     return;
262 }
263
264
265
266 //______________________________________________________________________
267 void AliITSClusterFinderSDD::Find1DClustersE(){
268     // find 1D clusters
269     static AliITS *iTS=(AliITS*)gAlice->GetModule("ITS");
270     // retrieve the parameters 
271     Int_t fNofMaps = fSegmentation->Npz();
272     Int_t fMaxNofSamples = fSegmentation->Npx();
273     Int_t fNofAnodes = fNofMaps/2;
274     Int_t dummy=0;
275     Float_t fTimeStep = fSegmentation->Dpx( dummy );
276     Float_t fSddLength = fSegmentation->Dx();
277     Float_t fDriftSpeed = fResponse->DriftSpeed();
278     Float_t anodePitch = fSegmentation->Dpz( dummy );
279     Float_t n, baseline;
280     fResponse->GetNoiseParam( n, baseline );
281     // map the signal
282     fMap->ClearMap();
283     fMap->SetThreshold( fCutAmplitude );
284     fMap->FillMap();
285     
286     Int_t nClu = 0;
287     //        cout << "Search  cluster... "<< endl;
288     for( Int_t j=0; j<2; j++ ){
289         for( Int_t k=0; k<fNofAnodes; k++ ){
290             Int_t idx = j*fNofAnodes+k;
291             Bool_t on = kFALSE;
292             Int_t start = 0;
293             Int_t nTsteps = 0;
294             Float_t fmax = 0.;
295             Int_t lmax = 0;
296             Float_t charge = 0.;
297             Float_t time = 0.;
298             Float_t anode = k+0.5;
299             Int_t peakpos = -1;
300             for( Int_t l=0; l<fMaxNofSamples; l++ ){
301                 Float_t fadc = (Float_t)fMap->GetSignal( idx, l );
302                 if( fadc > 0.0 ){
303                     if( on == kFALSE && l<fMaxNofSamples-4){
304                         // star RawCluster (reset var.)
305                         Float_t fadc1 = (Float_t)fMap->GetSignal( idx, l+1 );
306                         if( fadc1 < fadc ) continue;
307                         start = l;
308                         fmax = 0.;
309                         lmax = 0;
310                         time = 0.;
311                         charge = 0.; 
312                         on = kTRUE; 
313                         nTsteps = 0;
314                     } // end if on...
315                     nTsteps++ ;
316                     if( fadc > baseline ) fadc -= baseline;
317                     else fadc=0.;
318                     charge += fadc;
319                     time += fadc*l;
320                     if( fadc > fmax ){ 
321                         fmax = fadc; 
322                         lmax = l; 
323                         Int_t shift = (Int_t)(fTimeCorr/fTimeStep + 0.5);
324                         if( l > shift && l < (fMaxNofSamples-shift) )  
325                             peakpos = fMap->GetHitIndex( idx, l+shift );
326                         else
327                             peakpos = fMap->GetHitIndex( idx, l );
328                         if( peakpos < 0) peakpos = fMap->GetHitIndex( idx, l );
329                     } // end if fadc
330                 }else{ // end fadc>0
331                     if( on == kTRUE ){        
332                         if( nTsteps > 2 ){
333                             //  min # of timesteps for a RawCluster
334                             // Found a RawCluster...
335                             Int_t stop = l-1;
336                             time /= (charge/fTimeStep);   // ns
337                                 // time = lmax*fTimeStep;   // ns
338                             if( time > fTimeCorr ) time -= fTimeCorr;   // ns
339                             Float_t anodePath = (anode - fNofAnodes/2)*anodePitch;
340                             Float_t driftPath = time*fDriftSpeed;
341                             driftPath = fSddLength-driftPath;
342                             AliITSRawClusterSDD clust(j+1,anode,time,charge,
343                                                       fmax, peakpos,0.,0.,
344                                                       driftPath,anodePath,
345                                                       nTsteps,start,stop,
346                                                       start, stop, 1, k, k );
347                             iTS->AddCluster( 1, &clust );
348                             //        clust.PrintInfo();
349                             nClu++;
350                         } // end if nTsteps
351                         on = kFALSE;
352                     } // end if on==kTRUE
353                 } // end if fadc>0
354             } // samples
355         } // anodes
356     } // wings
357     //        cout << "# Rawclusters " << nClu << endl;         
358     return; 
359 }
360 //_______________________________________________________________________
361 Int_t AliITSClusterFinderSDD::SearchPeak(Float_t *spect,Int_t xdim,Int_t zdim,
362                                          Int_t *peakX, Int_t *peakZ, 
363                                          Float_t *peakAmp, Float_t minpeak ){
364     // search peaks on a 2D cluster
365     Int_t npeak = 0;    // # peaks
366     Int_t i,j;
367     // search peaks
368     for( Int_t z=1; z<zdim-1; z++ ){
369         for( Int_t x=1; x<xdim-2; x++ ){
370             Float_t sxz = spect[x*zdim+z];
371             Float_t sxz1 = spect[(x+1)*zdim+z];
372             Float_t sxz2 = spect[(x-1)*zdim+z];
373             // search a local max. in s[x,z]
374             if( sxz < minpeak || sxz1 <= 0 || sxz2 <= 0 ) continue;
375             if( sxz >= spect[(x+1)*zdim+z  ] && sxz >= spect[(x-1)*zdim+z  ] &&
376                 sxz >= spect[x*zdim    +z+1] && sxz >= spect[x*zdim    +z-1] &&
377                 sxz >= spect[(x+1)*zdim+z+1] && sxz >= spect[(x+1)*zdim+z-1] &&
378                 sxz >= spect[(x-1)*zdim+z+1] && sxz >= spect[(x-1)*zdim+z-1] ){
379                 // peak found
380                 peakX[npeak] = x;
381                 peakZ[npeak] = z;
382                 peakAmp[npeak] = sxz;
383                 npeak++;
384             } // end if ....
385         } // end for x
386     } // end for z
387     // search groups of peaks with same amplitude.
388     Int_t *flag = new Int_t[npeak];
389     for( i=0; i<npeak; i++ ) flag[i] = 0;
390     for( i=0; i<npeak; i++ ){
391         for( j=0; j<npeak; j++ ){
392             if( i==j) continue;
393             if( flag[j] > 0 ) continue;
394             if( peakAmp[i] == peakAmp[j] && 
395                 TMath::Abs(peakX[i]-peakX[j])<=1 && 
396                 TMath::Abs(peakZ[i]-peakZ[j])<=1 ){
397                 if( flag[i] == 0) flag[i] = i+1;
398                 flag[j] = flag[i];
399             } // end if ...
400         } // end for j
401     } // end for i
402     // make average of peak groups        
403     for( i=0; i<npeak; i++ ){
404         Int_t nFlag = 1;
405         if( flag[i] <= 0 ) continue;
406         for( j=0; j<npeak; j++ ){
407             if( i==j ) continue;
408             if( flag[j] != flag[i] ) continue;
409             peakX[i] += peakX[j];
410             peakZ[i] += peakZ[j];
411             nFlag++;
412             npeak--;
413             for( Int_t k=j; k<npeak; k++ ){
414                 peakX[k] = peakX[k+1];
415                 peakZ[k] = peakZ[k+1];
416                 peakAmp[k] = peakAmp[k+1];
417                 flag[k] = flag[k+1];
418             } // end for k        
419             j--;
420         } // end for j
421         if( nFlag > 1 ){
422             peakX[i] /= nFlag;
423             peakZ[i] /= nFlag;
424         } // end fi nFlag
425     } // end for i
426     delete [] flag;
427     return( npeak );
428 }
429 //______________________________________________________________________
430 void AliITSClusterFinderSDD::PeakFunc( Int_t xdim, Int_t zdim, Float_t *par,
431                                        Float_t *spe, Float_t *integral){
432     // function used to fit the clusters
433     // par -> parameters..
434     // par[0]  number of peaks.
435     // for each peak i=1, ..., par[0]
436     //                 par[i] = Ampl.
437     //                 par[i+1] = xpos
438     //                 par[i+2] = zpos
439     //                 par[i+3] = tau
440     //                 par[i+4] = sigma.
441     Int_t electronics = fResponse->Electronics(); // 1 = PASCAL, 2 = OLA
442     const Int_t knParam = 5;
443     Int_t npeak = (Int_t)par[0];
444
445     memset( spe, 0, sizeof( Float_t )*zdim*xdim );
446
447     Int_t k = 1;
448     for( Int_t i=0; i<npeak; i++ ){
449         if( integral != 0 ) integral[i] = 0.;
450         Float_t sigmaA2 = par[k+4]*par[k+4]*2.;
451         Float_t t2 = par[k+3];   // PASCAL
452         if( electronics == 2 ) { t2 *= t2; t2 *= 2; } // OLA
453         for( Int_t z=0; z<zdim; z++ ){
454             for( Int_t x=0; x<xdim; x++ ){
455                 Float_t z2 = (z-par[k+2])*(z-par[k+2])/sigmaA2;
456                 Float_t x2 = 0.;
457                 Float_t signal = 0.;
458                 if( electronics == 1 ){ // PASCAL
459                     x2 = (x-par[k+1]+t2)/t2;
460                     signal = (x2>0.) ? par[k]*x2*exp(-x2+1.-z2) :0.0; // RCCR2
461                 //  signal =(x2>0.) ? par[k]*x2*x2*exp(-2*x2+2.-z2 ):0.0;//RCCR
462                 }else if( electronics == 2 ) { // OLA
463                     x2 = (x-par[k+1])*(x-par[k+1])/t2;
464                     signal = par[k]  * exp( -x2 - z2 );
465                 } else {
466                   Warning("PeakFunc","Wrong SDD Electronics = %d",electronics);
467                     // exit( 1 );
468                 } // end if electronicx
469                 spe[x*zdim+z] += signal;
470                 if( integral != 0 ) integral[i] += signal;
471             } // end for x
472         } // end for z
473         k += knParam;
474     } // end for i
475     return;
476 }
477 //__________________________________________________________________________
478 Float_t AliITSClusterFinderSDD::ChiSqr( Int_t xdim, Int_t zdim, Float_t *spe,
479                                         Float_t *speFit ) const{
480     // EVALUATES UNNORMALIZED CHI-SQUARED
481     Float_t chi2 = 0.;
482     for( Int_t z=0; z<zdim; z++ ){
483         for( Int_t x=1; x<xdim-1; x++ ){
484             Int_t index = x*zdim+z;
485             Float_t tmp = spe[index] - speFit[index];
486             chi2 += tmp*tmp;
487         } // end for x
488     } // end for z
489     return( chi2 );
490 }
491 //_______________________________________________________________________
492 void AliITSClusterFinderSDD::Minim( Int_t xdim, Int_t zdim, Float_t *param,
493                                     Float_t *prm0,Float_t *steprm,
494                                     Float_t *chisqr,Float_t *spe,
495                                     Float_t *speFit ){
496     // 
497     Int_t   k, nnn, mmm, i;
498     Float_t p1, delta, d1, chisq1, p2, chisq2, t, p3, chisq3, a, b, p0, chisqt;
499     const Int_t knParam = 5;
500     Int_t npeak = (Int_t)param[0];
501     for( k=1; k<(npeak*knParam+1); k++ ) prm0[k] = param[k];
502     for( k=1; k<(npeak*knParam+1); k++ ){
503         p1 = param[k];
504         delta = steprm[k];
505         d1 = delta;
506         // ENSURE THAT STEP SIZE IS SENSIBLY LARGER THAN MACHINE ROUND OFF
507         if( fabs( p1 ) > 1.0E-6 ) 
508             if ( fabs( delta/p1 ) < 1.0E-4 ) delta = p1/1000;
509             else  delta = (Float_t)1.0E-4;
510         //  EVALUATE CHI-SQUARED AT FIRST TWO SEARCH POINTS
511         PeakFunc( xdim, zdim, param, speFit );
512         chisq1 = ChiSqr( xdim, zdim, spe, speFit );
513         p2 = p1+delta;
514         param[k] = p2;
515         PeakFunc( xdim, zdim, param, speFit );
516         chisq2 = ChiSqr( xdim, zdim, spe, speFit );
517         if( chisq1 < chisq2 ){
518             // REVERSE DIRECTION OF SEARCH IF CHI-SQUARED IS INCREASING
519             delta = -delta;
520             t = p1;
521             p1 = p2;
522             p2 = t;
523             t = chisq1;
524             chisq1 = chisq2;
525             chisq2 = t;
526         } // end if
527         i = 1; nnn = 0;
528         do {   // INCREMENT param(K) UNTIL CHI-SQUARED STARTS TO INCREASE
529             nnn++;
530             p3 = p2 + delta;
531             mmm = nnn - (nnn/5)*5;  // multiplo de 5
532             if( mmm == 0 ){
533                 d1 = delta;
534                 // INCREASE STEP SIZE IF STEPPING TOWARDS MINIMUM IS TOO SLOW 
535                 delta *= 5;
536             } // end if
537             param[k] = p3;
538             // Constrain paramiters
539             Int_t kpos = (k-1) % knParam;
540             switch( kpos ){
541             case 0 :
542                 if( param[k] <= 20 ) param[k] = fMinPeak;
543                 break;
544             case 1 :
545                 if( fabs( param[k] - prm0[k] ) > 1.5 ) param[k] = prm0[k];
546                 break;
547             case 2 :
548                 if( fabs( param[k] - prm0[k] ) > 1. ) param[k] = prm0[k];
549                 break;
550             case 3 :
551                 if( param[k] < .5 ) param[k] = .5;        
552                 break;
553             case 4 :
554                 if( param[k] < .288 ) param[k] = .288;        // 1/sqrt(12) = 0.288
555                 if( param[k] > zdim*.5 ) param[k] = zdim*.5;
556                 break;
557             }; // end switch
558             PeakFunc( xdim, zdim, param, speFit );
559             chisq3 = ChiSqr( xdim, zdim, spe, speFit );
560             if( chisq3 < chisq2 && nnn < 50 ){
561                 p1 = p2;
562                 p2 = p3;
563                 chisq1 = chisq2;
564                 chisq2 = chisq3;
565             }else i=0;
566         } while( i );
567         // FIND MINIMUM OF PARABOLA DEFINED BY LAST THREE POINTS
568         a = chisq1*(p2-p3)+chisq2*(p3-p1)+chisq3*(p1-p2);
569         b = chisq1*(p2*p2-p3*p3)+chisq2*(p3*p3-p1*p1)+chisq3*(p1*p1-p2*p2);
570         if( a!=0 ) p0 = (Float_t)(0.5*b/a);
571         else p0 = 10000;
572         //--IN CASE OF NEARLY EQUAL CHI-SQUARED AND TOO SMALL STEP SIZE PREVENT
573         //   ERRONEOUS EVALUATION OF PARABOLA MINIMUM
574         //---NEXT TWO LINES CAN BE OMITTED FOR HIGHER PRECISION MACHINES
575         //dp = (Float_t) max (fabs(p3-p2), fabs(p2-p1));
576         //if( fabs( p2-p0 ) > dp ) p0 = p2;
577         param[k] = p0;
578         // Constrain paramiters
579         Int_t kpos = (k-1) % knParam;
580         switch( kpos ){
581         case 0 :
582             if( param[k] <= 20 ) param[k] = fMinPeak;   
583             break;
584         case 1 :
585             if( fabs( param[k] - prm0[k] ) > 1.5 ) param[k] = prm0[k];
586             break;
587         case 2 :
588             if( fabs( param[k] - prm0[k] ) > 1. ) param[k] = prm0[k];
589             break;
590         case 3 :
591             if( param[k] < .5 ) param[k] = .5;        
592             break;
593         case 4 :
594             if( param[k] < .288 ) param[k] = .288;  // 1/sqrt(12) = 0.288
595             if( param[k] > zdim*.5 ) param[k] = zdim*.5;
596             break;
597         }; // end switch
598         PeakFunc( xdim, zdim, param, speFit );
599         chisqt = ChiSqr( xdim, zdim, spe, speFit );
600         // DO NOT ALLOW ERRONEOUS INTERPOLATION
601         if( chisqt <= *chisqr ) *chisqr = chisqt;
602         else param[k] = prm0[k];
603         // OPTIMIZE SEARCH STEP FOR EVENTUAL NEXT CALL OF MINIM
604         steprm[k] = (param[k]-prm0[k])/5;
605         if( steprm[k] >= d1 ) steprm[k] = d1/5;
606     } // end for k
607     // EVALUATE FIT AND CHI-SQUARED FOR OPTIMIZED PARAMETERS
608     PeakFunc( xdim, zdim, param, speFit );
609     *chisqr = ChiSqr( xdim, zdim, spe, speFit );
610     return;
611 }
612 //_________________________________________________________________________
613 Int_t AliITSClusterFinderSDD::NoLinearFit( Int_t xdim, Int_t zdim, 
614                                            Float_t *param, Float_t *spe, 
615                                            Int_t *niter, Float_t *chir ){
616     // fit method from Comput. Phys. Commun 46(1987) 149
617     const Float_t kchilmt = 0.01;  //        relative accuracy           
618     const Int_t   knel = 3;        //        for parabolic minimization  
619     const Int_t   knstop = 50;     //        Max. iteration number          
620     const Int_t   knParam = 5;
621     Int_t npeak = (Int_t)param[0];
622     // RETURN IF NUMBER OF DEGREES OF FREEDOM IS NOT POSITIVE 
623     if( (xdim*zdim - npeak*knParam) <= 0 ) return( -1 );
624     Float_t degFree = (xdim*zdim - npeak*knParam)-1;
625     Int_t   n, k, iterNum = 0;
626     Float_t *prm0 = new Float_t[npeak*knParam+1];
627     Float_t *step = new Float_t[npeak*knParam+1];
628     Float_t *schi = new Float_t[npeak*knParam+1]; 
629     Float_t *sprm[3];
630     sprm[0] = new Float_t[npeak*knParam+1];
631     sprm[1] = new Float_t[npeak*knParam+1];
632     sprm[2] = new Float_t[npeak*knParam+1];
633     Float_t  chi0, chi1, reldif, a, b, prmin, dp;
634     Float_t *speFit = new Float_t[ xdim*zdim ];
635     PeakFunc( xdim, zdim, param, speFit );
636     chi0 = ChiSqr( xdim, zdim, spe, speFit );
637     chi1 = chi0;
638     for( k=1; k<(npeak*knParam+1); k++) prm0[k] = param[k];
639         for( k=1 ; k<(npeak*knParam+1); k+=knParam ){
640             step[k] = param[k] / 20.0 ;
641             step[k+1] = param[k+1] / 50.0;
642             step[k+2] = param[k+2] / 50.0;                 
643             step[k+3] = param[k+3] / 20.0;                 
644             step[k+4] = param[k+4] / 20.0;                 
645         } // end for k
646     Int_t out = 0;
647     do{
648         iterNum++;
649             chi0 = chi1;
650             Minim( xdim, zdim, param, prm0, step, &chi1, spe, speFit );
651             reldif = ( chi1 > 0 ) ? ((Float_t) fabs( chi1-chi0)/chi1 ) : 0;
652         // EXIT conditions
653         if( reldif < (float) kchilmt ){
654             *chir  = (chi1>0) ? (float) TMath::Sqrt (chi1/degFree) :0;
655             *niter = iterNum;
656             out = 0;
657             break;
658         } // end if
659         if( (reldif < (float)(5*kchilmt)) && (iterNum > knstop) ){
660             *chir = (chi1>0) ?(float) TMath::Sqrt (chi1/degFree):0;
661             *niter = iterNum;
662             out = 0;
663             break;
664         } // end if
665         if( iterNum > 5*knstop ){
666             *chir  = (chi1>0) ?(float) TMath::Sqrt (chi1/degFree):0;
667             *niter = iterNum;
668             out = 1;
669             break;
670         } // end if
671         if( iterNum <= knel ) continue;
672         n = iterNum - (iterNum/knel)*knel; // EXTRAPOLATION LIMIT COUNTER N
673         if( n > 3 || n == 0 ) continue;
674         schi[n-1] = chi1;
675         for( k=1; k<(npeak*knParam+1); k++ ) sprm[n-1][k] = param[k];
676         if( n != 3 ) continue;
677         // -EVALUATE EXTRAPOLATED VALUE OF EACH PARAMETER BY FINDING MINIMUM OF
678         //    PARABOLA DEFINED BY LAST THREE CALLS OF MINIM
679         for( k=1; k<(npeak*knParam+1); k++ ){
680             Float_t tmp0 = sprm[0][k];
681             Float_t tmp1 = sprm[1][k];
682             Float_t tmp2 = sprm[2][k];
683             a  = schi[0]*(tmp1-tmp2) + schi[1]*(tmp2-tmp0);
684             a += (schi[2]*(tmp0-tmp1));
685             b  = schi[0]*(tmp1*tmp1-tmp2*tmp2);
686             b += (schi[1]*(tmp2*tmp2-tmp0*tmp0)+(schi[2]*
687                                              (tmp0*tmp0-tmp1*tmp1)));
688             if ((double)a < 1.0E-6) prmin = 0;
689             else prmin = (float) (0.5*b/a);
690             dp = 5*(tmp2-tmp0);
691             if( fabs(prmin-tmp2) > fabs(dp) ) prmin = tmp2+dp;
692             param[k] = prmin;
693             step[k]  = dp/10; // OPTIMIZE SEARCH STEP
694         } // end for k
695     } while( kTRUE );
696     delete [] prm0;
697     delete [] step;
698     delete [] schi; 
699     delete [] sprm[0];
700     delete [] sprm[1];
701     delete [] sprm[2];
702     delete [] speFit;
703     return( out );
704 }
705
706 //______________________________________________________________________
707 void AliITSClusterFinderSDD::ResolveClustersE(){
708     // The function to resolve clusters if the clusters overlapping exists
709     Int_t i;
710     static AliITS *iTS = (AliITS*)gAlice->GetModule( "ITS" );
711     // get number of clusters for this module
712     Int_t nofClusters = fClusters->GetEntriesFast();
713     nofClusters -= fNclusters;
714     Int_t fNofMaps = fSegmentation->Npz();
715     Int_t fNofAnodes = fNofMaps/2;
716     Int_t fMaxNofSamples = fSegmentation->Npx();
717     Int_t dummy=0;
718     Double_t fTimeStep = fSegmentation->Dpx( dummy );
719     Double_t fSddLength = fSegmentation->Dx();
720     Double_t fDriftSpeed = fResponse->DriftSpeed();
721     Double_t anodePitch = fSegmentation->Dpz( dummy );
722     Float_t n, baseline;
723     fResponse->GetNoiseParam( n, baseline );
724     Int_t electronics = fResponse->Electronics(); // 1 = PASCAL, 2 = OLA
725
726     for( Int_t j=0; j<nofClusters; j++ ){ 
727         // get cluster information
728         AliITSRawClusterSDD *clusterJ=(AliITSRawClusterSDD*) fClusters->At(j);
729         Int_t astart = clusterJ->Astart();
730         Int_t astop = clusterJ->Astop();
731         Int_t tstart = clusterJ->Tstartf();
732         Int_t tstop = clusterJ->Tstopf();
733         Int_t wing = (Int_t)clusterJ->W();
734         if( wing == 2 ){
735             astart += fNofAnodes; 
736             astop  += fNofAnodes;
737         } // end if 
738         Int_t xdim = tstop-tstart+3;
739         Int_t zdim = astop-astart+3;
740         if(xdim > 50 || zdim > 30) { 
741           Warning("ResolveClustersE","xdim: %d , zdim: %d ",xdim,zdim);
742           continue;
743         }
744         Float_t *sp = new Float_t[ xdim*zdim+1 ];
745         memset( sp, 0, sizeof(Float_t)*(xdim*zdim+1) );
746         
747         // make a local map from cluster region
748         for( Int_t ianode=astart; ianode<=astop; ianode++ ){
749             for( Int_t itime=tstart; itime<=tstop; itime++ ){
750                 Float_t fadc = fMap->GetSignal( ianode, itime );
751                 if( fadc > baseline ) fadc -= (Double_t)baseline;
752                 else fadc = 0.;
753                 Int_t index = (itime-tstart+1)*zdim+(ianode-astart+1);
754                 sp[index] = fadc;
755             } // time loop
756         } // anode loop
757         
758         // search peaks on cluster
759         const Int_t kNp = 150;
760         Int_t peakX1[kNp];
761         Int_t peakZ1[kNp];
762         Float_t peakAmp1[kNp];
763         Int_t npeak = SearchPeak(sp,xdim,zdim,peakX1,peakZ1,peakAmp1,fMinPeak);
764
765         // if multiple peaks, split cluster
766         if( npeak >= 1 )
767         {
768             //        cout << "npeak " << npeak << endl;
769             //        clusterJ->PrintInfo();
770             Float_t *par = new Float_t[npeak*5+1];
771             par[0] = (Float_t)npeak;                
772             // Initial parameters in cell dimentions
773             Int_t k1 = 1;
774             for( i=0; i<npeak; i++ ){
775                 par[k1] = peakAmp1[i];
776                 par[k1+1] = peakX1[i]; // local time pos. [timebin]
777                 par[k1+2] = peakZ1[i]; // local anode pos. [anodepitch]
778                 if( electronics == 1 ) 
779                     par[k1+3] = 2.; // PASCAL
780                 else if( electronics == 2 ) 
781                     par[k1+3] = 0.7; // tau [timebin]  OLA 
782                 par[k1+4] = .4;    // sigma        [anodepich]
783                 k1+=5;
784             } // end for i                        
785             Int_t niter;
786             Float_t chir;                        
787             NoLinearFit( xdim, zdim, par, sp, &niter, &chir );
788             Float_t peakX[kNp];
789             Float_t peakZ[kNp];
790             Float_t sigma[kNp];
791             Float_t tau[kNp];
792             Float_t peakAmp[kNp];
793             Float_t integral[kNp];
794             //get integrals => charge for each peak
795             PeakFunc( xdim, zdim, par, sp, integral );
796             k1 = 1;
797             for( i=0; i<npeak; i++ ){
798                 peakAmp[i] = par[k1];
799                 peakX[i] = par[k1+1];
800                 peakZ[i] = par[k1+2];
801                 tau[i] = par[k1+3];
802                 sigma[i] = par[k1+4];
803                 k1+=5;
804             } // end for i
805             // calculate parameter for new clusters
806             for( i=0; i<npeak; i++ ){
807                 AliITSRawClusterSDD clusterI( *clusterJ );
808                 Int_t newAnode = peakZ1[i]-1 + astart;
809                 Int_t newiTime = peakX1[i]-1 + tstart;
810                 Int_t shift = (Int_t)(fTimeCorr/fTimeStep + 0.5);
811                 if( newiTime > shift && newiTime < (fMaxNofSamples-shift) ) 
812                     shift = 0;
813                 Int_t peakpos = fMap->GetHitIndex( newAnode, newiTime+shift );
814                 clusterI.SetPeakPos( peakpos );
815                 clusterI.SetPeakAmpl( peakAmp1[i] );
816                 Float_t newAnodef = peakZ[i] - 0.5 + astart;
817                 Float_t newiTimef = peakX[i] - 1 + tstart;
818                 if( wing == 2 ) newAnodef -= fNofAnodes; 
819                 Float_t anodePath = (newAnodef - fNofAnodes/2)*anodePitch;
820                 newiTimef *= fTimeStep;
821                 if( newiTimef > fTimeCorr ) newiTimef -= fTimeCorr;
822                 if( electronics == 1 ){
823                 //    newiTimef *= 0.999438;    // PASCAL
824                 //    newiTimef += (6./fDriftSpeed - newiTimef/3000.);
825                 }else if( electronics == 2 )
826                     newiTimef *= 0.99714;    // OLA
827                 Float_t driftPath = fSddLength - newiTimef * fDriftSpeed;
828                 Float_t sign = ( wing == 1 ) ? -1. : 1.;
829                 clusterI.SetX( driftPath*sign * 0.0001 );        
830                 clusterI.SetZ( anodePath * 0.0001 );
831                 clusterI.SetAnode( newAnodef );
832                 clusterI.SetTime( newiTimef );
833                 clusterI.SetAsigma( sigma[i]*anodePitch );
834                 clusterI.SetTsigma( tau[i]*fTimeStep );
835                 clusterI.SetQ( integral[i] );
836                 //    clusterI.PrintInfo();
837                 iTS->AddCluster( 1, &clusterI );
838             } // end for i
839             fClusters->RemoveAt( j );
840             delete [] par;
841         } else {  // something odd
842           Warning("ResolveClustersE","--- Peak not found!!!!  minpeak=%d ,cluster peak= %f , module= %d",fMinPeak,clusterJ->PeakAmpl(),fModule); 
843           clusterJ->PrintInfo();
844           Warning("ResolveClustersE"," xdim= %d zdim= %d",xdim-2,zdim-2);
845         }
846         delete [] sp;
847     } // cluster loop
848     fClusters->Compress();
849 //    fMap->ClearMap(); 
850 }
851
852
853 //________________________________________________________________________
854 void  AliITSClusterFinderSDD::GroupClusters(){
855     // group clusters
856     Int_t dummy=0;
857     Float_t fTimeStep = fSegmentation->Dpx(dummy);
858     // get number of clusters for this module
859     Int_t nofClusters = fClusters->GetEntriesFast();
860     nofClusters -= fNclusters;
861     AliITSRawClusterSDD *clusterI;
862     AliITSRawClusterSDD *clusterJ;
863     Int_t *label = new Int_t [nofClusters];
864     Int_t i,j;
865     for(i=0; i<nofClusters; i++) label[i] = 0;
866     for(i=0; i<nofClusters; i++) { 
867         if(label[i] != 0) continue;
868         for(j=i+1; j<nofClusters; j++) { 
869             if(label[j] != 0) continue;
870             clusterI = (AliITSRawClusterSDD*) fClusters->At(i);
871             clusterJ = (AliITSRawClusterSDD*) fClusters->At(j);
872             // 1.3 good
873             if(clusterI->T() < fTimeStep*60) fDAnode = 4.2;  // TB 3.2  
874             if(clusterI->T() < fTimeStep*10) fDAnode = 1.5;  // TB 1.
875             Bool_t pair = clusterI->Brother(clusterJ,fDAnode,fDTime);
876             if(!pair) continue;
877             //      clusterI->PrintInfo();
878             //      clusterJ->PrintInfo();
879             clusterI->Add(clusterJ);
880             label[j] = 1;
881             fClusters->RemoveAt(j);
882             j=i; // <- Ernesto
883         } // J clusters  
884         label[i] = 1;
885     } // I clusters
886     fClusters->Compress();
887
888     delete [] label;
889     return;
890 }
891 //________________________________________________________________________
892 void AliITSClusterFinderSDD::SelectClusters(){
893     // get number of clusters for this module
894     Int_t nofClusters = fClusters->GetEntriesFast();
895
896     nofClusters -= fNclusters;
897     Int_t i;
898     for(i=0; i<nofClusters; i++) { 
899         AliITSRawClusterSDD *clusterI =(AliITSRawClusterSDD*) fClusters->At(i);
900         Int_t rmflg = 0;
901         Float_t wy = 0.;
902         if(clusterI->Anodes() != 0.) {
903             wy = ((Float_t) clusterI->Samples())/clusterI->Anodes();
904         } // end if
905         Int_t amp = (Int_t) clusterI->PeakAmpl();
906         Int_t cha = (Int_t) clusterI->Q();
907         if(amp < fMinPeak) rmflg = 1;  
908         if(cha < fMinCharge) rmflg = 1;
909         if(wy < fMinNCells) rmflg = 1;
910         //if(wy > fMaxNCells) rmflg = 1;
911         if(rmflg) fClusters->RemoveAt(i);
912     } // I clusters
913     fClusters->Compress();
914     return;
915 }
916 //__________________________________________________________________________
917 void AliITSClusterFinderSDD::ResolveClusters(){
918     // The function to resolve clusters if the clusters overlapping exists
919 /*    AliITS *iTS=(AliITS*)gAlice->GetModule("ITS");
920     // get number of clusters for this module
921     Int_t nofClusters = fClusters->GetEntriesFast();
922     nofClusters -= fNclusters;
923     //cout<<"Resolve Cl: nofClusters, fNclusters ="<<nofClusters<<","
924     // <<fNclusters<<endl;
925     Int_t fNofMaps = fSegmentation->Npz();
926     Int_t fNofAnodes = fNofMaps/2;
927     Int_t dummy=0;
928     Double_t fTimeStep = fSegmentation->Dpx(dummy);
929     Double_t fSddLength = fSegmentation->Dx();
930     Double_t fDriftSpeed = fResponse->DriftSpeed();
931     Double_t anodePitch = fSegmentation->Dpz(dummy);
932     Float_t n, baseline;
933     fResponse->GetNoiseParam(n,baseline);
934     Float_t dzz_1A = anodePitch * anodePitch / 12;
935     // fill Map of signals
936     fMap->FillMap(); 
937     Int_t j,i,ii,ianode,anode,itime;
938     Int_t wing,astart,astop,tstart,tstop,nanode;
939     Double_t fadc,ClusterTime;
940     Double_t q[400],x[400],z[400]; // digit charges and coordinates
941     for(j=0; j<nofClusters; j++) { 
942         AliITSRawClusterSDD *clusterJ=(AliITSRawClusterSDD*) fClusters->At(j);
943         Int_t ndigits = 0;
944         astart=clusterJ->Astart();
945         astop=clusterJ->Astop();
946         tstart=clusterJ->Tstartf();
947         tstop=clusterJ->Tstopf();
948         nanode=clusterJ->Anodes();  // <- Ernesto
949         wing=(Int_t)clusterJ->W();
950         if(wing == 2) {
951             astart += fNofAnodes; 
952             astop  += fNofAnodes;
953         }  // end if
954         // cout<<"astart,astop,tstart,tstop ="<<astart<<","<<astop<<","
955         //      <<tstart<<","<<tstop<<endl;
956         // clear the digit arrays
957         for(ii=0; ii<400; ii++) { 
958             q[ii] = 0.; 
959             x[ii] = 0.;
960             z[ii] = 0.;
961         } // end for ii
962
963         for(ianode=astart; ianode<=astop; ianode++) { 
964             for(itime=tstart; itime<=tstop; itime++) { 
965                 fadc=fMap->GetSignal(ianode,itime);
966                 if(fadc>baseline) {
967                     fadc-=(Double_t)baseline;
968                     q[ndigits] = fadc*(fTimeStep/160);  // KeV
969                     anode = ianode;
970                     if(wing == 2) anode -= fNofAnodes;
971                     z[ndigits] = (anode + 0.5 - fNofAnodes/2)*anodePitch;
972                     ClusterTime = itime*fTimeStep;
973                     if(ClusterTime > fTimeCorr) ClusterTime -= fTimeCorr;// ns
974                     x[ndigits] = fSddLength - ClusterTime*fDriftSpeed;
975                     if(wing == 1) x[ndigits] *= (-1);
976                     // cout<<"ianode,itime,fadc ="<<ianode<<","<<itime<<","
977                     //     <<fadc<<endl;
978                     // cout<<"wing,anode,ndigits,charge ="<<wing<<","
979                     //      <<anode<<","<<ndigits<<","<<q[ndigits]<<endl;
980                     ndigits++;
981                     continue;
982                 } //  end if
983                 fadc=0;
984                 //              cout<<"fadc=0, ndigits ="<<ndigits<<endl;
985             } // time loop
986         } // anode loop
987         //     cout<<"for new cluster ndigits ="<<ndigits<<endl;
988         // Fit cluster to resolve for two separate ones --------------------
989         Double_t qq=0., xm=0., zm=0., xx=0., zz=0., xz=0.;
990         Double_t dxx=0., dzz=0., dxz=0.;
991         Double_t scl = 0., tmp, tga, elps = -1.;
992         Double_t xfit[2], zfit[2], qfit[2];
993         Double_t pitchz = anodePitch*1.e-4;             // cm
994         Double_t pitchx = fTimeStep*fDriftSpeed*1.e-4;  // cm
995         Double_t sigma2;
996         Int_t nfhits;
997         Int_t nbins = ndigits;
998         Int_t separate = 0;
999         // now, all lengths are in microns
1000         for (ii=0; ii<nbins; ii++) {
1001             qq += q[ii];
1002             xm += x[ii]*q[ii];
1003             zm += z[ii]*q[ii];
1004             xx += x[ii]*x[ii]*q[ii];
1005             zz += z[ii]*z[ii]*q[ii];
1006             xz += x[ii]*z[ii]*q[ii];
1007         } // end for ii
1008         xm /= qq;
1009         zm /= qq;
1010         xx /= qq;
1011         zz /= qq;
1012         xz /= qq;
1013         dxx = xx - xm*xm;
1014         dzz = zz - zm*zm;
1015         dxz = xz - xm*zm;
1016
1017         // shrink the cluster in the time direction proportionaly to the 
1018         // dxx/dzz, which lineary depends from the drift path
1019         // new  Ernesto........         
1020         if( nanode == 1 ){
1021             dzz = dzz_1A; // for one anode cluster dzz = anode**2/12
1022             scl = TMath::Sqrt( 7.2/(-0.57*xm*1.e-3+71.8) );
1023         } // end if
1024         if( nanode == 2 ){
1025             scl = TMath::Sqrt( (-0.18*xm*1.e-3+21.3)/(-0.57*xm*1.e-3+71.8) );
1026         } // end if
1027         if( nanode == 3 ){
1028             scl = TMath::Sqrt( (-0.5*xm*1.e-3+34.5)/(-0.57*xm*1.e-3+71.8) );
1029         } // end if
1030         if( nanode > 3 ){
1031             scl = TMath::Sqrt( (1.3*xm*1.e-3+49.)/(-0.57*xm*1.e-3+71.8) );
1032         } // end if
1033         //   cout<<"1 microns: zm,dzz,xm,dxx,dxz,qq ="<<zm<<","<<dzz<<","
1034         //  <<xm<<","<<dxx<<","<<dxz<<","<<qq<<endl;
1035         //  old Boris.........
1036         //  tmp=29730. - 585.*fabs(xm/1000.); 
1037         //  scl=TMath::Sqrt(tmp/130000.);
1038    
1039         xm *= scl;
1040         xx *= scl*scl;
1041         xz *= scl;
1042
1043         dxx = xx - xm*xm;
1044         //   dzz = zz - zm*zm;
1045         dxz = xz - xm*zm;
1046         //   cout<<"microns: zm,dzz,xm,dxx,xz,dxz,qq ="<<zm<<","<<dzz<<","
1047         // <<xm<<","<<dxx<<","<<xz<<","<<dxz<<","<<qq<<endl;
1048         // if(dzz < 7200.) dzz=7200.;//for one anode cluster dzz = anode**2/12
1049   
1050         if (dxx < 0.) dxx=0.;
1051         // the data if no cluster overlapping (the coordunates are in cm) 
1052         nfhits = 1;
1053         xfit[0] = xm*1.e-4;
1054         zfit[0] = zm*1.e-4;
1055         qfit[0] = qq;
1056         //   if(nbins < 7) cout<<"**** nbins ="<<nbins<<endl;
1057   
1058         if (nbins >= 7) {
1059             if (dxz==0.) tga=0.;
1060             else {
1061                 tmp=0.5*(dzz-dxx)/dxz;
1062                 tga = (dxz<0.) ? tmp-TMath::Sqrt(tmp*tmp+1) : 
1063                                                    tmp+TMath::Sqrt(tmp*tmp+1);
1064             } // end if dxz
1065             elps=(tga*tga*dxx-2*tga*dxz+dzz)/(dxx+2*tga*dxz+tga*tga*dzz);
1066             // change from microns to cm
1067             xm *= 1.e-4; 
1068             zm *= 1.e-4; 
1069             zz *= 1.e-8;
1070             xx *= 1.e-8;
1071             xz *= 1.e-8;
1072             dxz *= 1.e-8;
1073             dxx *= 1.e-8;
1074             dzz *= 1.e-8;
1075             //   cout<<"cm: zm,dzz,xm,dxx,xz,dxz,qq ="<<zm<<","<<dzz<<","
1076             //  <<xm<<","<<dxx<<","<<xz<<","<<dxz<<","<<qq<<endl;
1077             for (i=0; i<nbins; i++) {     
1078                 x[i] = x[i] *= scl;
1079                 x[i] = x[i] *= 1.e-4;
1080                 z[i] = z[i] *= 1.e-4;
1081             } // end for i
1082             //     cout<<"!!! elps ="<<elps<<endl;
1083             if (elps < 0.3) { // try to separate hits 
1084                 separate = 1;
1085                 tmp=atan(tga);
1086                 Double_t cosa=cos(tmp),sina=sin(tmp);
1087                 Double_t a1=0., x1=0., xxx=0.;
1088                 for (i=0; i<nbins; i++) {
1089                     tmp=x[i]*cosa + z[i]*sina;
1090                     if (q[i] > a1) {
1091                         a1=q[i];
1092                         x1=tmp;
1093                     } // end if
1094                     xxx += tmp*tmp*tmp*q[i];
1095                 } // end for i
1096                 xxx /= qq;
1097                 Double_t z12=-sina*xm + cosa*zm;
1098                 sigma2=(sina*sina*xx-2*cosa*sina*xz+cosa*cosa*zz) - z12*z12;
1099                 xm=cosa*xm + sina*zm;
1100                 xx=cosa*cosa*xx + 2*cosa*sina*xz + sina*sina*zz;
1101                 Double_t x2=(xx - xm*x1 - sigma2)/(xm - x1);
1102                 Double_t r=a1*2*TMath::ACos(-1.)*sigma2/(qq*pitchx*pitchz);
1103                 for (i=0; i<33; i++) { // solve a system of equations
1104                     Double_t x1_old=x1, x2_old=x2, r_old=r;
1105                     Double_t c11=x1-x2;
1106                     Double_t c12=r;
1107                     Double_t c13=1-r;
1108                     Double_t c21=x1*x1 - x2*x2;
1109                     Double_t c22=2*r*x1;
1110                     Double_t c23=2*(1-r)*x2;
1111                     Double_t c31=3*sigma2*(x1-x2) + x1*x1*x1 - x2*x2*x2;
1112                     Double_t c32=3*r*(sigma2 + x1*x1);
1113                     Double_t c33=3*(1-r)*(sigma2 + x2*x2);
1114                     Double_t f1=-(r*x1 + (1-r)*x2 - xm);
1115                     Double_t f2=-(r*(sigma2+x1*x1)+(1-r)*(sigma2+x2*x2)- xx);
1116                     Double_t f3=-(r*x1*(3*sigma2+x1*x1)+(1-r)*x2*
1117                                                          (3*sigma2+x2*x2)-xxx);
1118                     Double_t d=c11*c22*c33+c21*c32*c13+c12*c23*c31-
1119                                        c31*c22*c13 - c21*c12*c33 - c32*c23*c11;
1120                     if (d==0.) {
1121                         cout<<"*********** d=0 ***********\n";
1122                         break;
1123                     } // end if
1124                     Double_t dr=f1*c22*c33 + f2*c32*c13 + c12*c23*f3 -
1125                         f3*c22*c13 - f2*c12*c33 - c32*c23*f1;
1126                     Double_t d1=c11*f2*c33 + c21*f3*c13 + f1*c23*c31 -
1127                         c31*f2*c13 - c21*f1*c33 - f3*c23*c11;
1128                     Double_t d2=c11*c22*f3 + c21*c32*f1 + c12*f2*c31 -
1129                         c31*c22*f1 - c21*c12*f3 - c32*f2*c11;
1130                     r  += dr/d;
1131                     x1 += d1/d;
1132                     x2 += d2/d;
1133                     if (fabs(x1-x1_old) > 0.0001) continue;
1134                     if (fabs(x2-x2_old) > 0.0001) continue;
1135                     if (fabs(r-r_old)/5 > 0.001) continue;
1136                     a1=r*qq*pitchx*pitchz/(2*TMath::ACos(-1.)*sigma2);
1137                     Double_t a2=a1*(1-r)/r;
1138                     qfit[0]=a1; xfit[0]=x1*cosa - z12*sina; zfit[0]=x1*sina + 
1139                                                                 z12*cosa;
1140                     qfit[1]=a2; xfit[1]=x2*cosa - z12*sina; zfit[1]=x2*sina + 
1141                                                                 z12*cosa;
1142                     nfhits=2;
1143                     break; // Ok !
1144                 } // end for i
1145                 if (i==33) cerr<<"No more iterations ! "<<endl;
1146             } // end of attempt to separate overlapped clusters
1147         } // end of nbins cut 
1148         if(elps < 0.) cout<<" elps=-1 ="<<elps<<endl;
1149         if(elps >0. && elps< 0.3 && nfhits == 1) cout<<" small elps, nfh=1 ="
1150                                                      <<elps<<","<<nfhits<<endl;
1151         if(nfhits == 2) cout<<" nfhits=2 ="<<nfhits<<endl;
1152         for (i=0; i<nfhits; i++) {
1153             xfit[i] *= (1.e+4/scl);
1154             if(wing == 1) xfit[i] *= (-1);
1155             zfit[i] *= 1.e+4;
1156             //       cout<<" ---------  i,xfiti,zfiti,qfiti ="<<i<<","
1157             // <<xfit[i]<<","<<zfit[i]<<","<<qfit[i]<<endl;
1158         } // end for i
1159         Int_t ncl = nfhits;
1160         if(nfhits == 1 && separate == 1) {
1161             cout<<"!!!!! no separate"<<endl;
1162             ncl = -2;
1163         }  // end if
1164         if(nfhits == 2) {
1165             cout << "Split cluster: " << endl;
1166             clusterJ->PrintInfo();
1167             cout << " in: " << endl;
1168             for (i=0; i<nfhits; i++) {
1169                 // AliITSRawClusterSDD *clust = new AliITSRawClusterSDD(wing,
1170                                                -1,-1,(Float_t)qfit[i],ncl,0,0,
1171                                                (Float_t)xfit[i],
1172                                                (Float_t)zfit[i],0,0,0,0,
1173                                                 tstart,tstop,astart,astop);
1174             //        AliITSRawClusterSDD *clust = new AliITSRawClusterSDD(wing,-1,
1175             //                                 -1,(Float_t)qfit[i],0,0,0,
1176             //                                  (Float_t)xfit[i],
1177             //                                  (Float_t)zfit[i],0,0,0,0,
1178             //                                  tstart,tstop,astart,astop,ncl);
1179             // ???????????
1180             // if(wing == 1) xfit[i] *= (-1);
1181             Float_t Anode = (zfit[i]/anodePitch+fNofAnodes/2-0.5);
1182             Float_t Time = (fSddLength - xfit[i])/fDriftSpeed;
1183             Float_t clusterPeakAmplitude = clusterJ->PeakAmpl();
1184             Float_t peakpos = clusterJ->PeakPos();
1185             Float_t clusteranodePath = (Anode - fNofAnodes/2)*anodePitch;
1186             Float_t clusterDriftPath = Time*fDriftSpeed;
1187             clusterDriftPath = fSddLength-clusterDriftPath;
1188             AliITSRawClusterSDD *clust = new AliITSRawClusterSDD(wing,Anode,
1189                                                                  Time,qfit[i],
1190                                                clusterPeakAmplitude,peakpos,
1191                                                0.,0.,clusterDriftPath,
1192                                          clusteranodePath,clusterJ->Samples()/2
1193                                     ,tstart,tstop,0,0,0,astart,astop);
1194             clust->PrintInfo();
1195             iTS->AddCluster(1,clust);
1196             //        cout<<"new cluster added: tstart,tstop,astart,astop,x,ncl ="
1197             // <<tstart<<","<<tstop<<","<<astart<<","<<astop<<","<<xfit[i]
1198             // <<","<<ncl<<endl;
1199             delete clust;
1200         }// nfhits loop
1201         fClusters->RemoveAt(j);
1202     } // if nfhits = 2
1203 } // cluster loop
1204 fClusters->Compress();
1205 fMap->ClearMap(); 
1206 */
1207     return;
1208 }
1209 //______________________________________________________________________
1210 void AliITSClusterFinderSDD::GetRecPoints(){
1211     // get rec points
1212     static AliITS *iTS=(AliITS*)gAlice->GetModule("ITS");
1213     // get number of clusters for this module
1214     Int_t nofClusters = fClusters->GetEntriesFast();
1215     nofClusters -= fNclusters;
1216     const Float_t kconvGeV = 1.e-6; // GeV -> KeV
1217     const Float_t kconv = 1.0e-4; 
1218     const Float_t kRMSx = 38.0*kconv; // microns->cm ITS TDR Table 1.3
1219     const Float_t kRMSz = 28.0*kconv; // microns->cm ITS TDR Table 1.3
1220     Int_t i,j;
1221     Int_t ix, iz, idx=-1;
1222     AliITSdigitSDD *dig=0;
1223     Int_t ndigits=fDigits->GetEntriesFast();
1224     for(i=0; i<nofClusters; i++) { 
1225         AliITSRawClusterSDD *clusterI = (AliITSRawClusterSDD*)fClusters->At(i);
1226         if(!clusterI) Error("SDD: GetRecPoints","i clusterI ",i,clusterI);
1227         if(clusterI) idx=clusterI->PeakPos();
1228         if(idx>ndigits) Error("SDD: GetRecPoints","idx ndigits",idx,ndigits);
1229         // try peak neighbours - to be done 
1230         if(idx&&idx<= ndigits) dig =(AliITSdigitSDD*)fDigits->UncheckedAt(idx);
1231         //// debug
1232         //      cout<<"R.C. Anode = "<<clusterI->A()<<"; Time= "<<clusterI->T()<<endl;
1233         fSegmentation->LocalToDet(clusterI->X(),clusterI->Z(),ix,iz);
1234         //      cout<<"From R.C. coordinates- Anode: "<<iz<<" and time: "<<ix<<endl;
1235         // end debug
1236         Int_t trks[10];
1237         Int_t notr=-1;
1238         Int_t deger = 0;
1239         if(!dig) {
1240           Warning("GetRecPoints","Cannot assign the track number\n");
1241         }
1242         else {
1243           fSegmentation->LocalToDet(clusterI->X(),clusterI->Z(),ix,iz);
1244           Int_t signal[30];
1245           for(Int_t kk=0;kk<9;kk++)trks[kk]=-2;
1246           AliITSdigitSDD * pdig = 0;
1247           for(Int_t itime=ix-1;itime<=ix+1;itime++){
1248             if(itime<0 || itime>=fSegmentation->Npx())continue;
1249             for(Int_t ianod=iz-1;ianod<=iz+1;ianod++){
1250               if(ianod<0 || ianod>=fSegmentation->Npz())continue;
1251               if(iz==(fSegmentation->Npz())/2 && ianod<iz)continue;
1252               if(iz==(fSegmentation->Npz())/2-1 && ianod>iz)continue;
1253               pdig = (AliITSdigitSDD*)fMap->GetHit(ianod,itime);
1254               if(pdig){
1255                 for(Int_t kk=0;kk<3;kk++){
1256                   if(kk == 0 || (kk>0 && pdig->fTracks[kk]>=0)){
1257                     notr++;
1258                     trks[notr]=pdig->fTracks[kk];
1259                     signal[notr]=pdig->fSignal;
1260                   }
1261                 }
1262               }
1263             }
1264           } // for(itime....
1265           if((dig->fCoord1<(iz-1) || dig->fCoord1>(iz+1)) 
1266              && (dig->fCoord2<(ix-1) || dig->fCoord2>(ix+1)) 
1267              && dig->fTracks[0]>=-2){
1268             notr++;
1269             trks[notr]=dig->fTracks[0];
1270             signal[notr]=dig->fSignal;
1271           }
1272           for(Int_t ii=0; ii<notr;ii++){
1273             for(Int_t jj=ii+1; jj<=notr; jj++){
1274               if(trks[ii] == trks[jj]){
1275                 signal[ii]+=signal[jj];
1276                 signal[jj]=-100;
1277                 trks[jj]=-jj-100;
1278                 deger++;
1279               }
1280             }
1281           }
1282           Int_t ordtmp;
1283           for(Int_t ii=0; ii<notr;ii++){
1284             Int_t maxi = ii;
1285             for(Int_t jj=ii+1; jj<=notr; jj++){
1286               if(signal[jj]>signal[maxi])maxi=jj;
1287             }
1288             ordtmp = trks[ii];
1289             trks[ii]=trks[maxi];
1290             trks[maxi]=ordtmp;
1291             ordtmp = signal[ii];
1292             signal[ii]=signal[maxi];
1293             signal[maxi]=ordtmp;
1294           }
1295         }
1296         notr-=deger;
1297         notr++;
1298         /*
1299           if(!dig) {
1300             // try cog
1301             fSegmentation->GetPadIxz(clusterI->X(),clusterI->Z(),ix,iz);
1302             dig = (AliITSdigitSDD*)fMap->GetHit(iz-1,ix-1);
1303             // if null try neighbours
1304             if (!dig) dig = (AliITSdigitSDD*)fMap->GetHit(iz-1,ix); 
1305             if (!dig) dig = (AliITSdigitSDD*)fMap->GetHit(iz-1,ix+1); 
1306             if (!dig) printf("SDD: cannot assign the track number!\n");
1307         } //  end if !dig
1308         */
1309         AliITSRecPoint rnew;
1310         rnew.SetX(clusterI->X());
1311         rnew.SetZ(clusterI->Z());
1312         rnew.SetQ(clusterI->Q());   // in KeV - should be ADC
1313         //      cout<<"Cluster # "<<i<< " - X,Z,Q= "<<clusterI->X()<<" "<<clusterI->Z()<<" "<<clusterI->Q()<<"; Digit n= "<<idx<<endl;
1314         rnew.SetdEdX(kconvGeV*clusterI->Q());
1315         rnew.SetSigmaX2(kRMSx*kRMSx);
1316         rnew.SetSigmaZ2(kRMSz*kRMSz);
1317         if(notr>3)notr=3;
1318         if(notr>=0)for(j=0;j<notr;j++)rnew.fTracks[j]=trks[j];
1319         /*     
1320         if(dig){
1321           for(j=0;j<dig->GetNTracks();j++){
1322             if(j>0 && j%4==0)cout<<endl;
1323           }
1324           cout<<endl;
1325             rnew.fTracks[0] = dig->fTracks[0];
1326             cout<<"  "<<dig->fTracks[0]<<" assigned to rp 0 "<<rnew.fTracks[0]<<endl;
1327             rnew.fTracks[1] = -3;
1328             rnew.fTracks[2] = -3;
1329             j=1;
1330             while(rnew.fTracks[0]==dig->fTracks[j] &&
1331                   j<dig->GetNTracks()) j++;
1332             if(j<dig->GetNTracks()){
1333                 rnew.fTracks[1] = dig->fTracks[j];
1334                 cout<<"  Digit "<<j<<" "<<dig->fTracks[j]<<" assigned to rp 1 "<<rnew.fTracks[1]<<endl;
1335                 while((rnew.fTracks[0]==dig->fTracks[j] || 
1336                        rnew.fTracks[1]==dig->fTracks[j] )&& 
1337                       j<dig->GetNTracks()) j++;
1338                 if(j<dig->GetNTracks()) {
1339                   rnew.fTracks[2] = dig->fTracks[j];
1340                   cout<<"  Digit "<<j<<" "<<dig->fTracks[j]<<" assigned to rp 2 "<<rnew.fTracks[2]<<endl;
1341                 }
1342             } // end if
1343         } // end if
1344         */
1345
1346         iTS->AddRecPoint(rnew);
1347     } // I clusters
1348 //    fMap->ClearMap();
1349 }
1350 //______________________________________________________________________
1351 void AliITSClusterFinderSDD::FindRawClusters(Int_t mod){
1352     // find raw clusters
1353     
1354     fModule = mod;
1355     
1356     Find1DClustersE();
1357     GroupClusters();
1358     SelectClusters();
1359     ResolveClustersE();
1360     GetRecPoints();
1361 }
1362 //_______________________________________________________________________
1363 void AliITSClusterFinderSDD::Print() const{
1364     // Print SDD cluster finder Parameters
1365
1366     cout << "**************************************************" << endl;
1367     cout << " Silicon Drift Detector Cluster Finder Parameters " << endl;
1368     cout << "**************************************************" << endl;
1369     cout << "Number of Clusters: " << fNclusters << endl;
1370     cout << "Anode Tolerance: " << fDAnode << endl;
1371     cout << "Time  Tolerance: " << fDTime << endl;
1372     cout << "Time  correction (electronics): " << fTimeCorr << endl;
1373     cout << "Cut Amplitude (threshold): " << fCutAmplitude << endl;
1374     cout << "Minimum Amplitude: " << fMinPeak << endl;
1375     cout << "Minimum Charge: " << fMinCharge << endl;
1376     cout << "Minimum number of cells/clusters: " << fMinNCells << endl;
1377     cout << "Maximum number of cells/clusters: " << fMaxNCells << endl;
1378     cout << "**************************************************" << endl;
1379 }