]> git.uio.no Git - u/mrichter/AliRoot.git/blob - ITS/AliITSsimulationSDD.cxx
Changes needed in ths SDD simulation, and bug fixes.
[u/mrichter/AliRoot.git] / ITS / AliITSsimulationSDD.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
17 #include <iostream.h>
18 #include <stdlib.h>
19 #include <stdio.h>
20 #include <TStopwatch.h>
21 #include <TCanvas.h>
22 #include <TF1.h>
23 #include <TRandom.h>
24 #include <string.h>
25
26
27 #include "AliRun.h"
28 #include "AliITS.h"
29 #include "AliITShit.h"
30 #include "AliITSdigit.h"
31 #include "AliITSmodule.h"
32 #include "AliITSMapA1.h"
33 #include "AliITSMapA2.h"
34 #include "AliITSsimulationSDD.h"
35 #include "AliITSetfSDD.h"
36 #include "AliITSRawData.h"
37 #include "AliITSHuffman.h"
38 #include "AliITSsegmentation.h"
39 #include "AliITSresponse.h"
40
41 ClassImp(AliITSsimulationSDD)
42 ////////////////////////////////////////////////////////////////////////
43 // Version: 0
44 // Written by Piergiorgio Cerello
45 // November 23 1999
46 //
47 // AliITSsimulationSDD is the simulation of SDDs.
48   //
49 //Begin_Html
50 /*
51 <img src="picts/ITS/AliITShit_Class_Diagram.gif">
52 </pre>
53 <br clear=left>
54 <font size=+2 color=red>
55 <p>This show the relasionships between the ITS hit class and the rest of Aliroot.
56 </font>
57 <pre>
58 */
59 //End_Html
60 //_____________________________________________________________________________
61
62 Int_t power(Int_t b, Int_t e) {
63   // compute b to the e power, where both b and e are Int_ts.
64   Int_t power = 1,i;
65   for(i=0; i<e; i++) power *= b;
66   return power;
67 }
68
69 //_____________________________________________
70
71 void FastFourierTransform(AliITSetfSDD *alisddetf,Double_t *real,
72                           Double_t *imag,Int_t direction) {
73   // Do a Fast Fourier Transform
74   //printf("FFT: direction %d\n",direction);
75
76   Int_t samples = alisddetf->GetSamples();
77   Int_t l = (Int_t) ((log((Float_t) samples)/log(2.))+0.5);
78   Int_t m1 = samples;
79   Int_t m  = samples/2;
80   Int_t m2 = samples/m1;
81   Int_t i,j,k;
82   for(i=1; i<=l; i++) {
83     for(j=0; j<samples; j += m1) {
84       Int_t p = 0;
85       for(k=j; k<= j+m-1; k++) {
86         Double_t wsr = alisddetf->GetWeightReal(p);
87         Double_t wsi = alisddetf->GetWeightImag(p);
88         if(direction == -1) wsi = -wsi;
89         Double_t xr = *(real+k+m);
90         Double_t xi = *(imag+k+m);
91         *(real+k+m) = wsr*(*(real+k)-xr) - wsi*(*(imag+k)-xi);
92         *(imag+k+m) = wsr*(*(imag+k)-xi) + wsi*(*(real+k)-xr);
93         *(real+k) += xr;
94         *(imag+k) += xi;
95         p += m2;
96       }
97     }
98     m1 = m;
99     m /= 2;
100     m2 += m2;
101   } 
102   
103   for(j=0; j<samples; j++) {
104     Int_t j1 = j;
105     Int_t p = 0;
106     Int_t i1;
107     for(i1=1; i1<=l; i1++) {
108       Int_t j2 = j1;
109       j1 /= 2;
110       p = p + p + j2 - j1 - j1;
111     }
112     if(p >= j) {
113       Double_t xr = *(real+j);
114       Double_t xi = *(imag+j);
115       *(real+j) = *(real+p);
116       *(imag+j) = *(imag+p);
117       *(real+p) = xr;
118       *(imag+p) = xi;
119     }
120   }
121   if(direction == -1) {
122     for(i=0; i<samples; i++) {
123       *(real+i) /= samples;
124       *(imag+i) /= samples;
125     }
126   }
127   return;
128 }
129 //_____________________________________________________________________________
130
131 AliITSsimulationSDD::AliITSsimulationSDD(){
132   // Default constructor
133
134   fResponse = 0;
135   fSegmentation = 0;
136   fHis = 0;
137   fHitMap1 = 0;
138   fHitMap2 = 0;
139   fElectronics = 0;
140   fStream = 0;
141   fD.Set(0);
142   fT1.Set(0);
143   fT2.Set(0);
144   fTol.Set(0);
145   fNoise.Set(0);
146   fBaseline.Set(0);
147   SetScaleFourier();
148   SetPerpendTracksFlag();
149   SetDoFFT();
150   SetCheckNoise();
151   fInZR = 0;
152   fInZI = 0;
153   fOutZR = 0;
154   fOutZI = 0;
155   fNofMaps = 0;
156   fMaxNofSamples = 0;
157   fITS = 0;
158   fTreeB=0;
159 }
160 //_____________________________________________________________________________
161 AliITSsimulationSDD::AliITSsimulationSDD(AliITSsimulationSDD &source)
162 {
163   // Copy constructor to satify Coding roules only.
164   if(this==&source) return;
165   printf("Not allowed to make a copy of AliITSsimulationSDD "
166          "Using default creater instead\n");
167   AliITSsimulationSDD();
168 }
169 //_____________________________________________________________________________
170 AliITSsimulationSDD& AliITSsimulationSDD::operator=(AliITSsimulationSDD &source)
171 {
172   // Assignment operator to satify Coding roules only.
173   if(this==&source) return *this;
174   printf("Not allowed to make a = with AliITSsimulationSDD "
175          "Using default creater instead\n");
176   return *this ;
177 }
178 //_____________________________________________________________________________
179
180 AliITSsimulationSDD::AliITSsimulationSDD(AliITSsegmentation *seg,AliITSresponse *resp) 
181 {
182   // Standard Constructor
183
184       fHis=0;
185       fTreeB=0;
186       fResponse = resp;
187       fSegmentation = seg;
188       SetScaleFourier();
189       SetPerpendTracksFlag();
190       SetDoFFT();
191       SetCheckNoise();
192
193       fHitMap2 = new AliITSMapA2(fSegmentation,fScaleSize,1);
194       fHitMap1 = new AliITSMapA1(fSegmentation);
195
196       //
197       fNofMaps=fSegmentation->Npz();
198       fMaxNofSamples=fSegmentation->Npx();
199
200       Float_t sddLength = fSegmentation->Dx();
201       Float_t sddWidth = fSegmentation->Dz();
202
203       Int_t dummy=0;
204       Float_t anodePitch = fSegmentation->Dpz(dummy);
205       Double_t timeStep = (Double_t)fSegmentation->Dpx(dummy);
206       Float_t driftSpeed=fResponse->DriftSpeed();    
207
208       if(anodePitch*(fNofMaps/2) > sddWidth) {
209          Warning("AliITSsimulationSDD",
210            "Too many anodes %d or too big pitch %f \n",fNofMaps/2,anodePitch);
211       }
212
213       if(timeStep*fMaxNofSamples < sddLength/driftSpeed) {
214          Error("AliITSsimulationSDD",
215                              "Time Interval > Allowed Time Interval: exit\n");
216          return;
217       }
218
219       fElectronics = new AliITSetfSDD(timeStep/fScaleSize);
220
221       char opt1[20], opt2[20];
222       fResponse->ParamOptions(opt1,opt2);
223       fParam=opt2;
224       char *same = strstr(opt1,"same");
225       if (same) {
226          fNoise.Set(0);
227          fBaseline.Set(0);
228       } else {
229          fNoise.Set(fNofMaps);
230          fBaseline.Set(fNofMaps);
231       }
232       
233       //
234       const char *kopt=fResponse->ZeroSuppOption();
235         if (strstr(fParam,"file") ) {
236           fD.Set(fNofMaps);
237           fT1.Set(fNofMaps);
238           if (strstr(kopt,"2D")) {
239             fT2.Set(fNofMaps);
240             fTol.Set(0);
241             Init2D();       // desactivate if param change module by module
242           } else if(strstr(kopt,"1D"))  {
243             fT2.Set(2);
244             fTol.Set(2);
245             Init1D();      // desactivate if param change module by module
246           }
247         } else {
248           fD.Set(2);
249           fTol.Set(2);
250           fT1.Set(2);
251           fT2.Set(2);
252           SetCompressParam();
253         }
254
255
256         Bool_t write=fResponse->OutputOption();
257         if(write && strstr(kopt,"2D")) MakeTreeB();
258
259         // call here if baseline does not change by module
260         // ReadBaseline();
261
262         fITS = (AliITS*)gAlice->GetModule("ITS");
263         Int_t size=fNofMaps*fMaxNofSamples;
264         fStream = new AliITSInStream(size); 
265         
266         fInZR = new Double_t [fScaleSize*fMaxNofSamples];
267         fInZI = new Double_t [fScaleSize*fMaxNofSamples];
268         fOutZR = new Double_t [fScaleSize*fMaxNofSamples];
269         fOutZI = new Double_t [fScaleSize*fMaxNofSamples];  
270
271 }
272
273
274 //_____________________________________________________________________________
275
276 AliITSsimulationSDD::~AliITSsimulationSDD() { 
277   // destructor
278
279   delete fHitMap1;
280   delete fHitMap2;
281   delete fStream;
282   delete fElectronics;
283
284   fD.Set(0);
285   fT1.Set(0);
286   fT2.Set(0);
287   fTol.Set(0);
288   fNoise.Set(0);
289   fBaseline.Set(0);
290   fITS = 0;
291
292   if (fHis) {
293      fHis->Delete(); 
294      delete fHis;     
295   }     
296   if(fTreeB) delete fTreeB;           
297   if(fInZR) delete [] fInZR;
298   if(fInZI) delete [] fInZI;    
299   if(fOutZR) delete [] fOutZR;
300   if(fOutZI) delete [] fOutZI;
301 }
302 //_____________________________________________________________________________
303
304 void AliITSsimulationSDD::DigitiseModule(AliITSmodule *mod,Int_t md,Int_t ev){
305   // create maps to build the lists of tracks
306   // for each digit
307
308     fModule=md;
309     fEvent=ev;
310
311     TObjArray *fHits = mod->GetHits();
312     Int_t nhits = fHits->GetEntriesFast();
313     if (!nhits && fCheckNoise) {
314         ChargeToSignal();
315         GetNoise();
316         fHitMap2->ClearMap();
317         return;
318     } else if (!nhits) return;
319
320     //printf("simSDD: module nhits %d %d\n",md,nhits);
321
322
323     TObjArray *list=new TObjArray;
324     static TClonesArray *padr=0;
325     if(!padr) padr=new TClonesArray("TVector",1000);
326     Int_t arg[6] = {0,0,0,0,0,0}; 
327     fHitMap1->SetArray(list);
328
329
330     Int_t nofAnodes=fNofMaps/2;
331
332     Float_t sddLength = fSegmentation->Dx();
333     Float_t sddWidth = fSegmentation->Dz();
334
335     Int_t dummy=0;
336     Float_t anodePitch = fSegmentation->Dpz(dummy);
337     Float_t timeStep = fSegmentation->Dpx(dummy);
338
339     Float_t driftSpeed=fResponse->DriftSpeed();    
340
341     // Piergiorgio's part (apart for few variables which I made float
342     // when i thought that can be done
343
344     // Fill detector maps with GEANT hits
345     // loop over hits in the module
346
347     const Float_t kconv=1.0e+6;  // GeV->KeV
348     Int_t ii;
349     Int_t idhit=-1;
350     for(ii=0; ii<nhits; ii++) {
351         AliITShit *hit = (AliITShit*) fHits->At(ii);
352         Float_t xL[3];
353         hit = (AliITShit*) fHits->At(ii);
354         hit->GetPositionL(xL[0],xL[1],xL[2]);
355         Int_t hitDetector = hit->GetDetector();
356
357         if(hit->StatusEntering()) idhit=ii;
358
359         // Deposited energy in keV
360         Float_t avpath = 0.;
361         Float_t avanod = 0.;
362         Float_t depEnergy = kconv*hit->GetIonization();
363         AliITShit *hit1 = 0;
364         if(depEnergy != 0.) continue;
365
366         ii++;
367         Float_t xL1[3];
368         hit1 = (AliITShit*) fHits->At(ii);
369         hit1->GetPositionL(xL1[0],xL1[1],xL1[2]);
370         avpath = xL1[0];
371         avanod = xL1[2];
372         depEnergy = kconv*hit1->GetIonization();
373         
374         // added 11.09.2000 - continue if the particle did not lose energy
375         // passing through detector
376         if (!depEnergy) {
377           printf("This particle has passed without losing energy!\n");
378           continue;
379         }
380         // end add
381
382         // scale path to simulate a perpendicular track
383         if (fFlag) {
384           Float_t lC[3];
385           hit->GetPositionL(lC[0],lC[1],lC[2]);
386           Float_t lC1[3];
387           hit1->GetPositionL(lC1[0],lC1[1],lC1[2]);
388           Float_t pathInSDD = TMath::Sqrt((lC[0]-lC1[0])*(lC[0]-lC1[0])+(lC[1]-lC1[1])*(lC[1]-lC1[1])+(lC[2]-lC1[2])*(lC[2]-lC1[2]));
389           if(pathInSDD) depEnergy *= (0.03/pathInSDD);
390         }
391
392         Float_t avDrft = xL[0]+avpath;
393         Float_t avAnode = xL[2]+avanod;
394
395         if(avpath != 0.) avDrft /= 2.;
396         if(avanod != 0.) avAnode /= 2.;
397
398         Float_t driftPath = 10000.*avDrft;
399         Int_t iWing = 2;
400         if(driftPath < 0) {
401           iWing = 1;
402           driftPath = -driftPath;
403         }
404         driftPath = sddLength-driftPath;
405         Int_t detector = 2*(hitDetector-1) + iWing;
406         if(driftPath < 0) {
407           cout << "Warning: negative drift path " << driftPath << endl;
408           continue;
409         }
410          
411         //   Drift Time
412         Float_t driftTime = driftPath/driftSpeed;
413         Int_t timeSample = (Int_t) (fScaleSize*driftTime/timeStep + 1);
414         if(timeSample > fScaleSize*fMaxNofSamples) {
415           cout << "Warning: Wrong Time Sample: " << timeSample << endl;
416           continue;
417         }
418
419         //   Anode
420         Float_t xAnode = 10000.*(avAnode)/anodePitch + nofAnodes/2;  // +1?
421         if((xAnode+1)*anodePitch > sddWidth || xAnode*anodePitch < 0.) 
422              { cout << "Warning: Z = " << xAnode*anodePitch << endl; }
423         Int_t iAnode = (Int_t) (1.+xAnode); // xAnode?
424         if(iAnode < 0 || iAnode > nofAnodes) {
425           cout << "Warning: Wrong iAnode: " << iAnode << endl;
426           continue;
427         } 
428
429
430         // work with the idtrack=entry number in the TreeH for the moment
431         //Int_t idhit,idtrack;
432         //mod->GetHitTrackAndHitIndex(ii,idtrack,idhit);    
433         //Int_t idtrack=mod->GetHitTrackIndex(ii);  
434         // or store straight away the particle position in the array
435         // of particles and take idhit=ii only when part is entering (this
436         // requires FillModules() in the macro for analysis) : 
437         Int_t itrack = hit->GetTrack();
438
439         //  Signal 2d Shape
440         Float_t diffCoeff, s0;
441         fResponse->DiffCoeff(diffCoeff,s0);
442     
443         // Squared Sigma along the anodes
444         Double_t sigma2A = 2.*diffCoeff*driftTime+s0*s0;
445         Double_t sigmaA  = TMath::Sqrt(sigma2A);
446         Double_t sigmaT  = sigmaA/driftSpeed;
447     
448         // Peak amplitude in nanoAmpere
449         Double_t eVpairs = 3.6;
450         Double_t amplitude = fScaleSize*160.*depEnergy/(timeStep*eVpairs*2.*acos(-1.)*sigmaT*sigmaA);
451     
452         Float_t nsigma=fResponse->NSigmaIntegration();
453         // Spread the charge 
454         // Pixel index
455         Int_t ja = iAnode;
456         Int_t jt = timeSample;
457         // Sub-pixel index
458         Int_t nsplit = 4; // hard-wired
459         nsplit = (nsplit+1)/2*2;
460         // Sub-pixel size
461         Double_t aStep = anodePitch/(nsplit*fScaleSize);
462         Double_t tStep = timeStep/(nsplit*fScaleSize);
463         // Define SDD window corresponding to the hit
464         Int_t anodeWindow = (Int_t) (fScaleSize*nsigma*sigmaA/anodePitch + 1);
465         Int_t timeWindow = (Int_t) (fScaleSize*nsigma*sigmaT/timeStep + 1);
466         Int_t jamin = (ja - anodeWindow/2 - 1)*fScaleSize*nsplit + 1;
467         Int_t jamax = (ja + anodeWindow/2)*fScaleSize*nsplit;
468         if(jamin <= 0) jamin = 1;
469         if(jamax > fScaleSize*nofAnodes*nsplit) jamax = fScaleSize*nofAnodes*nsplit;
470         Int_t jtmin = (jt - timeWindow*3 - 1)*nsplit + 1; //hard-wired
471         Int_t jtmax = (jt + timeWindow*3)*nsplit; //hard-wired
472         if(jtmin <= 0) jtmin = 1;
473         if(jtmax > fScaleSize*fMaxNofSamples*nsplit) jtmax = fScaleSize*fMaxNofSamples*nsplit;
474
475         Double_t rlAnode = log(aStep*amplitude);
476
477         // Spread the charge in the anode-time window
478         Int_t ka;
479         for(ka=jamin; ka <=jamax; ka++) {
480           Int_t ia = (ka-1)/(fScaleSize*nsplit) + 1;
481           if(ia <= 0) { cout << "Warning: ia < 1: " << endl; continue; }
482           if(ia > nofAnodes) ia = nofAnodes;
483           Double_t aExpo = (aStep*(ka-0.5)-xAnode*anodePitch)/sigmaA;
484           Double_t anodeAmplitude = rlAnode - 0.5*aExpo*aExpo;
485           // Protect against overflows
486           if(anodeAmplitude > -87.3)
487             anodeAmplitude = exp(anodeAmplitude);
488           else
489             anodeAmplitude = 0;
490           Int_t index = ((detector+1)%2)*nofAnodes+ia-1; // index starts from 0
491           if(anodeAmplitude) {
492             Double_t rlTime = log(tStep*anodeAmplitude);
493             Int_t kt;
494             for(kt=jtmin; kt<=jtmax; kt++) {
495               Int_t it = (kt-1)/nsplit+1;  // it starts from 1
496               if(it<=0) { cout << "Warning: it < 1: " << endl; continue; } 
497               if(it>fScaleSize*fMaxNofSamples) it = fScaleSize*fMaxNofSamples;
498               Double_t tExpo = (tStep*(kt-0.5)-driftTime)/sigmaT;
499               Double_t timeAmplitude = rlTime - 0.5*tExpo*tExpo;
500               // Protect against overflows
501               if(timeAmplitude > -87.3){
502                 timeAmplitude = exp(timeAmplitude);
503               } else
504                 timeAmplitude = 0;
505
506               // build the list of digits for this module       
507               arg[0]=index;
508               arg[1]=it;
509               arg[2]=itrack;
510               arg[3]=idhit;
511               ListOfFiredCells(arg,timeAmplitude,list,padr);
512         } // loop over time in window 
513       } // end if anodeAmplitude
514     } // loop over anodes in window
515   } // end loop over hits
516
517   // introduce the electronics effects and do zero-suppression if required
518   Int_t nentries=list->GetEntriesFast();
519   if (nentries) {
520
521     //TStopwatch timer;
522     ChargeToSignal(); 
523     //timer.Stop(); timer.Print();
524
525     const char *kopt=fResponse->ZeroSuppOption();
526     ZeroSuppression(kopt);
527   } 
528
529   // clean memory
530   list->Delete();
531   delete list; 
532                       
533   padr->Delete(); 
534
535   fHitMap1->ClearMap();
536   fHitMap2->ClearMap();
537
538   //gObjectTable->Print();
539 }
540
541
542 //____________________________________________
543
544 void AliITSsimulationSDD::ListOfFiredCells(Int_t *arg,Double_t timeAmplitude,
545                                            TObjArray *list,TClonesArray *padr){
546   // Returns the list of "fired" cells.
547
548                     Int_t index=arg[0];
549                     Int_t ik=arg[1];
550                     Int_t idtrack=arg[2];
551                     Int_t idhit=arg[3];
552                     Int_t counter=arg[4];
553                     Int_t countadr=arg[5];
554                    
555                     Double_t charge=timeAmplitude;
556                     charge += fHitMap2->GetSignal(index,ik-1);
557                     fHitMap2->SetHit(index, ik-1, charge);
558
559                     Int_t digits[3];
560                     Int_t it=(Int_t)((ik-1)/fScaleSize);
561                     
562                     digits[0]=index;
563                     digits[1]=it;
564                     digits[2]=(Int_t)timeAmplitude;
565                     Float_t phys;
566                     if (idtrack >= 0) phys=(Float_t)timeAmplitude;
567                     else phys=0;
568                    
569                     Double_t cellcharge=0.;
570                     AliITSTransientDigit* pdigit;
571                     // build the list of fired cells and update the info
572                     if (!fHitMap1->TestHit(index, it)) {
573                       
574                         new((*padr)[countadr++]) TVector(3);
575                         TVector &trinfo=*((TVector*) (*padr)[countadr-1]);
576                         trinfo(0)=(Float_t)idtrack;
577                         trinfo(1)=(Float_t)idhit;
578                         trinfo(2)=(Float_t)timeAmplitude;
579
580                         list->AddAtAndExpand(
581                             new AliITSTransientDigit(phys,digits),counter);
582                         
583                         fHitMap1->SetHit(index, it, counter);
584                         counter++;
585                         pdigit=(AliITSTransientDigit*)list->
586                                                       At(list->GetLast());
587                         // list of tracks
588                         TObjArray *trlist=(TObjArray*)pdigit->TrackList();
589                         trlist->Add(&trinfo);
590
591                     } else {
592                         pdigit=
593                          (AliITSTransientDigit*) fHitMap1->GetHit(index, it);
594                         for(Int_t kk=0;kk<fScaleSize;kk++) {
595                           cellcharge += fHitMap2->GetSignal(index,fScaleSize*it+kk);
596                         }
597                         // update charge
598                         (*pdigit).fSignal=(Int_t)cellcharge;
599                         (*pdigit).fPhysics+=phys;                       
600                         // update list of tracks
601                         TObjArray* trlist=(TObjArray*)pdigit->TrackList();
602                         Int_t lastentry=trlist->GetLast();
603                         TVector *ptrkp=(TVector*)trlist->At(lastentry);
604                         TVector &trinfo=*ptrkp;
605                         Int_t lasttrack=Int_t(trinfo(0));
606                         //Int_t lasthit=Int_t(trinfo(1));
607                         Float_t lastcharge=(trinfo(2));
608                         
609                         if (lasttrack==idtrack ) {
610                             lastcharge+=(Float_t)timeAmplitude;
611                             trlist->RemoveAt(lastentry);
612                             trinfo(0)=lasttrack;
613                             //trinfo(1)=lasthit; // or idhit
614                             trinfo(1)=idhit;
615                             trinfo(2)=lastcharge;
616                             trlist->AddAt(&trinfo,lastentry);
617                         } else {
618                           
619                             new((*padr)[countadr++]) TVector(3);
620                             TVector &trinfo=*((TVector*) (*padr)[countadr-1]);
621                             trinfo(0)=(Float_t)idtrack;
622                             trinfo(1)=(Float_t)idhit;
623                             trinfo(2)=(Float_t)timeAmplitude;
624                           
625                             trlist->Add(&trinfo);
626                         }
627
628 #ifdef print
629                         // check the track list - debugging
630                         Int_t trk[20], htrk[20];
631                         Float_t chtrk[20];  
632                         Int_t nptracks=trlist->GetEntriesFast();
633                         if (nptracks > 2) {
634                             Int_t tr;
635                             for (tr=0;tr<nptracks;tr++) {
636                                 TVector *pptrkp=(TVector*)trlist->At(tr);
637                                 TVector &pptrk=*pptrkp;
638                                 trk[tr]=Int_t(pptrk(0));
639                                 htrk[tr]=Int_t(pptrk(1));
640                                 chtrk[tr]=(pptrk(2));
641                                 printf("nptracks %d \n",nptracks);
642                                 // set printings
643                             }
644                         } // end if nptracks
645 #endif
646                     } //  end if pdigit
647
648                     arg[4]=counter;
649                     arg[5]=countadr;
650
651
652 }
653
654
655 //____________________________________________
656
657 void AliITSsimulationSDD::AddDigit(Int_t i, Int_t j, Int_t signal){
658   // Adds a Digit.
659     // tag with -1 signals coming from background tracks
660     // tag with -2 signals coming from pure electronic noise
661
662     Int_t digits[3], tracks[3], hits[3];
663     Float_t phys, charges[3];
664
665     Int_t trk[20], htrk[20];
666     Float_t chtrk[20];  
667
668     Bool_t do10to8=fResponse->Do10to8();
669
670     if(do10to8) signal=Convert8to10(signal); 
671     AliITSTransientDigit *obj = (AliITSTransientDigit*)fHitMap1->GetHit(i,j);
672     digits[0]=i;
673     digits[1]=j;
674     digits[2]=signal;
675     if (!obj) {
676         phys=0;
677         Int_t k;
678         for (k=0;k<3;k++) {
679           tracks[k]=-2;
680           charges[k]=0;
681           hits[k]=-1;
682         }
683         fITS->AddSimDigit(1,phys,digits,tracks,hits,charges); 
684     } else {
685       phys=obj->fPhysics;
686       TObjArray* trlist=(TObjArray*)obj->TrackList();
687       Int_t nptracks=trlist->GetEntriesFast();
688
689       if (nptracks > 20) {
690          cout<<"Attention - nptracks > 20 "<<nptracks<<endl;
691          nptracks=20;
692       }
693       Int_t tr;
694       for (tr=0;tr<nptracks;tr++) {
695           TVector &pp  =*((TVector*)trlist->At(tr));
696           trk[tr]=Int_t(pp(0));
697           htrk[tr]=Int_t(pp(1));
698           chtrk[tr]=(pp(2));
699       }
700       if (nptracks > 1) {
701         //printf("nptracks > 2  -- %d\n",nptracks);
702           SortTracks(trk,chtrk,htrk,nptracks);
703       }
704       Int_t i;
705       if (nptracks < 3 ) {
706          for (i=0; i<nptracks; i++) {
707              tracks[i]=trk[i];
708              charges[i]=chtrk[i];
709              hits[i]=htrk[i];
710          }
711          for (i=nptracks; i<3; i++) {
712              tracks[i]=-3;
713              hits[i]=-1;
714              charges[i]=0;
715          }
716       } else {
717          for (i=0; i<3; i++) {
718              tracks[i]=trk[i];
719              charges[i]=chtrk[i];
720              hits[i]=htrk[i];
721          }
722       }
723
724       fITS->AddSimDigit(1,phys,digits,tracks,hits,charges); 
725  
726     }
727
728 }
729
730 //____________________________________________
731
732 void AliITSsimulationSDD::SortTracks(Int_t *tracks,Float_t *charges,Int_t *hits,Int_t ntr){
733   //
734   // Sort the list of tracks contributing to a given digit
735   // Only the 3 most significant tracks are acctually sorted
736   //
737   
738   //
739   //  Loop over signals, only 3 times
740   //
741
742   
743   Float_t qmax;
744   Int_t jmax;
745   Int_t idx[3] = {-3,-3,-3};
746   Float_t jch[3] = {-3,-3,-3};
747   Int_t jtr[3] = {-3,-3,-3};
748   Int_t jhit[3] = {-3,-3,-3};
749   Int_t i,j,imax;
750   
751   if (ntr<3) imax=ntr;
752   else imax=3;
753   for(i=0;i<imax;i++){
754     qmax=0;
755     jmax=0;
756     
757     for(j=0;j<ntr;j++){
758       
759       if((i == 1 && j == idx[i-1] )
760          ||(i == 2 && (j == idx[i-1] || j == idx[i-2]))) continue;
761       
762       if(charges[j] > qmax) {
763         qmax = charges[j];
764         jmax=j;
765       }       
766     } 
767     
768     if(qmax > 0) {
769       idx[i]=jmax;
770       jch[i]=charges[jmax]; 
771       jtr[i]=tracks[jmax]; 
772       jhit[i]=hits[jmax]; 
773     }
774     
775   } 
776   
777   for(i=0;i<3;i++){
778     if (jtr[i] == -3) {
779          charges[i]=0;
780          tracks[i]=-3;
781          hits[i]=-1;
782     } else {
783          charges[i]=jch[i];
784          tracks[i]=jtr[i];
785          hits[i]=jhit[i];
786     }
787   }
788
789 }
790 //____________________________________________
791 void AliITSsimulationSDD::ChargeToSignal() {
792   // add baseline, noise, electronics and ADC saturation effects
793
794
795   Float_t maxadc = fResponse->MaxAdc();    
796   Float_t topValue = fResponse->MagicValue();
797   Float_t norm = maxadc/topValue;
798
799   char opt1[20], opt2[20];
800   fResponse->ParamOptions(opt1,opt2);
801   char *read = strstr(opt1,"file");
802
803   Float_t baseline, noise; 
804
805   if (read) {
806       static Bool_t readfile=kTRUE;
807       //read baseline and noise from file
808       if (readfile) ReadBaseline();
809       readfile=kFALSE;
810   } else fResponse->GetNoiseParam(noise,baseline);
811
812   Float_t contrib=0;
813
814   TRandom random; 
815   Int_t i,k,kk; 
816
817   if(!fDoFFT) {
818     for (i=0;i<fNofMaps;i++) {
819         if  (read && i<fNofMaps) GetAnodeBaseline(i,baseline,noise);
820         for(k=0; k<fScaleSize*fMaxNofSamples; k++) {
821            fInZR[k] = fHitMap2->GetSignal(i,k);
822            contrib = baseline + noise*random.Gaus();
823            fInZR[k] += contrib;
824         }
825         for(k=0; k<fMaxNofSamples; k++) {
826            Float_t newcont = 0.;
827            Float_t maxcont = 0.;
828            for(kk=0;kk<fScaleSize;kk++) {
829              newcont = fInZR[fScaleSize*k+kk];
830              if(newcont > maxcont) maxcont = newcont;
831            }
832            newcont = maxcont;
833            Double_t signal = newcont*norm;
834            if (signal >= maxadc) signal = maxadc -1;
835            // back to analog: ?
836            signal /=norm;
837            fHitMap2->SetHit(i,k,signal);
838         }  
839     } // loop over anodes
840     return;
841   } // end if DoFFT
842
843   for (i=0;i<fNofMaps;i++) {
844       if  (read && i<fNofMaps) GetAnodeBaseline(i,baseline,noise);
845       for(k=0; k<fScaleSize*fMaxNofSamples; k++) {
846         fInZR[k] = fHitMap2->GetSignal(i,k);
847         contrib = baseline + noise*random.Gaus();
848         fInZR[k] += contrib;
849         fInZI[k] = 0.;
850       }
851       FastFourierTransform(fElectronics,&fInZR[0],&fInZI[0],1);
852       for(k=0; k<fScaleSize*fMaxNofSamples; k++) {
853         Double_t rw = fElectronics->GetTraFunReal(k);
854         Double_t iw = fElectronics->GetTraFunImag(k);
855         fOutZR[k] = fInZR[k]*rw - fInZI[k]*iw;
856         fOutZI[k] = fInZR[k]*iw + fInZI[k]*rw;
857       }
858       FastFourierTransform(fElectronics,&fOutZR[0],&fOutZI[0],-1);
859       for(k=0; k<fMaxNofSamples; k++) {
860         Float_t newcont = 0.;
861         //Float_t totcont = 0.;
862         Float_t maxcont = 0.;
863         for(kk=0;kk<fScaleSize;kk++) {
864           newcont = fOutZR[fScaleSize*k+kk];
865           if(newcont > maxcont) maxcont = newcont;
866           //      totcont += (0.25*Out_ZR[4*k+kk]);
867         }
868         newcont = maxcont;
869         Double_t signal = newcont*norm;
870         if (signal >= maxadc) signal = maxadc -1;
871         // back to analog: ?
872         // comment the line below because you want to keep the signal in ADCs
873         // convert back to nA in cluster finder
874         signal /=norm;
875         fHitMap2->SetHit(i,k,signal);
876       }      
877   } // loop over anodes
878   return;
879
880 }
881
882 //____________________________________________
883 void AliITSsimulationSDD::GetAnodeBaseline(Int_t i,Float_t &baseline,
884                                            Float_t &noise){
885   // Returns the Baseline for a particular anode.
886     baseline=fBaseline[i];
887     noise=fNoise[i];
888
889 }
890
891 //____________________________________________
892 void AliITSsimulationSDD::CompressionParam(Int_t i,Int_t &db,Int_t &tl,
893                                            Int_t &th){
894   // Returns the compression alogirthm parameters
895    Int_t size = fD.GetSize();
896    if (size > 2 ) {
897       db=fD[i]; tl=fT1[i]; th=fT2[i];
898    } else {
899       if (size <= 2 && i>=fNofMaps/2) {
900         db=fD[1]; tl=fT1[1]; th=fT2[1];
901       } else {
902         db=fD[0]; tl=fT1[0]; th=fT2[0];
903       }
904    }
905 }
906 //____________________________________________
907 void AliITSsimulationSDD::CompressionParam(Int_t i,Int_t &db,Int_t &tl){
908   // returns the compression alogirthm parameters
909    Int_t size = fD.GetSize();
910    if (size > 2 ) {
911       db=fD[i]; tl=fT1[i];
912    } else {
913       if (size <= 2 && i>=fNofMaps/2) {
914         db=fD[1]; tl=fT1[1]; 
915       } else {
916         db=fD[0]; tl=fT1[0]; 
917       }
918    }
919
920 }
921 //____________________________________________
922 void AliITSsimulationSDD::SetCompressParam(){
923   // Sets the compression alogirthm parameters  
924    Int_t cp[8],i;
925    
926    fResponse->GiveCompressParam(cp);
927    for (i=0; i<2; i++) {
928        fD[i]  =cp[i];
929        fT1[i] =cp[i+2];
930        fT2[i] =cp[i+4];
931        fTol[i]=cp[i+6];
932        printf("\n i, fD, fT1, fT2, fTol %d %d %d %d %d\n",
933                                       i,fD[i],fT1[i],fT2[i],fTol[i]);
934    }
935 }
936
937 //____________________________________________
938 void AliITSsimulationSDD::ReadBaseline(){
939       // read baseline and noise from file - either a .root file and in this
940       // case data should be organised in a tree with one entry for each
941       // module => reading should be done accordingly
942       // or a classic file and do smth. like this:
943   //
944   // Read baselines and noise for SDD
945   //
946
947
948     Int_t na,pos;
949     Float_t bl,n;
950     char input[100], base[100], param[100];
951     char *filtmp;
952
953     fResponse->Filenames(input,base,param);
954     fFileName=base;
955 //
956     filtmp = gSystem->ExpandPathName(fFileName.Data());
957     FILE *bline = fopen(filtmp,"r");
958     printf("filtmp %s\n",filtmp);
959     na = 0;
960
961     if(bline) {
962        while(fscanf(bline,"%d %f %f",&pos, &bl, &n) != EOF) {
963           if (pos != na+1) {
964              Error("ReadBaseline","Anode number not in increasing order!",
965                    filtmp);
966              exit(1);
967           }
968           fBaseline[na]=bl;
969           fNoise[na]=n;
970           na++;
971        }
972     } else {
973       Error("ReadBaseline"," THE BASELINE FILE %s DOES NOT EXIST !",
974           filtmp);
975       exit(1);
976     } // end if(bline)
977     
978     fclose(bline);
979     delete [] filtmp;
980
981
982 //____________________________________________
983 Int_t AliITSsimulationSDD::Convert10to8(Int_t signal) {
984   // To the 10 to 8 bit lossive compression.
985   // code from Davide C. and Albert W.
986
987    if (signal < 128)  return signal;
988    if (signal < 256)  return (128+((signal-128)>>1));
989    if (signal < 512)  return (192+((signal-256)>>3));
990    if (signal < 1024) return (224+((signal-512)>>4));
991    return 0;
992
993 }
994
995 //____________________________________________
996 Int_t AliITSsimulationSDD::Convert8to10(Int_t signal) {
997   // Undo the lossive 10 to 8 bit compression.
998   // code from Davide C. and Albert W.
999    if (signal < 0 || signal > 255) {
1000        printf("<Convert8to10> out of range %d \n",signal);
1001        return 0;
1002    }
1003    
1004    if (signal < 128) return signal;
1005    if (signal < 192) {
1006      if (TMath::Odd(signal)) return (128+((signal-128)<<1));
1007      else  return (128+((signal-128)<<1)+1);
1008    }
1009    if (signal < 224) {
1010      if (TMath::Odd(signal)) return (256+((signal-192)<<3)+3);
1011      else  return (256+((signal-192)<<3)+4);
1012    }
1013    if (TMath::Odd(signal)) return (512+((signal-224)<<4)+7);
1014    else  return (512+((signal-224)<<4)+7);
1015    return 0;
1016
1017 }
1018
1019 //____________________________________________
1020 AliITSMap*   AliITSsimulationSDD::HitMap(Int_t i){
1021   //Return the correct map.
1022     return ((i==0)? fHitMap1 : fHitMap2);
1023 }
1024
1025
1026 //____________________________________________
1027 void AliITSsimulationSDD::ZeroSuppression(const char *option) {
1028   // perform the zero suppresion
1029   if (strstr(option,"2D")) {
1030     //Init2D();              // activate if param change module by module
1031     Compress2D();
1032   } else if (strstr(option,"1D")) {
1033     //Init1D();              // activate if param change module by module
1034     Compress1D();  
1035   } else StoreAllDigits();  
1036
1037 }
1038
1039 //____________________________________________
1040 void AliITSsimulationSDD::Init2D(){
1041      // read in and prepare arrays: fD, fT1, fT2
1042      //                         savemu[nanodes], savesigma[nanodes] 
1043       // read baseline and noise from file - either a .root file and in this
1044       // case data should be organised in a tree with one entry for each
1045       // module => reading should be done accordingly
1046       // or a classic file and do smth. like this ( code from Davide C. and
1047       // Albert W.) :
1048   //
1049   // Read 2D zero-suppression parameters for SDD
1050   //
1051
1052     if (!strstr(fParam,"file")) return;
1053
1054     Int_t na,pos,tempTh;
1055     Float_t mu,sigma;
1056     Float_t *savemu = new Float_t [fNofMaps];
1057     Float_t *savesigma = new Float_t [fNofMaps];
1058     char input[100],basel[100],par[100];
1059     char *filtmp;
1060
1061
1062     Int_t minval = fResponse->MinVal();
1063
1064     fResponse->Filenames(input,basel,par);
1065     fFileName=par;
1066
1067 //
1068     filtmp = gSystem->ExpandPathName(fFileName.Data());
1069     FILE *param = fopen(filtmp,"r");
1070     na = 0;
1071
1072     if(param) {
1073        while(fscanf(param,"%d %f %f",&pos, &mu, &sigma) != EOF) {
1074           if (pos != na+1) {
1075              Error("Init2D ","Anode number not in increasing order!",
1076                    filtmp);
1077              exit(1);
1078           }
1079           savemu[na]=mu;
1080           savesigma[na]=sigma;
1081           if ((2.*sigma) < mu) {
1082               fD[na] = (Int_t)floor(mu - 2.0*sigma + 0.5);
1083               mu = 2.0 * sigma;
1084           } else fD[na] = 0;
1085           tempTh = (Int_t)floor(mu+2.25*sigma+0.5) - minval;
1086           if (tempTh < 0) tempTh=0;
1087           fT1[na] = tempTh;
1088           tempTh = (Int_t)floor(mu+3.0*sigma+0.5) - minval;
1089           if (tempTh < 0) tempTh=0;
1090           fT2[na] = tempTh;
1091           na++;
1092        } // end while
1093
1094     } else {
1095       Error("Init2D "," THE FILE %s DOES NOT EXIST !",
1096           filtmp);
1097       exit(1);
1098     } // end if(param)
1099     
1100     fclose(param);
1101     delete [] filtmp;
1102     delete [] savemu;
1103     delete [] savesigma;
1104
1105
1106 //____________________________________________
1107 void AliITSsimulationSDD::Compress2D(){
1108   //
1109   // simple ITS cluster finder -- online zero-suppression conditions
1110   // 
1111   //
1112
1113     Int_t db,tl,th;  
1114     Int_t minval = fResponse->MinVal();
1115     Bool_t write=fResponse->OutputOption();   
1116     Bool_t do10to8=fResponse->Do10to8();
1117
1118     Int_t nz, nl, nh, low, i, j; 
1119
1120     for (i=0; i<fNofMaps; i++) {
1121         CompressionParam(i,db,tl,th);
1122         nz=0; 
1123         nl=0;
1124         nh=0;
1125         low=0;
1126         for (j=0; j<fMaxNofSamples; j++) {
1127             Int_t signal=(Int_t)(fHitMap2->GetSignal(i,j));
1128             signal -= db; // if baseline eq. is done here
1129             if (signal <= 0) {nz++; continue;}
1130             if ((signal - tl) < minval) low++;
1131             if ((signal - th) >= minval) {
1132                 nh++;
1133                 Bool_t cond=kTRUE;
1134                 FindCluster(i,j,signal,minval,cond);
1135                 if (cond && ((TMath::Abs(fHitMap2->GetSignal(i,j-1))-th)>=minval)) {
1136                   if(do10to8) signal = Convert10to8(signal);
1137                   AddDigit(i,j,signal);
1138                 }
1139             } else if ((signal - tl) >= minval) nl++;
1140        } // loop time samples
1141        if (write) TreeB()->Fill(nz,nl,nh,low,i+1);
1142     } // loop anodes  
1143
1144       char hname[30];
1145       if (write) {
1146         sprintf(hname,"TNtuple%d_%d",fModule,fEvent);
1147         TreeB()->Write(hname);
1148         // reset tree
1149         TreeB()->Reset();
1150       }
1151
1152
1153
1154 //_____________________________________________________________________________
1155 void  AliITSsimulationSDD::FindCluster(Int_t i,Int_t j,Int_t signal,
1156                                        Int_t minval,Bool_t &cond){
1157 //
1158 //  Find clusters according to the online 2D zero-suppression algorithm
1159 //
1160
1161     Bool_t do10to8=fResponse->Do10to8();
1162
1163     Bool_t high=kFALSE;
1164
1165     fHitMap2->FlagHit(i,j);
1166 //
1167 //  check the online zero-suppression conditions
1168 //  
1169     const Int_t maxNeighbours = 4;
1170
1171     Int_t nn;
1172     Int_t dbx,tlx,thx;  
1173     Int_t xList[maxNeighbours], yList[maxNeighbours];
1174     fSegmentation->Neighbours(i,j,&nn,xList,yList);
1175     Int_t in,ix,iy,qns;
1176     for (in=0; in<nn; in++) {
1177         ix=xList[in];
1178         iy=yList[in];
1179         if (fHitMap2->TestHit(ix,iy)==kUnused) {
1180            CompressionParam(ix,dbx,tlx,thx);
1181            Int_t qn = (Int_t)(fHitMap2->GetSignal(ix,iy));
1182            qn -= dbx; // if baseline eq. is done here
1183            if ((qn-tlx) < minval) {
1184               fHitMap2->FlagHit(ix,iy);
1185               continue;
1186            } else {
1187               if ((qn - thx) >= minval) high=kTRUE;
1188               if (cond) {
1189                  if(do10to8) signal = Convert10to8(signal);
1190                  AddDigit(i,j,signal);
1191               }
1192               if(do10to8) qns = Convert10to8(qn);
1193               else qns=qn;
1194               if (!high) AddDigit(ix,iy,qns);
1195               cond=kFALSE;
1196               if(!high) fHitMap2->FlagHit(ix,iy);
1197            }
1198         } // TestHit
1199     } // loop over neighbours
1200
1201 }
1202
1203 //____________________________________________
1204 void AliITSsimulationSDD::Init1D(){
1205   // this is just a copy-paste of input taken from 2D algo
1206   // Torino people should give input
1207   //
1208   // Read 1D zero-suppression parameters for SDD
1209   //
1210
1211     if (!strstr(fParam,"file")) return;
1212
1213     Int_t na,pos,tempTh;
1214     Float_t mu,sigma;
1215     Float_t *savemu = new Float_t [fNofMaps];
1216     Float_t *savesigma = new Float_t [fNofMaps];
1217     char input[100],basel[100],par[100];
1218     char *filtmp;
1219
1220
1221     Int_t minval = fResponse->MinVal();
1222     fResponse->Filenames(input,basel,par);
1223     fFileName=par;
1224
1225 //  set first the disable and tol param
1226     SetCompressParam();
1227 //
1228     filtmp = gSystem->ExpandPathName(fFileName.Data());
1229     FILE *param = fopen(filtmp,"r");
1230     na = 0;
1231
1232     if (param) {
1233           fscanf(param,"%d %d %d %d ", &fT2[0], &fT2[1], &fTol[0], &fTol[1]);
1234           while(fscanf(param,"%d %f %f",&pos, &mu, &sigma) != EOF) {
1235                if (pos != na+1) {
1236                   Error("Init1D ","Anode number not in increasing order!",
1237                    filtmp);
1238                   exit(1);
1239                }
1240                savemu[na]=mu;
1241                savesigma[na]=sigma;
1242                if ((2.*sigma) < mu) {
1243                  fD[na] = (Int_t)floor(mu - 2.0*sigma + 0.5);
1244                  mu = 2.0 * sigma;
1245                } else fD[na] = 0;
1246                tempTh = (Int_t)floor(mu+2.25*sigma+0.5) - minval;
1247                if (tempTh < 0) tempTh=0;
1248                fT1[na] = tempTh;
1249                na++;
1250           } // end while
1251     } else {
1252       Error("Init1D "," THE FILE %s DOES NOT EXIST !",
1253           filtmp);
1254       exit(1);
1255     } // end if(param)
1256     
1257     fclose(param);
1258     delete [] filtmp;
1259     delete [] savemu;
1260     delete [] savesigma;
1261
1262
1263
1264 }
1265  
1266 //____________________________________________
1267 void AliITSsimulationSDD::Compress1D(){
1268     // 1D zero-suppression algorithm (from Gianluca A.)
1269
1270     Int_t dis,tol,thres,decr,diff;  
1271
1272     UChar_t *str=fStream->Stream();
1273     Int_t counter=0;
1274
1275     Bool_t do10to8=fResponse->Do10to8();
1276
1277     Int_t last=0;
1278     Int_t k,i,j;
1279     for (k=0; k<2; k++) {
1280          tol = Tolerance(k);
1281          dis = Disable(k);  
1282          for (i=0; i<fNofMaps/2; i++) {
1283              Bool_t firstSignal=kTRUE;
1284              Int_t idx=i+k*fNofMaps/2;
1285              CompressionParam(idx,decr,thres); 
1286              for (j=0; j<fMaxNofSamples; j++) {
1287                  Int_t signal=(Int_t)(fHitMap2->GetSignal(idx,j));
1288                  signal -= decr;  // if baseline eq.
1289                  if(do10to8) signal = Convert10to8(signal);
1290                  if (signal <= thres) {
1291                      signal=0;
1292                      diff=128; 
1293                      last=0; 
1294                      // write diff in the buffer for HuffT
1295                      str[counter]=(UChar_t)diff;
1296                      counter++;
1297                      continue;
1298                  }
1299                  diff=signal-last;
1300                  if (diff > 127) diff=127;
1301                  if (diff < -128) diff=-128;
1302    
1303                  if (signal < dis) {
1304                    // tol has changed to 8 possible cases ? - one can write
1305                    // this if(TMath::Abs(diff)<tol) ... else ...
1306                     if(TMath::Abs(diff)<tol) diff=0;
1307                     // or keep it as it was before
1308                     /*
1309                     if (tol==1 && (diff >= -2 && diff <= 1)) diff=0;
1310                     if (tol==2 && (diff >= -4 && diff <= 3)) diff=0;
1311                     if (tol==3 && (diff >= -16 && diff <= 15)) diff=0;
1312                     */
1313                     AddDigit(idx,j,last+diff);
1314                  } else {
1315                    AddDigit(idx,j,signal);
1316                  }
1317                  
1318                  diff += 128;
1319                  // write diff in the buffer used to compute Huffman tables
1320                  if (firstSignal) str[counter]=(UChar_t)signal;
1321                  else str[counter]=(UChar_t)diff;
1322                  counter++;
1323
1324                  last=signal;
1325                  firstSignal=kFALSE;
1326              } // loop time samples
1327          } // loop anodes  one half of detector 
1328     }
1329
1330     // check
1331     fStream->CheckCount(counter);
1332
1333     // open file and write out the stream of diff's
1334    
1335     static Bool_t open=kTRUE;
1336     static TFile *outFile;
1337     Bool_t write = fResponse->OutputOption();
1338  
1339     if (write ) {
1340         if(open) {
1341             SetFileName("stream.root");
1342             cout<<"filename "<<fFileName<<endl;
1343             outFile=new TFile(fFileName,"recreate");
1344             cout<<"I have opened "<<fFileName<<" file "<<endl;
1345         }           
1346         open=kFALSE;
1347         outFile->cd();
1348         fStream->Write();
1349     }  // endif write   
1350
1351      fStream->ClearStream();
1352
1353      // back to galice.root file
1354
1355      TTree *fAli=gAlice->TreeK();
1356      TFile *file = 0;
1357             
1358      if (fAli) file =fAli->GetCurrentFile();
1359      file->cd();
1360
1361
1362
1363 //____________________________________________
1364 void AliITSsimulationSDD::StoreAllDigits(){
1365   // if non-zero-suppressed data 
1366
1367     Bool_t do10to8=fResponse->Do10to8();
1368
1369     Int_t i, j, digits[3];
1370     for (i=0; i<fNofMaps; i++) {
1371         for (j=0; j<fMaxNofSamples; j++) {
1372              Int_t signal=(Int_t)(fHitMap2->GetSignal(i,j));
1373              if(do10to8) signal = Convert10to8(signal);
1374              if(do10to8) signal = Convert8to10(signal); 
1375              digits[0]=i;
1376              digits[1]=j;
1377              digits[2]=signal;
1378              fITS->AddRealDigit(1,digits);
1379         }
1380     }
1381
1382 //____________________________________________
1383
1384 void AliITSsimulationSDD::CreateHistograms(Int_t scale){
1385   // Creates histograms of maps for debugging
1386
1387       Int_t i;
1388
1389       fHis=new TObjArray(fNofMaps);
1390       TString sddName("sdd_");
1391       for (i=0;i<fNofMaps;i++) {
1392            Char_t candNum[4];
1393            sprintf(candNum,"%d",i+1);
1394            sddName.Append(candNum);
1395            (*fHis)[i] = new TH1F(sddName.Data(),"SDD maps",
1396                 scale*fMaxNofSamples,0.,(Float_t) scale*fMaxNofSamples);
1397       }
1398
1399 }
1400 //____________________________________________
1401 void AliITSsimulationSDD::FillHistograms(){
1402   // fill 1D histograms from map
1403   if (!fHis) return; 
1404   
1405   for( Int_t i=0; i<fNofMaps; i++) {
1406     TH1F *hist =(TH1F *)fHis->UncheckedAt(i);
1407     Int_t nsamples = hist->GetNbinsX();
1408     for( Int_t j=0; j<nsamples; j++) {
1409       Double_t signal=fHitMap2->GetSignal(i,j);
1410       hist->Fill((Float_t)j,signal);
1411     }
1412   }
1413 }
1414
1415 //____________________________________________
1416
1417 void AliITSsimulationSDD::ResetHistograms(){
1418     //
1419     // Reset histograms for this detector
1420     //
1421     Int_t i;
1422     for (i=0;i<fNofMaps;i++ ) {
1423         if ((*fHis)[i])    ((TH1F*)(*fHis)[i])->Reset();
1424     }
1425
1426 }
1427
1428
1429 //____________________________________________
1430
1431 TH1F *AliITSsimulationSDD::GetAnode(Int_t wing, Int_t anode) { 
1432   // Fills a histogram from a give anode.  
1433   if (!fHis) return 0;
1434
1435   if(wing <=0 || wing > 2) {
1436     cout << "Wrong wing number: " << wing << endl;
1437     return NULL;
1438   }
1439   if(anode <=0 || anode > fNofMaps/2) {
1440     cout << "Wrong anode number: " << anode << endl;
1441     return NULL;
1442   }
1443
1444   Int_t index = (wing-1)*fNofMaps/2 + anode-1;
1445   return (TH1F*)((*fHis)[index]); 
1446 }
1447
1448 //____________________________________________
1449
1450 void AliITSsimulationSDD::WriteToFile(TFile *hfile) {
1451   // Writes the histograms to a file 
1452   if (!fHis) return;
1453
1454   hfile->cd();
1455   Int_t i;
1456   for(i=0; i<fNofMaps; i++)  (*fHis)[i]->Write(); //fAdcs[i]->Write();
1457   return;
1458 }
1459 //____________________________________________
1460 Float_t AliITSsimulationSDD::GetNoise() {  
1461   // Returns the noise value
1462
1463   //Bool_t do10to8=fResponse->Do10to8();
1464   //noise will always be in the liniar part of the signal
1465
1466   Int_t decr;
1467   Int_t threshold=fT1[0];
1468
1469   char opt1[20], opt2[20];
1470   fResponse->ParamOptions(opt1,opt2);
1471   fParam=opt2;
1472   char *same = strstr(opt1,"same");
1473   Float_t noise,baseline;
1474   if (same) {
1475     fResponse->GetNoiseParam(noise,baseline);
1476   } else {
1477      static Bool_t readfile=kTRUE;
1478      //read baseline and noise from file
1479      if (readfile) ReadBaseline();
1480      readfile=kFALSE;
1481   }
1482
1483    TCanvas *c2 = (TCanvas*)gROOT->GetListOfCanvases()->FindObject("c2");
1484    if(c2) delete c2->GetPrimitive("noisehist");
1485    if(c2) delete c2->GetPrimitive("anode");
1486    else     c2=new TCanvas("c2");
1487    c2->cd();
1488    c2->SetFillColor(0);
1489
1490    TH1F *noisehist = new TH1F("noisehist","noise",100,0.,(float)2*threshold);
1491    TH1F *anode = new TH1F("anode","Anode Projection",fMaxNofSamples,0.,(float)fMaxNofSamples);
1492   Int_t i,k;
1493   for (i=0;i<fNofMaps;i++) {
1494     CompressionParam(i,decr,threshold); 
1495     if  (!same) GetAnodeBaseline(i,baseline,noise);
1496     anode->Reset();
1497     for (k=0;k<fMaxNofSamples;k++) {
1498       Float_t signal=(Float_t)fHitMap2->GetSignal(i,k);
1499       //if (signal <= (float)threshold) noisehist->Fill(signal-baseline);
1500       if (signal <= (float)threshold) noisehist->Fill(signal);
1501       anode->Fill((float)k,signal);
1502     }
1503     anode->Draw();
1504     c2->Update();
1505   }
1506   TF1 *gnoise = new TF1("gnoise","gaus",0.,threshold);
1507   noisehist->Fit("gnoise","RQ");
1508   noisehist->Draw();
1509   c2->Update();
1510   Float_t mnoise = gnoise->GetParameter(1);
1511   cout << "mnoise : " << mnoise << endl;
1512   Float_t rnoise = gnoise->GetParameter(2);
1513   cout << "rnoise : " << rnoise << endl;
1514   delete noisehist;
1515   return rnoise;
1516 }