]> git.uio.no Git - u/mrichter/AliRoot.git/blob - ITS/AliITSClusterFinderSDD.cxx
merging RecPoints and ClustersV2. All ClusterFinders produce AliITSRecPoints objects...
[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
24
25 #include "AliITSClusterFinderSDD.h"
26 #include "AliITSMapA1.h"
27 #include "AliITSRawClusterSDD.h"
28 #include "AliITSRecPoint.h"
29 #include "AliITSdigitSDD.h"
30 #include "AliITSDetTypeRec.h"
31 #include "AliITSCalibrationSDD.h"
32 #include "AliITSsegmentationSDD.h"
33 #include "AliLog.h"
34
35 ClassImp(AliITSClusterFinderSDD)
36
37 //______________________________________________________________________
38 AliITSClusterFinderSDD::AliITSClusterFinderSDD():
39 AliITSClusterFinder(),
40 fNclusters(0),
41 fDAnode(0.0),
42 fDTime(0.0),
43 fTimeCorr(0.0),
44 fCutAmplitude(0),
45 fMinPeak(0),
46 fMinCharge(0),
47 fMinNCells(0),
48 fMaxNCells(0){
49     // default constructor
50 }
51 //______________________________________________________________________
52 AliITSClusterFinderSDD::AliITSClusterFinderSDD(AliITSDetTypeRec* dettyp,
53                                                TClonesArray *digits,
54                                                TClonesArray *recp):
55 AliITSClusterFinder(dettyp),
56 fNclusters(0),
57 fDAnode(0.0),
58 fDTime(0.0),
59 fTimeCorr(0.0),
60 fCutAmplitude(0),
61 fMinPeak(0),
62 fMinCharge(0),
63 fMinNCells(0),
64 fMaxNCells(0){
65     // standard constructor
66
67     SetDigits(digits);
68     SetClusters(recp);
69     SetCutAmplitude(fDetTypeRec->GetITSgeom()->GetStartSDD());
70     SetDAnode();
71     SetDTime();
72     SetMinPeak((Int_t)(((AliITSCalibrationSDD*)GetResp(fDetTypeRec->GetITSgeom()->GetStartSDD()))->
73                        GetNoiseAfterElectronics()*5));
74     //    SetMinPeak();
75     SetMinNCells();
76     SetMaxNCells();
77     SetTimeCorr();
78     SetMinCharge();
79     SetMap(new AliITSMapA1(GetSeg(),Digits(),fCutAmplitude));
80 }
81 //______________________________________________________________________
82 void AliITSClusterFinderSDD::SetCutAmplitude(Int_t mod,Double_t nsigma){
83     // set the signal threshold for cluster finder
84     Double_t baseline,noise,noiseAfterEl;
85
86     GetResp(mod)->GetNoiseParam(noise,baseline);
87     noiseAfterEl = ((AliITSCalibrationSDD*)GetResp(mod))->GetNoiseAfterElectronics();
88     fCutAmplitude = (Int_t)((baseline + nsigma*noiseAfterEl));
89 }
90 //______________________________________________________________________
91 void AliITSClusterFinderSDD::Find1DClusters(){
92     // find 1D clusters
93   
94     // retrieve the parameters 
95     Int_t fNofMaps       = GetSeg()->Npz();
96     Int_t fMaxNofSamples = GetSeg()->Npx();
97     Int_t fNofAnodes     = fNofMaps/2;
98     Int_t dummy          = 0;
99     Double_t fTimeStep    = GetSeg()->Dpx(dummy);
100     Double_t fSddLength   = GetSeg()->Dx();
101     Double_t fDriftSpeed  = GetResp(fModule)->GetDriftSpeed();  
102     Double_t anodePitch   = GetSeg()->Dpz(dummy);
103
104     // map the signal
105     Map()->ClearMap();
106     Map()->SetThreshold(fCutAmplitude);
107     Map()->FillMap();
108   
109     Double_t noise;
110     Double_t baseline;
111     GetResp(fModule)->GetNoiseParam(noise,baseline);
112   
113     Int_t nofFoundClusters = 0;
114     Int_t i;
115     Double_t **dfadc = new Double_t*[fNofAnodes];
116     for(i=0;i<fNofAnodes;i++) dfadc[i] = new Double_t[fMaxNofSamples];
117     Double_t fadc  = 0.;
118     Double_t fadc1 = 0.;
119     Double_t fadc2 = 0.;
120     Int_t j,k,idx,l,m;
121     for(j=0;j<2;j++) {
122         for(k=0;k<fNofAnodes;k++) {
123             idx = j*fNofAnodes+k;
124             // signal (fadc) & derivative (dfadc)
125             dfadc[k][255]=0.;
126             for(l=0; l<fMaxNofSamples; l++) {
127                 fadc2=(Double_t)Map()->GetSignal(idx,l);
128                 if(l>0) fadc1=(Double_t)Map()->GetSignal(idx,l-1);
129                 if(l>0) dfadc[k][l-1] = fadc2-fadc1;
130             } // samples
131         } // anodes
132
133         for(k=0;k<fNofAnodes;k++) {
134             AliDebug(5,Form("Anode: %d, Wing: %d",k+1,j+1));
135             idx = j*fNofAnodes+k;
136             Int_t imax  = 0;
137             Int_t imaxd = 0;
138             Int_t it    = 0;
139             while(it <= fMaxNofSamples-3) {
140                 imax  = it;
141                 imaxd = it;
142                 // maximum of signal          
143                 Double_t fadcmax  = 0.;
144                 Double_t dfadcmax = 0.;
145                 Int_t lthrmina   = 1;
146                 Int_t lthrmint   = 3;
147                 Int_t lthra      = 1;
148                 Int_t lthrt      = 0;
149                 for(m=0;m<20;m++) {
150                     Int_t id = it+m;
151                     if(id>=fMaxNofSamples) break;
152                     fadc=(float)Map()->GetSignal(idx,id);
153                     if(fadc > fadcmax) { fadcmax = fadc; imax = id;}
154                     if(fadc > (float)fCutAmplitude)lthrt++; 
155                     if(dfadc[k][id] > dfadcmax) {
156                         dfadcmax = dfadc[k][id];
157                         imaxd    = id;
158                     } // end if
159                 } // end for m
160                 it = imaxd;
161                 if(Map()->TestHit(idx,imax) == kEmpty) {it++; continue;}
162                 // cluster charge
163                 Int_t tstart = it-2;
164                 if(tstart < 0) tstart = 0;
165                 Bool_t ilcl = 0;
166                 if(lthrt >= lthrmint && lthra >= lthrmina) ilcl = 1;
167                 if(ilcl) {
168                     nofFoundClusters++;
169                     Int_t tstop      = tstart;
170                     Double_t dfadcmin = 10000.;
171                     Int_t ij;
172                     for(ij=0; ij<20; ij++) {
173                         if(tstart+ij > 255) { tstop = 255; break; }
174                         fadc=(float)Map()->GetSignal(idx,tstart+ij);
175                         if((dfadc[k][tstart+ij] < dfadcmin) && 
176                            (fadc > fCutAmplitude)) {
177                             tstop = tstart+ij+5;
178                             if(tstop > 255) tstop = 255;
179                             dfadcmin = dfadc[k][it+ij];
180                         } // end if
181                     } // end for ij
182
183                     Double_t clusterCharge = 0.;
184                     Double_t clusterAnode  = k+0.5;
185                     Double_t clusterTime   = 0.;
186                     Int_t   clusterMult   = 0;
187                     Double_t clusterPeakAmplitude = 0.;
188                     Int_t its,peakpos     = -1;
189                     Double_t n, baseline;
190                     GetResp(fModule)->GetNoiseParam(n,baseline);
191                     for(its=tstart; its<=tstop; its++) {
192                         fadc=(float)Map()->GetSignal(idx,its);
193                         if(fadc>baseline) fadc -= baseline;
194                         else fadc = 0.;
195                         clusterCharge += fadc;
196                         // as a matter of fact we should take the peak
197                         // pos before FFT
198                         // to get the list of tracks !!!
199                         if(fadc > clusterPeakAmplitude) {
200                             clusterPeakAmplitude = fadc;
201                             //peakpos=Map()->GetHitIndex(idx,its);
202                             Int_t shift = (int)(fTimeCorr/fTimeStep);
203                             if(its>shift && its<(fMaxNofSamples-shift))
204                                 peakpos  = Map()->GetHitIndex(idx,its+shift);
205                             else peakpos = Map()->GetHitIndex(idx,its);
206                             if(peakpos<0) peakpos =Map()->GetHitIndex(idx,its);
207                         } // end if
208                         clusterTime += fadc*its;
209                         if(fadc > 0) clusterMult++;
210                         if(its == tstop) {
211                             clusterTime /= (clusterCharge/fTimeStep);   // ns
212                             if(clusterTime>fTimeCorr) clusterTime -=fTimeCorr;
213                             //ns
214                         } // end if
215                     } // end for its
216
217                     Double_t clusteranodePath = (clusterAnode - fNofAnodes/2)*
218                                                  anodePitch;
219                     Double_t clusterDriftPath = clusterTime*fDriftSpeed;
220                     clusterDriftPath = fSddLength-clusterDriftPath;
221                     if(clusterCharge <= 0.) break;
222                     AliITSRawClusterSDD clust(j+1,//i
223                                               clusterAnode,clusterTime,//ff
224                                               clusterCharge, //f
225                                               clusterPeakAmplitude, //f
226                                               peakpos, //i
227                                               0.,0.,clusterDriftPath,//fff
228                                               clusteranodePath, //f
229                                               clusterMult, //i
230                                               0,0,0,0,0,0,0);//7*i
231                     fDetTypeRec->AddCluster(1,&clust);
232                     it = tstop;
233                 } // ilcl
234                 it++;
235             } // while (samples)
236         } // anodes
237     } // detectors (2)
238
239     for(i=0;i<fNofAnodes;i++) delete[] dfadc[i];
240     delete [] dfadc;
241
242     return;
243 }
244 //______________________________________________________________________
245 void AliITSClusterFinderSDD::Find1DClustersE(){
246     // find 1D clusters
247     // retrieve the parameters 
248     Int_t fNofMaps = GetSeg()->Npz();
249     Int_t fMaxNofSamples = GetSeg()->Npx();
250     Int_t fNofAnodes = fNofMaps/2;
251     Int_t dummy=0;
252     Double_t fTimeStep = GetSeg()->Dpx( dummy );
253     Double_t fSddLength = GetSeg()->Dx();
254     Double_t fDriftSpeed = GetResp(fModule)->GetDriftSpeed();
255     Double_t anodePitch = GetSeg()->Dpz( dummy );
256     Double_t n, baseline;
257     GetResp(fModule)->GetNoiseParam( n, baseline );
258     // map the signal
259     Map()->ClearMap();
260     Map()->SetThreshold( fCutAmplitude );
261     Map()->FillMap();
262
263     Int_t nClu = 0;
264     //        cout << "Search  cluster... "<< endl;
265     for( Int_t j=0; j<2; j++ ){
266         for( Int_t k=0; k<fNofAnodes; k++ ){
267             Int_t idx = j*fNofAnodes+k;
268             Bool_t on = kFALSE;
269             Int_t start = 0;
270             Int_t nTsteps = 0;
271             Double_t fmax = 0.;
272             Int_t lmax = 0;
273             Double_t charge = 0.;
274             Double_t time = 0.;
275             Double_t anode = k+0.5;
276             Int_t peakpos = -1;
277             for( Int_t l=0; l<fMaxNofSamples; l++ ){
278                 Double_t fadc = (Double_t)Map()->GetSignal( idx, l );
279                 if( fadc > 0.0 ){
280                     if( on == kFALSE && l<fMaxNofSamples-4){
281                         // star RawCluster (reset var.)
282                         Double_t fadc1 = (Double_t)Map()->GetSignal( idx, l+1 );
283                         if( fadc1 < fadc ) continue;
284                         start = l;
285                         fmax = 0.;
286                         lmax = 0;
287                         time = 0.;
288                         charge = 0.; 
289                         on = kTRUE; 
290                         nTsteps = 0;
291                     } // end if on...
292                     nTsteps++ ;
293                     if( fadc > baseline ) fadc -= baseline;
294                     else fadc=0.;
295                     charge += fadc;
296                     time += fadc*l;
297                     if( fadc > fmax ){ 
298                         fmax = fadc; 
299                         lmax = l; 
300                         Int_t shift = (Int_t)(fTimeCorr/fTimeStep + 0.5);
301                         if( l > shift && l < (fMaxNofSamples-shift) )  
302                             peakpos = Map()->GetHitIndex( idx, l+shift );
303                         else
304                             peakpos = Map()->GetHitIndex( idx, l );
305                         if( peakpos < 0) peakpos = Map()->GetHitIndex(idx,l);
306                     } // end if fadc
307                 }else{ // end fadc>0
308                     if( on == kTRUE ){        
309                         if( nTsteps > 2 ){
310                             //  min # of timesteps for a RawCluster
311                             // Found a RawCluster...
312                             Int_t stop = l-1;
313                             time /= (charge/fTimeStep);   // ns
314                                 // time = lmax*fTimeStep;   // ns
315                             if( time > fTimeCorr ) time -= fTimeCorr;   // ns
316                             Double_t anodePath =(anode-fNofAnodes/2)*anodePitch;
317                             Double_t driftPath = time*fDriftSpeed;
318                             driftPath = fSddLength-driftPath;
319                             AliITSRawClusterSDD clust(j+1,anode,time,charge,
320                                                       fmax, peakpos,0.,0.,
321                                                       driftPath,anodePath,
322                                                       nTsteps,start,stop,
323                                                       start, stop, 1, k, k );
324                             fDetTypeRec->AddCluster( 1, &clust );
325                             if(AliDebugLevel()>=5) clust.PrintInfo();
326                             nClu++;
327                         } // end if nTsteps
328                         on = kFALSE;
329                     } // end if on==kTRUE
330                 } // end if fadc>0
331             } // samples
332         } // anodes
333     } // wings
334     AliDebug(3,Form("# Rawclusters %d",nClu));         
335     return; 
336 }
337 //_______________________________________________________________________
338 Int_t AliITSClusterFinderSDD::SearchPeak(Double_t *spect,Int_t xdim,Int_t zdim,
339                                          Int_t *peakX, Int_t *peakZ, 
340                                          Double_t *peakAmp, Double_t minpeak ){
341     // search peaks on a 2D cluster
342     Int_t npeak = 0;    // # peaks
343     Int_t i,j;
344     // search peaks
345     for( Int_t z=1; z<zdim-1; z++ ){
346         for( Int_t x=1; x<xdim-2; x++ ){
347             Double_t sxz = spect[x*zdim+z];
348             Double_t sxz1 = spect[(x+1)*zdim+z];
349             Double_t sxz2 = spect[(x-1)*zdim+z];
350             // search a local max. in s[x,z]
351             if( sxz < minpeak || sxz1 <= 0 || sxz2 <= 0 ) continue;
352             if( sxz >= spect[(x+1)*zdim+z  ] && sxz >= spect[(x-1)*zdim+z  ] &&
353                 sxz >= spect[x*zdim    +z+1] && sxz >= spect[x*zdim    +z-1] &&
354                 sxz >= spect[(x+1)*zdim+z+1] && sxz >= spect[(x+1)*zdim+z-1] &&
355                 sxz >= spect[(x-1)*zdim+z+1] && sxz >= spect[(x-1)*zdim+z-1] ){
356                 // peak found
357                 peakX[npeak] = x;
358                 peakZ[npeak] = z;
359                 peakAmp[npeak] = sxz;
360                 npeak++;
361             } // end if ....
362         } // end for x
363     } // end for z
364     // search groups of peaks with same amplitude.
365     Int_t *flag = new Int_t[npeak];
366     for( i=0; i<npeak; i++ ) flag[i] = 0;
367     for( i=0; i<npeak; i++ ){
368         for( j=0; j<npeak; j++ ){
369             if( i==j) continue;
370             if( flag[j] > 0 ) continue;
371             if( peakAmp[i] == peakAmp[j] && 
372                 TMath::Abs(peakX[i]-peakX[j])<=1 && 
373                 TMath::Abs(peakZ[i]-peakZ[j])<=1 ){
374                 if( flag[i] == 0) flag[i] = i+1;
375                 flag[j] = flag[i];
376             } // end if ...
377         } // end for j
378     } // end for i
379     // make average of peak groups        
380     for( i=0; i<npeak; i++ ){
381         Int_t nFlag = 1;
382         if( flag[i] <= 0 ) continue;
383         for( j=0; j<npeak; j++ ){
384             if( i==j ) continue;
385             if( flag[j] != flag[i] ) continue;
386             peakX[i] += peakX[j];
387             peakZ[i] += peakZ[j];
388             nFlag++;
389             npeak--;
390             for( Int_t k=j; k<npeak; k++ ){
391                 peakX[k] = peakX[k+1];
392                 peakZ[k] = peakZ[k+1];
393                 peakAmp[k] = peakAmp[k+1];
394                 flag[k] = flag[k+1];
395             } // end for k        
396             j--;
397         } // end for j
398         if( nFlag > 1 ){
399             peakX[i] /= nFlag;
400             peakZ[i] /= nFlag;
401         } // end fi nFlag
402     } // end for i
403     delete [] flag;
404     return( npeak );
405 }
406 //______________________________________________________________________
407 void AliITSClusterFinderSDD::PeakFunc( Int_t xdim, Int_t zdim, Double_t *par,
408                                        Double_t *spe, Double_t *integral){
409     // function used to fit the clusters
410     // par -> parameters..
411     // par[0]  number of peaks.
412     // for each peak i=1, ..., par[0]
413     //                 par[i] = Ampl.
414     //                 par[i+1] = xpos
415     //                 par[i+2] = zpos
416     //                 par[i+3] = tau
417     //                 par[i+4] = sigma.
418     Int_t electronics = GetResp(fModule)->GetElectronics(); // 1 = PASCAL, 2 = OLA
419     const Int_t knParam = 5;
420     Int_t npeak = (Int_t)par[0];
421
422     memset( spe, 0, sizeof( Double_t )*zdim*xdim );
423
424     Int_t k = 1;
425     for( Int_t i=0; i<npeak; i++ ){
426         if( integral != 0 ) integral[i] = 0.;
427         Double_t sigmaA2 = par[k+4]*par[k+4]*2.;
428         Double_t t2 = par[k+3];   // PASCAL
429         if( electronics == 2 ) { t2 *= t2; t2 *= 2; } // OLA
430         for( Int_t z=0; z<zdim; z++ ){
431             for( Int_t x=0; x<xdim; x++ ){
432                 Double_t z2 = (z-par[k+2])*(z-par[k+2])/sigmaA2;
433                 Double_t x2 = 0.;
434                 Double_t signal = 0.;
435                 if( electronics == 1 ){ // PASCAL
436                     x2 = (x-par[k+1]+t2)/t2;
437                     signal = (x2>0.) ? par[k]*x2*exp(-x2+1.-z2) :0.0; // RCCR2
438                 //  signal =(x2>0.) ? par[k]*x2*x2*exp(-2*x2+2.-z2 ):0.0;//RCCR
439                 }else if( electronics == 2 ) { // OLA
440                     x2 = (x-par[k+1])*(x-par[k+1])/t2;
441                     signal = par[k]  * exp( -x2 - z2 );
442                 } else {
443                     Warning("PeakFunc","Wrong SDD Electronics = %d",
444                             electronics);
445                     // exit( 1 );
446                 } // end if electronicx
447                 spe[x*zdim+z] += signal;
448                 if( integral != 0 ) integral[i] += signal;
449             } // end for x
450         } // end for z
451         k += knParam;
452     } // end for i
453     return;
454 }
455 //__________________________________________________________________________
456 Double_t AliITSClusterFinderSDD::ChiSqr( Int_t xdim, Int_t zdim, Double_t *spe,
457                                         Double_t *speFit ) const{
458     // EVALUATES UNNORMALIZED CHI-SQUARED
459     Double_t chi2 = 0.;
460     for( Int_t z=0; z<zdim; z++ ){
461         for( Int_t x=1; x<xdim-1; x++ ){
462             Int_t index = x*zdim+z;
463             Double_t tmp = spe[index] - speFit[index];
464             chi2 += tmp*tmp;
465         } // end for x
466     } // end for z
467     return( chi2 );
468 }
469 //_______________________________________________________________________
470 void AliITSClusterFinderSDD::Minim( Int_t xdim, Int_t zdim, Double_t *param,
471                                     Double_t *prm0,Double_t *steprm,
472                                     Double_t *chisqr,Double_t *spe,
473                                     Double_t *speFit ){
474     // 
475     Int_t   k, nnn, mmm, i;
476     Double_t p1, delta, d1, chisq1, p2, chisq2, t, p3, chisq3, a, b, p0, chisqt;
477     const Int_t knParam = 5;
478     Int_t npeak = (Int_t)param[0];
479     for( k=1; k<(npeak*knParam+1); k++ ) prm0[k] = param[k];
480     for( k=1; k<(npeak*knParam+1); k++ ){
481         p1 = param[k];
482         delta = steprm[k];
483         d1 = delta;
484         // ENSURE THAT STEP SIZE IS SENSIBLY LARGER THAN MACHINE ROUND OFF
485         if( TMath::Abs( p1 ) > 1.0E-6 ) 
486             if ( TMath::Abs( delta/p1 ) < 1.0E-4 ) delta = p1/1000;
487             else  delta = (Double_t)1.0E-4;
488         //  EVALUATE CHI-SQUARED AT FIRST TWO SEARCH POINTS
489         PeakFunc( xdim, zdim, param, speFit );
490         chisq1 = ChiSqr( xdim, zdim, spe, speFit );
491         p2 = p1+delta;
492         param[k] = p2;
493         PeakFunc( xdim, zdim, param, speFit );
494         chisq2 = ChiSqr( xdim, zdim, spe, speFit );
495         if( chisq1 < chisq2 ){
496             // REVERSE DIRECTION OF SEARCH IF CHI-SQUARED IS INCREASING
497             delta = -delta;
498             t = p1;
499             p1 = p2;
500             p2 = t;
501             t = chisq1;
502             chisq1 = chisq2;
503             chisq2 = t;
504         } // end if
505         i = 1; nnn = 0;
506         do {   // INCREMENT param(K) UNTIL CHI-SQUARED STARTS TO INCREASE
507             nnn++;
508             p3 = p2 + delta;
509             mmm = nnn - (nnn/5)*5;  // multiplo de 5
510             if( mmm == 0 ){
511                 d1 = delta;
512                 // INCREASE STEP SIZE IF STEPPING TOWARDS MINIMUM IS TOO SLOW 
513                 delta *= 5;
514             } // end if
515             param[k] = p3;
516             // Constrain paramiters
517             Int_t kpos = (k-1) % knParam;
518             switch( kpos ){
519             case 0 :
520                 if( param[k] <= 20 ) param[k] = fMinPeak;
521                 break;
522             case 1 :
523                 if( TMath::Abs( param[k] - prm0[k] ) > 1.5 ) param[k] = prm0[k];
524                 break;
525             case 2 :
526                 if( TMath::Abs( param[k] - prm0[k] ) > 1. ) param[k] = prm0[k];
527                 break;
528             case 3 :
529                 if( param[k] < .5 ) param[k] = .5;        
530                 break;
531             case 4 :
532                 if( param[k] < .288 ) param[k] = .288;// 1/sqrt(12) = 0.288
533                 if( param[k] > zdim*.5 ) param[k] = zdim*.5;
534                 break;
535             }; // end switch
536             PeakFunc( xdim, zdim, param, speFit );
537             chisq3 = ChiSqr( xdim, zdim, spe, speFit );
538             if( chisq3 < chisq2 && nnn < 50 ){
539                 p1 = p2;
540                 p2 = p3;
541                 chisq1 = chisq2;
542                 chisq2 = chisq3;
543             }else i=0;
544         } while( i );
545         // FIND MINIMUM OF PARABOLA DEFINED BY LAST THREE POINTS
546         a = chisq1*(p2-p3)+chisq2*(p3-p1)+chisq3*(p1-p2);
547         b = chisq1*(p2*p2-p3*p3)+chisq2*(p3*p3-p1*p1)+chisq3*(p1*p1-p2*p2);
548         if( a!=0 ) p0 = (Double_t)(0.5*b/a);
549         else p0 = 10000;
550         //--IN CASE OF NEARLY EQUAL CHI-SQUARED AND TOO SMALL STEP SIZE PREVENT
551         //   ERRONEOUS EVALUATION OF PARABOLA MINIMUM
552         //---NEXT TWO LINES CAN BE OMITTED FOR HIGHER PRECISION MACHINES
553         //dp = (Double_t) max (TMath::Abs(p3-p2), TMath::Abs(p2-p1));
554         //if( TMath::Abs( p2-p0 ) > dp ) p0 = p2;
555         param[k] = p0;
556         // Constrain paramiters
557         Int_t kpos = (k-1) % knParam;
558         switch( kpos ){
559         case 0 :
560             if( param[k] <= 20 ) param[k] = fMinPeak;   
561             break;
562         case 1 :
563             if( TMath::Abs( param[k] - prm0[k] ) > 1.5 ) param[k] = prm0[k];
564             break;
565         case 2 :
566             if( TMath::Abs( param[k] - prm0[k] ) > 1. ) param[k] = prm0[k];
567             break;
568         case 3 :
569             if( param[k] < .5 ) param[k] = .5;        
570             break;
571         case 4 :
572             if( param[k] < .288 ) param[k] = .288;  // 1/sqrt(12) = 0.288
573             if( param[k] > zdim*.5 ) param[k] = zdim*.5;
574             break;
575         }; // end switch
576         PeakFunc( xdim, zdim, param, speFit );
577         chisqt = ChiSqr( xdim, zdim, spe, speFit );
578         // DO NOT ALLOW ERRONEOUS INTERPOLATION
579         if( chisqt <= *chisqr ) *chisqr = chisqt;
580         else param[k] = prm0[k];
581         // OPTIMIZE SEARCH STEP FOR EVENTUAL NEXT CALL OF MINIM
582         steprm[k] = (param[k]-prm0[k])/5;
583         if( steprm[k] >= d1 ) steprm[k] = d1/5;
584     } // end for k
585     // EVALUATE FIT AND CHI-SQUARED FOR OPTIMIZED PARAMETERS
586     PeakFunc( xdim, zdim, param, speFit );
587     *chisqr = ChiSqr( xdim, zdim, spe, speFit );
588     return;
589 }
590 //_________________________________________________________________________
591 Int_t AliITSClusterFinderSDD::NoLinearFit( Int_t xdim, Int_t zdim, 
592                                            Double_t *param, Double_t *spe, 
593                                            Int_t *niter, Double_t *chir ){
594     // fit method from Comput. Phys. Commun 46(1987) 149
595     const Double_t kchilmt = 0.01;  //        relative accuracy           
596     const Int_t   knel = 3;        //        for parabolic minimization  
597     const Int_t   knstop = 50;     //        Max. iteration number          
598     const Int_t   knParam = 5;
599     Int_t npeak = (Int_t)param[0];
600     // RETURN IF NUMBER OF DEGREES OF FREEDOM IS NOT POSITIVE 
601     if( (xdim*zdim - npeak*knParam) <= 0 ) return( -1 );
602     Double_t degFree = (xdim*zdim - npeak*knParam)-1;
603     Int_t   n, k, iterNum = 0;
604     Double_t *prm0 = new Double_t[npeak*knParam+1];
605     Double_t *step = new Double_t[npeak*knParam+1];
606     Double_t *schi = new Double_t[npeak*knParam+1]; 
607     Double_t *sprm[3];
608     sprm[0] = new Double_t[npeak*knParam+1];
609     sprm[1] = new Double_t[npeak*knParam+1];
610     sprm[2] = new Double_t[npeak*knParam+1];
611     Double_t  chi0, chi1, reldif, a, b, prmin, dp;
612     Double_t *speFit = new Double_t[ xdim*zdim ];
613     PeakFunc( xdim, zdim, param, speFit );
614     chi0 = ChiSqr( xdim, zdim, spe, speFit );
615     chi1 = chi0;
616     for( k=1; k<(npeak*knParam+1); k++) prm0[k] = param[k];
617         for( k=1 ; k<(npeak*knParam+1); k+=knParam ){
618             step[k] = param[k] / 20.0 ;
619             step[k+1] = param[k+1] / 50.0;
620             step[k+2] = param[k+2] / 50.0;                 
621             step[k+3] = param[k+3] / 20.0;                 
622             step[k+4] = param[k+4] / 20.0;                 
623         } // end for k
624     Int_t out = 0;
625     do{
626         iterNum++;
627             chi0 = chi1;
628             Minim( xdim, zdim, param, prm0, step, &chi1, spe, speFit );
629             reldif = ( chi1 > 0 ) ? ((Double_t) TMath::Abs( chi1-chi0)/chi1 ) : 0;
630         // EXIT conditions
631         if( reldif < (float) kchilmt ){
632             *chir  = (chi1>0) ? (float) TMath::Sqrt (chi1/degFree) :0;
633             *niter = iterNum;
634             out = 0;
635             break;
636         } // end if
637         if( (reldif < (float)(5*kchilmt)) && (iterNum > knstop) ){
638             *chir = (chi1>0) ?(float) TMath::Sqrt (chi1/degFree):0;
639             *niter = iterNum;
640             out = 0;
641             break;
642         } // end if
643         if( iterNum > 5*knstop ){
644             *chir  = (chi1>0) ?(float) TMath::Sqrt (chi1/degFree):0;
645             *niter = iterNum;
646             out = 1;
647             break;
648         } // end if
649         if( iterNum <= knel ) continue;
650         n = iterNum - (iterNum/knel)*knel; // EXTRAPOLATION LIMIT COUNTER N
651         if( n > 3 || n == 0 ) continue;
652         schi[n-1] = chi1;
653         for( k=1; k<(npeak*knParam+1); k++ ) sprm[n-1][k] = param[k];
654         if( n != 3 ) continue;
655         // -EVALUATE EXTRAPOLATED VALUE OF EACH PARAMETER BY FINDING MINIMUM OF
656         //    PARABOLA DEFINED BY LAST THREE CALLS OF MINIM
657         for( k=1; k<(npeak*knParam+1); k++ ){
658             Double_t tmp0 = sprm[0][k];
659             Double_t tmp1 = sprm[1][k];
660             Double_t tmp2 = sprm[2][k];
661             a  = schi[0]*(tmp1-tmp2) + schi[1]*(tmp2-tmp0);
662             a += (schi[2]*(tmp0-tmp1));
663             b  = schi[0]*(tmp1*tmp1-tmp2*tmp2);
664             b += (schi[1]*(tmp2*tmp2-tmp0*tmp0)+(schi[2]*
665                                              (tmp0*tmp0-tmp1*tmp1)));
666             if ((double)a < 1.0E-6) prmin = 0;
667             else prmin = (float) (0.5*b/a);
668             dp = 5*(tmp2-tmp0);
669             if( TMath::Abs(prmin-tmp2) > TMath::Abs(dp) ) prmin = tmp2+dp;
670             param[k] = prmin;
671             step[k]  = dp/10; // OPTIMIZE SEARCH STEP
672         } // end for k
673     } while( kTRUE );
674     delete [] prm0;
675     delete [] step;
676     delete [] schi; 
677     delete [] sprm[0];
678     delete [] sprm[1];
679     delete [] sprm[2];
680     delete [] speFit;
681     return( out );
682 }
683
684 //______________________________________________________________________
685 void AliITSClusterFinderSDD::ResolveClusters(){
686     // The function to resolve clusters if the clusters overlapping exists
687     Int_t i;
688     // get number of clusters for this module
689     Int_t nofClusters = NClusters();
690     nofClusters -= fNclusters;
691     Int_t fNofMaps = GetSeg()->Npz();
692     Int_t fNofAnodes = fNofMaps/2;
693     //Int_t fMaxNofSamples = GetSeg()->Npx();
694     Int_t dummy=0;
695     Double_t fTimeStep = GetSeg()->Dpx( dummy );
696     Double_t fSddLength = GetSeg()->Dx();
697     Double_t fDriftSpeed = GetResp(fModule)->GetDriftSpeed();
698     Double_t anodePitch = GetSeg()->Dpz( dummy );
699     Double_t n, baseline;
700     GetResp(fModule)->GetNoiseParam( n, baseline );
701     Int_t electronics =GetResp(fModule)->GetElectronics(); // 1 = PASCAL, 2 = OLA
702
703     for( Int_t j=0; j<nofClusters; j++ ){ 
704         // get cluster information
705         AliITSRawClusterSDD *clusterJ=(AliITSRawClusterSDD*) Cluster(j);
706         Int_t astart = clusterJ->Astart();
707         Int_t astop = clusterJ->Astop();
708         Int_t tstart = clusterJ->Tstartf();
709         Int_t tstop = clusterJ->Tstopf();
710         Int_t wing = (Int_t)clusterJ->W();
711         if( wing == 2 ){
712             astart += fNofAnodes; 
713             astop  += fNofAnodes;
714         } // end if 
715         Int_t xdim = tstop-tstart+3;
716         Int_t zdim = astop-astart+3;
717         if( xdim > 50 || zdim > 30 ) { 
718             Warning("ResolveClusters","xdim: %d , zdim: %d ",xdim,zdim);
719             continue;
720         }
721         Double_t *sp = new Double_t[ xdim*zdim+1 ];
722         memset( sp, 0, sizeof(Double_t)*(xdim*zdim+1) );
723         
724         // make a local map from cluster region
725         for( Int_t ianode=astart; ianode<=astop; ianode++ ){
726             for( Int_t itime=tstart; itime<=tstop; itime++ ){
727                 Double_t fadc = Map()->GetSignal( ianode, itime );
728                 if( fadc > baseline ) fadc -= (Double_t)baseline;
729                 else fadc = 0.;
730                 Int_t index = (itime-tstart+1)*zdim+(ianode-astart+1);
731                 sp[index] = fadc;
732             } // time loop
733         } // anode loop
734         
735         // search peaks on cluster
736         const Int_t kNp = 150;
737         Int_t peakX1[kNp];
738         Int_t peakZ1[kNp];
739         Double_t peakAmp1[kNp];
740         Int_t npeak = SearchPeak(sp,xdim,zdim,peakX1,peakZ1,peakAmp1,fMinPeak);
741
742         // if multiple peaks, split cluster
743         if( npeak >= 1 ){
744             //        cout << "npeak " << npeak << endl;
745             //        clusterJ->PrintInfo();
746             Double_t *par = new Double_t[npeak*5+1];
747             par[0] = (Double_t)npeak;                
748             // Initial parameters in cell dimentions
749             Int_t k1 = 1;
750             for( i=0; i<npeak; i++ ){
751                 par[k1] = peakAmp1[i];
752                 par[k1+1] = peakX1[i]; // local time pos. [timebin]
753                 par[k1+2] = peakZ1[i]; // local anode pos. [anodepitch]
754                 if( electronics == 1 ) par[k1+3] = 2.; // PASCAL
755                 else if(electronics==2) par[k1+3] = 0.7;//tau [timebin] OLA 
756                 par[k1+4] = .4;    // sigma        [anodepich]
757                 k1 += 5;
758             } // end for i                        
759             Int_t niter;
760             Double_t chir;                        
761             NoLinearFit( xdim, zdim, par, sp, &niter, &chir );
762             Double_t peakX[kNp];
763             Double_t peakZ[kNp];
764             Double_t sigma[kNp];
765             Double_t tau[kNp];
766             Double_t peakAmp[kNp];
767             Double_t integral[kNp];
768             //get integrals => charge for each peak
769             PeakFunc( xdim, zdim, par, sp, integral );
770             k1 = 1;
771             for( i=0; i<npeak; i++ ){
772                 peakAmp[i] = par[k1];
773                 peakX[i]   = par[k1+1];
774                 peakZ[i]   = par[k1+2];
775                 tau[i]     = par[k1+3];
776                 sigma[i]   = par[k1+4];
777                 k1+=5;
778             } // end for i
779             // calculate parameter for new clusters
780             for( i=0; i<npeak; i++ ){
781                 AliITSRawClusterSDD clusterI( *clusterJ );
782             
783                 Int_t newAnode = peakZ1[i]-1 + astart;
784
785             //    Int_t newiTime = peakX1[i]-1 + tstart;
786             //    Int_t shift = (Int_t)(fTimeCorr/fTimeStep + 0.5);
787             //    if( newiTime > shift && newiTime < (fMaxNofSamples-shift) ) 
788             //        shift = 0;
789             //    Int_t peakpos = Map()->GetHitIndex(newAnode,newiTime+shift );
790             //    clusterI.SetPeakPos( peakpos );
791             
792                 clusterI.SetPeakAmpl( peakAmp1[i] );
793                 Double_t newAnodef = peakZ[i] - 0.5 + astart;
794                 Double_t newiTimef = peakX[i] - 1 + tstart;
795                 if( wing == 2 ) newAnodef -= fNofAnodes; 
796                 Double_t anodePath = (newAnodef - fNofAnodes/2)*anodePitch;
797                 newiTimef *= fTimeStep;
798                 if( newiTimef > fTimeCorr ) newiTimef -= fTimeCorr;
799                 if( electronics == 1 ){
800                 //    newiTimef *= 0.999438;    // PASCAL
801                 //    newiTimef += (6./fDriftSpeed - newiTimef/3000.);
802                 }else if( electronics == 2 )
803                     newiTimef *= 0.99714;    // OLA
804                     
805                 Int_t timeBin = (Int_t)(newiTimef/fTimeStep+0.5);    
806                 Int_t peakpos = Map()->GetHitIndex( newAnode, timeBin );
807                 if( peakpos < 0 ) { 
808                     for( Int_t ii=0; ii<3; ii++ ) {
809                         peakpos = Map()->GetHitIndex( newAnode, timeBin+ii );
810                         if( peakpos > 0 ) break;
811                         peakpos = Map()->GetHitIndex( newAnode, timeBin-ii );
812                         if( peakpos > 0 ) break;
813                     }
814                 }
815                 
816                 if( peakpos < 0 ) { 
817                     //Warning("ResolveClusters",
818                     //        "Digit not found for cluster");
819                     //if(AliDebugLevel()>=3) clusterI.PrintInfo(); 
820                    continue;
821                 }
822                 clusterI.SetPeakPos( peakpos );    
823                 Double_t driftPath = fSddLength - newiTimef * fDriftSpeed;
824                 Double_t sign = ( wing == 1 ) ? -1. : 1.;
825                 clusterI.SetX( driftPath*sign * 0.0001 );        
826                 clusterI.SetZ( anodePath * 0.0001 );
827                 clusterI.SetAnode( newAnodef );
828                 clusterI.SetTime( newiTimef );
829                 clusterI.SetAsigma( sigma[i]*anodePitch );
830                 clusterI.SetTsigma( tau[i]*fTimeStep );
831                 clusterI.SetQ( integral[i] );
832                 
833                 fDetTypeRec->AddCluster( 1, &clusterI );
834             } // end for i
835             Clusters()->RemoveAt( j );
836             delete [] par;
837         } else {  // something odd
838             Warning( "ResolveClusters",
839                      "--- Peak not found!!!!  minpeak=%d ,cluster peak= %f"
840                      " , module= %d",
841                      fMinPeak, clusterJ->PeakAmpl(),GetModule()); 
842             clusterJ->PrintInfo();
843             Warning( "ResolveClusters"," xdim= %d zdim= %d", xdim-2, zdim-2 );
844         }
845         delete [] sp;
846     } // cluster loop
847     Clusters()->Compress();
848 //    Map()->ClearMap(); 
849 }
850 //________________________________________________________________________
851 void  AliITSClusterFinderSDD::GroupClusters(){
852     // group clusters
853     Int_t dummy=0;
854     Double_t fTimeStep = GetSeg()->Dpx(dummy);
855     // get number of clusters for this module
856     Int_t nofClusters = NClusters();
857     nofClusters -= fNclusters;
858     AliITSRawClusterSDD *clusterI;
859     AliITSRawClusterSDD *clusterJ;
860     Int_t *label = new Int_t [nofClusters];
861     Int_t i,j;
862     for(i=0; i<nofClusters; i++) label[i] = 0;
863     for(i=0; i<nofClusters; i++) { 
864         if(label[i] != 0) continue;
865         for(j=i+1; j<nofClusters; j++) { 
866             if(label[j] != 0) continue;
867             clusterI = (AliITSRawClusterSDD*) Cluster(i);
868             clusterJ = (AliITSRawClusterSDD*) Cluster(j);
869             // 1.3 good
870             if(clusterI->T() < fTimeStep*60) fDAnode = 4.2;  // TB 3.2  
871             if(clusterI->T() < fTimeStep*10) fDAnode = 1.5;  // TB 1.
872             Bool_t pair = clusterI->Brother(clusterJ,fDAnode,fDTime);
873             if(!pair) continue;
874             if(AliDebugLevel()>=4){
875                 clusterI->PrintInfo();
876                 clusterJ->PrintInfo();
877             } // end if AliDebugLevel
878             clusterI->Add(clusterJ);
879             label[j] = 1;
880             Clusters()->RemoveAt(j);
881             j=i; // <- Ernesto
882         } // J clusters  
883         label[i] = 1;
884     } // I clusters
885     Clusters()->Compress();
886
887     delete [] label;
888     return;
889 }
890 //________________________________________________________________________
891 void AliITSClusterFinderSDD::SelectClusters(){
892     // get number of clusters for this module
893     Int_t nofClusters = NClusters();
894
895     nofClusters -= fNclusters;
896     Int_t i;
897     for(i=0; i<nofClusters; i++) { 
898         AliITSRawClusterSDD *clusterI =(AliITSRawClusterSDD*) Cluster(i);
899         Int_t rmflg = 0;
900         Double_t wy = 0.;
901         if(clusterI->Anodes() != 0.) {
902             wy = ((Double_t) clusterI->Samples())/clusterI->Anodes();
903         } // end if
904         Int_t amp = (Int_t) clusterI->PeakAmpl();
905         Int_t cha = (Int_t) clusterI->Q();
906         if(amp < fMinPeak) rmflg = 1;  
907         if(cha < fMinCharge) rmflg = 1;
908         if(wy < fMinNCells) rmflg = 1;
909         //if(wy > fMaxNCells) rmflg = 1;
910         if(rmflg) Clusters()->RemoveAt(i);
911     } // I clusters
912     Clusters()->Compress();
913     return;
914 }
915
916 //______________________________________________________________________
917 void AliITSClusterFinderSDD::GetRecPoints(){
918     // get rec points
919   
920     // get number of clusters for this module
921     Int_t nofClusters = NClusters();
922     nofClusters -= fNclusters;
923     const Double_t kconvGeV = 1.e-6; // GeV -> KeV
924     const Double_t kconv = 1.0e-4; 
925     const Double_t kRMSx = 38.0*kconv; // microns->cm ITS TDR Table 1.3
926     const Double_t kRMSz = 28.0*kconv; // microns->cm ITS TDR Table 1.3
927     Int_t i;
928     Int_t ix, iz, idx=-1;
929     AliITSdigitSDD *dig=0;
930     Int_t ndigits=NDigits();
931
932     Int_t lay,lad,det;
933     fDetTypeRec->GetITSgeom()->GetModuleId(fModule,lay,lad,det);
934     Int_t ind=(lad-1)*fDetTypeRec->GetITSgeom()->GetNdetectors(lay)+(det-1);
935     Int_t lyr=(lay-1);
936
937
938     for(i=0; i<nofClusters; i++) { 
939         AliITSRawClusterSDD *clusterI = (AliITSRawClusterSDD*)Cluster(i);
940         if(!clusterI) Error("SDD: GetRecPoints","i clusterI ",i,clusterI);
941         if(clusterI) idx=clusterI->PeakPos();
942         if(idx>ndigits) Error("SDD: GetRecPoints","idx ndigits",idx,ndigits);
943         // try peak neighbours - to be done 
944         if(idx&&idx<= ndigits) dig =(AliITSdigitSDD*)GetDigit(idx);
945         if(!dig) {
946             // try cog
947             GetSeg()->GetPadIxz(clusterI->X(),clusterI->Z(),ix,iz);
948             dig = (AliITSdigitSDD*)Map()->GetHit(iz-1,ix-1);
949             // if null try neighbours
950             if (!dig) dig = (AliITSdigitSDD*)Map()->GetHit(iz-1,ix); 
951             if (!dig) dig = (AliITSdigitSDD*)Map()->GetHit(iz-1,ix+1); 
952             if (!dig) printf("SDD: cannot assign the track number!\n");
953         } //  end if !dig
954         AliITSRecPoint rnew(fDetTypeRec->GetITSgeom());
955         rnew.SetXZ(fModule,clusterI->X(),clusterI->Z());
956         rnew.SetQ(clusterI->Q());   // in KeV - should be ADC
957         rnew.SetdEdX(kconvGeV*clusterI->Q());
958         rnew.SetSigmaDetLocX2(kRMSx*kRMSx);
959         rnew.SetSigmaZ2(kRMSz*kRMSz);
960
961         if(dig) rnew.SetLabel(dig->GetTrack(0),0);
962         if(dig) rnew.SetLabel(dig->GetTrack(1),1);
963         if(dig) rnew.SetLabel(dig->GetTrack(2),2);
964         rnew.SetDetectorIndex(ind);
965         rnew.SetLayer(lyr);
966         fDetTypeRec->AddRecPoint(rnew);        
967     } // I clusters
968 //    Map()->ClearMap();
969 }
970 //______________________________________________________________________
971 void AliITSClusterFinderSDD::FindRawClusters(Int_t mod){
972     // find raw clusters
973     
974     SetModule(mod);
975     Find1DClustersE();
976     GroupClusters();
977     SelectClusters();
978     ResolveClusters();
979     GetRecPoints();
980 }
981 //_______________________________________________________________________
982 void AliITSClusterFinderSDD::PrintStatus() const{
983     // Print SDD cluster finder Parameters
984
985     cout << "**************************************************" << endl;
986     cout << " Silicon Drift Detector Cluster Finder Parameters " << endl;
987     cout << "**************************************************" << endl;
988     cout << "Number of Clusters: " << fNclusters << endl;
989     cout << "Anode Tolerance: " << fDAnode << endl;
990     cout << "Time  Tolerance: " << fDTime << endl;
991     cout << "Time  correction (electronics): " << fTimeCorr << endl;
992     cout << "Cut Amplitude (threshold): " << fCutAmplitude << endl;
993     cout << "Minimum Amplitude: " << fMinPeak << endl;
994     cout << "Minimum Charge: " << fMinCharge << endl;
995     cout << "Minimum number of cells/clusters: " << fMinNCells << endl;
996     cout << "Maximum number of cells/clusters: " << fMaxNCells << endl;
997     cout << "**************************************************" << endl;
998 }