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