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