]> git.uio.no Git - u/mrichter/AliRoot.git/blob - ITS/AliITS.cxx
Added protection in case gGeoManager is a null pointer
[u/mrichter/AliRoot.git] / ITS / AliITS.cxx
1 /**************************************************************************
2  * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
3  *                                                                        *
4  * Author: The ALICE Off-line Project.                                    *
5  * Contributors are mentioned in the code where appropriate.              *
6  *                                                                        *
7  * Permission to use, copy, modify and distribute this software and its   *
8  * documentation strictly for non-commercial purposes is hereby granted   *
9  * without fee, provided that the above copyright notice appears in all   *
10  * copies and that both the copyright notice and this permission notice   *
11  * appear in the supporting documentation. The authors make no claims     *
12  * about the suitability of this software for any purpose. It is          *
13  * provided "as is" without express or implied warranty.                  *
14  **************************************************************************/
15
16 /* $Id$ */
17
18
19 ///////////////////////////////////////////////////////////////////////////////
20 //                                                                           //
21 //      An overview of the basic philosophy of the ITS code development      //
22 // and analysis is show in the figure below.                                 //
23 //Begin_Html                                                                 //
24 /*                                               
25 <img src="picts/ITS/ITS_Analysis_schema.gif">
26 </pre>
27 <br clear=left>
28 <font size=+2 color=red>
29 <p>Roberto Barbera is in charge of the ITS Offline code (1999).
30 <a href="mailto:roberto.barbera@ct.infn.it">Roberto Barbera</a>.
31 </font>
32 <pre>
33 */
34 //End_Html
35 //
36 //  AliITS. Inner Traking System base class.
37 //  This class contains the base procedures for the Inner Tracking System
38 //
39 //Begin_Html
40 /*
41 <img src="picts/ITS/AliITS_Class_Diagram.gif">
42 </pre>
43 <br clear=left>
44 <font size=+2 color=red>
45 <p>This show the class diagram of the different elements that are part of
46 the AliITS class.
47 </font>
48 <pre>
49 */
50 //End_Html
51 //
52 // Version: 0
53 // Written by Rene Brun, Federico Carminati, and Roberto Barbera
54 //
55 // Version: 1
56 // Modified and documented by Bjorn S. Nilsen
57 // July 11 1999
58 //
59 // Version: 2
60 // Modified and documented by A. Bologna
61 // October 18 1999
62 //
63 // AliITS is the general base class for the ITS. Also see AliDetector for
64 // futher information.
65 //
66 ///////////////////////////////////////////////////////////////////////////////
67
68 #include <stdlib.h>
69 #include <TClonesArray.h>
70 #include <TFile.h>
71 #include <TParticle.h>
72 #include <TString.h>
73 #include <TTree.h>
74 #include <TVirtualMC.h>
75 #include "AliDetector.h"
76 #include "AliITS.h"
77 #include "AliITSDetTypeSim.h"
78 #include "AliITSDDLRawData.h"
79 #include "AliITSLoader.h"
80 #include "AliITShit.h"
81 #include "AliITSmodule.h"
82 #include "AliITSpListItem.h"
83 #include "AliITSsimulation.h"
84 #include "AliITSsimulationFastPoints.h"
85 #include "AliMC.h"
86 #include "AliITSDigitizer.h"
87 #include "AliITSRecPoint.h"
88 #include "AliITSsegmentationSPD.h"
89 #include "AliITSsegmentationSDD.h"
90 #include "AliITSsegmentationSSD.h"
91 #include "AliITSRawStreamSPD.h"
92 #include "AliITSRawStreamSSD.h"
93 #include "AliITSRawStreamSDD.h"
94 #include "AliITSresponseSDD.h" 
95 #include "AliRawReader.h"
96 #include "AliRun.h"
97 #include "AliLog.h"
98 #include "AliITSInitGeometry.h"
99
100 ClassImp(AliITS)
101
102 //______________________________________________________________________
103 AliITS::AliITS() : AliDetector(),
104 fDetTypeSim(0),
105 fEuclidOut(0),
106 fOpt("All"),
107 fIdN(0),
108 fIdSens(0),
109 fIdName(0),
110 fITSmodules(0),
111 fTiming(kFALSE)
112 {
113   // Default initializer for ITS
114   //      The default constructor of the AliITS class. In addition to
115   // creating the AliITS class it zeros the variables fIshunt (a member
116   // of AliDetector class), fEuclidOut, and fIdN, and zeros the pointers
117   // fIdSens, and fIdName. The AliDetector default constructor
118   // is also called.
119   
120 //    SetDetectors(); // default to fOpt="All". This variable not written out.
121 //PH    SetMarkerColor(kRed);
122 }
123 //______________________________________________________________________
124 AliITS::AliITS(const Char_t *title):AliDetector("ITS",title),
125 fDetTypeSim(0),
126 fEuclidOut(0),
127 fOpt("All"),
128 fIdN(0),
129 fIdSens(0),
130 fIdName(0),
131 fITSmodules(0),
132 fTiming(kFALSE)
133 {
134     //     The standard Constructor for the ITS class. 
135     // It also zeros the variables
136     // fIshunt (a member of AliDetector class), fEuclidOut, and zeros
137     // the pointers fIdSens and fIdName. To help in displaying hits via the
138     // ROOT macro display.C AliITS also sets the marker color to red. The
139     // variables passes with this constructor, const char *name and *title,
140     // are used by the constructor of AliDetector class. See AliDetector
141     // class for a description of these parameters and its constructor
142     // functions.
143     // Inputs:
144     //   Char_t *title  Simulation title for the ITS
145     // Outputs:
146     //   none.
147     // Return:
148     //   none.
149   
150     fHits = new TClonesArray("AliITShit",1560); // from AliDetector
151     if(gAlice->GetMCApp()) gAlice->GetMCApp()->AddHitList(fHits);
152     //fNhits=0;  //done in AliDetector(name,title)
153     SetDetectors(); // default to fOpt="All". This variable not written out.
154     fDetTypeSim   = new AliITSDetTypeSim();
155     //PH  SetMarkerColor(kRed);
156     if(!fLoader) MakeLoader(AliConfig::GetDefaultEventFolderName());
157     fDetTypeSim->SetLoader((AliITSLoader*)fLoader);
158 }
159 //______________________________________________________________________
160 AliITS::AliITS(const char *name, const char *title):AliDetector(name,title),
161 fDetTypeSim(0),
162 fEuclidOut(0),
163 fOpt("All"),
164 fIdN(0),
165 fIdSens(0),
166 fIdName(0),
167 fITSmodules(0),
168 fTiming(kFALSE)
169 {
170   //     The standard Constructor for the ITS class. 
171   // It also zeros the variables
172   // fIshunt (a member of AliDetector class), fEuclidOut, and zeros
173   // the pointers fIdSens and fIdName. To help in displaying hits via the
174   // ROOT macro display.C AliITS also sets the marker color to red. The
175   // variables passes with this constructor, const char *name and *title,
176   // are used by the constructor of AliDetector class. See AliDetector
177   // class for a description of these parameters and its constructor
178   // functions.
179   
180   fHits = new TClonesArray("AliITShit",1560);
181   if(gAlice->GetMCApp()) gAlice->GetMCApp()->AddHitList(fHits);
182   //fNhits=0;  //done in AliDetector(name,title)
183
184   SetDetectors(); // default to fOpt="All". This variable not written out.
185     
186   fDetTypeSim   = new AliITSDetTypeSim();
187   
188   //PH  SetMarkerColor(kRed);
189   if(!fLoader) MakeLoader(AliConfig::GetDefaultEventFolderName());
190   fDetTypeSim->SetLoader((AliITSLoader*)fLoader);
191
192 }
193 //______________________________________________________________________
194 AliITS::~AliITS(){
195     // Default destructor for ITS.
196     //     The default destructor of the AliITS class. In addition to deleting
197     // the AliITS class it deletes the memory pointed to by 
198     // fIdSens, fIdName, fDetTypeSim and it's contents.
199     // Inputs:
200     //      none.
201     // Outputs:
202     //      none.
203     // Return:
204     //      none.
205
206     if (fHits) {
207       fHits->Delete();
208       delete fHits;
209       fHits=0;
210     }
211     if(fITSmodules) {
212         this->ClearModules();
213         delete fITSmodules;
214         fITSmodules = 0;
215     }// end if fITSmodules!=0
216
217     delete[] fIdName;  // Array of TStrings
218     delete[] fIdSens;
219
220     if (fDetTypeSim){
221       delete fDetTypeSim;
222       fDetTypeSim = 0;
223     }
224 }
225 //______________________________________________________________________
226 AliDigitizer* AliITS::CreateDigitizer(AliRunDigitizer* manager)const{
227     // Creates the AliITSDigitizer in a standard way for use via AliModule.
228     // This function can not be included in the .h file because of problems
229     // with the order of inclusion (recursive).
230     // Inputs:
231     //    AliRunDigitizer *manager  The Manger class for Digitization
232     // Output:
233     //    none.
234     // Return:
235     //    A new AliITSRunDigitizer (cast as a AliDigitizer).
236
237      return new AliITSDigitizer(manager);
238 }
239 //______________________________________________________________________
240 void AliITS::Init(){
241     // Initializer ITS after it has been built
242     //     This routine initializes the AliITS class. It is intended to be
243     // called from the Init function in AliITSv?. Besides displaying a banner
244     // indicating that it has been called it initializes the array fIdSens
245     // and sets the default segmentation, response, digit and raw cluster
246     // classes therefore it should be called after a call to CreateGeometry.
247     // Inputs:
248     //      none.
249     // Outputs:
250     //      none.
251     // Return:
252     //      none.
253     Int_t i;
254     // Array of TStrings
255     if(gMC) for(i=0;i<fIdN;i++) fIdSens[i] = gMC->VolId(fIdName[i]);
256  
257 }
258
259
260 //______________________________________________________________________
261 void AliITS::SetDefaults(){
262     // sets the default segmentation, response, digit and raw cluster classes.
263     // Inputs:
264     //      none.
265     // Outputs:
266     //      none.
267     // Return:
268     //      none.
269     AliInfoClass("AliITS::Setting Defaults");
270     if(!fDetTypeSim) { 
271      Error("SetDefaults()","fDetTypeSim is 0!"); 
272      return;
273     }
274
275     fDetTypeSim->SetDefaults();
276
277
278 }
279 //______________________________________________________________________
280 void AliITS::SetDefaultSimulation(){
281     // sets the default simulation.
282     // Inputs:
283     //      none.
284     // Outputs:
285     //      none.
286     // Return:
287     //      none.
288     if(!fDetTypeSim) { 
289      Error("SetDefaultSimulation()","fDetTypeSim is 0!"); 
290      return;
291     }
292
293     fDetTypeSim->SetDefaultSimulation();
294
295 }
296
297
298 //______________________________________________________________________
299 void AliITS::MakeBranch(Option_t* option){
300     // Creates Tree branches for the ITS.
301     // Inputs:
302     //      Option_t *option    String of Tree types S,D, and/or R.
303     //      const char *file    String of the file name where these branches
304     //                          are to be stored. If blank then these branches
305     //                          are written to the same tree as the Hits were
306     //                          read from.
307     // Outputs:
308     //      none.
309     // Return:
310     //      none.
311   if(!fDetTypeSim) {
312     Error("MakeBranch","fDetTypeSim is 0!");
313     return;
314   }
315
316   Bool_t cH = (strstr(option,"H")!=0);
317   Bool_t cS = (strstr(option,"S")!=0);
318   Bool_t cD = (strstr(option,"D")!=0);
319   
320   if(cH && (fHits == 0x0)) fHits = new TClonesArray("AliITShit", 1560);
321   AliDetector::MakeBranch(option);
322   
323   if(cS) MakeBranchS(0);
324   if(cD) MakeBranchD(0);
325
326
327 }
328 //___________________________________________________________________
329 void AliITS::MakeBranchS(const char* fl){
330
331   // Creates Tree Branch for the ITS summable digits.
332   // Inputs:
333   //      cont char *fl  File name where SDigits branch is to be written
334   //                     to. If blank it write the SDigits to the same
335   //                     file in which the Hits were found.
336
337   
338   if(!fDetTypeSim){
339     Error("MakeBranchS","fDetTypeSim is 0!");
340   }
341   Int_t buffersize = 4000;
342   char branchname[30];
343
344   // only one branch for SDigits.
345   sprintf(branchname,"%s",GetName());
346
347   if(fLoader->TreeS()){
348     if(fDetTypeSim->GetSDigits()==0x0) fDetTypeSim->SetSDigits(new TClonesArray("AliITSpListItem",1000));
349     TClonesArray* sdig = (TClonesArray*)fDetTypeSim->GetSDigits();
350     MakeBranchInTree(fLoader->TreeS(),branchname,&sdig,buffersize,fl);
351   } 
352 }
353 //______________________________________________________________________
354 void AliITS::MakeBranchD(const char* file){
355
356   //Make branch for digits
357   if(!fDetTypeSim) {
358     Warning("MakeBranchD","fDetTypeSim is 0!");
359     return;
360   }
361   fDetTypeSim->SetLoader((AliITSLoader*)fLoader);
362   MakeBranchInTreeD(fLoader->TreeD(),file);
363 }
364
365 //___________________________________________________________________
366 void AliITS:: MakeBranchInTreeD(TTree* treeD, const char* file){
367   // Creates Tree branches for the ITS.
368
369   if(!fDetTypeSim){
370     Error("MakeBranchS","fDetTypeSim is 0!");
371   }
372   fDetTypeSim->SetLoader((AliITSLoader*)fLoader);
373
374   const Char_t *det[3] = {"SPD","SDD","SSD"};
375   Char_t* digclass;
376   Int_t buffersize = 4000;
377   Char_t branchname[30];
378   
379   if(!fDetTypeSim->GetDigits()){
380     fDetTypeSim->SetDigits(new TObjArray(fgkNTYPES));
381   }
382   for(Int_t i=0;i<fgkNTYPES;i++){
383     digclass = fDetTypeSim->GetDigitClassName(i);
384     TString classn = digclass;
385     if(!((fDetTypeSim->GetDigits())->At(i))){
386       (fDetTypeSim->GetDigits())->AddAt(new TClonesArray(classn.Data(),1000),i);
387     }
388     else ResetDigits(i);  
389     if(fgkNTYPES==3) sprintf(branchname,"%sDigits%s",GetName(),det[i]);
390     else sprintf(branchname,"%sDigits%d",GetName(),i+1);
391     TObjArray* dig = DigitsAddress(i);
392     if(GetDigits() && treeD) AliDetector::MakeBranchInTree(treeD,branchname, &dig,buffersize,file);
393   }
394
395 }
396 //______________________________________________________________________
397 void AliITS::SetTreeAddress(){
398     // Set branch address for the Trees.
399     // Inputs:
400     //      none.
401     // Outputs:
402     //      none.
403     // Return:
404     //      none.
405     
406   if(!fDetTypeSim) {
407     Error("SetTreeAddress","fDetTypeSim is 0!");
408     return;
409   }
410
411   fDetTypeSim->SetLoader((AliITSLoader*)fLoader);
412
413   TTree *treeS = fLoader->TreeS();
414   TTree *treeD = fLoader->TreeD();
415   if (fLoader->TreeH() && (fHits == 0x0)) {
416       fHits = new TClonesArray("AliITShit", 1560);
417   }
418   AliDetector::SetTreeAddress();
419
420   fDetTypeSim->SetTreeAddressS(treeS, (Char_t*)GetName());
421   fDetTypeSim->SetTreeAddressD(treeD, (Char_t*)GetName());
422 }
423 //______________________________________________________________________
424 void AliITS::AddHit(Int_t track, Int_t *vol, Float_t *hits){
425     // Add an ITS hit
426     //     The function to add information to the AliITShit class. See the
427     // AliITShit class for a full description. This function allocates the
428     // necessary new space for the hit information and passes the variable
429     // track, and the pointers *vol and *hits to the AliITShit constructor
430     // function.
431     // Inputs:
432     //      Int_t   track   Track number which produced this hit.
433     //      Int_t   *vol    Array of Integer Hit information. See AliITShit.h
434     //      Float_t *hits   Array of Floating Hit information.  see AliITShit.h
435     // Outputs:
436     //      none.
437     // Return:
438     //      none.
439   TClonesArray &lhits = *fHits;
440   new(lhits[fNhits++]) AliITShit(fIshunt,track,vol,hits);
441 }
442
443 //______________________________________________________________________
444 void AliITS::FillModules(Int_t evnt,Int_t bgrev,Int_t nmodules,
445                          Option_t *option, const char *filename){
446   // fill the modules with the sorted by module hits; add hits from
447   // background if option=Add.
448
449   static TTree *trH1;                 //Tree with background hits
450   static Bool_t first=kTRUE;
451   static TFile *file;
452   const char *addBgr = strstr(option,"Add");
453   
454   evnt = nmodules; // Dummy use of variables to remove warnings
455   if (addBgr ) {
456     if(first) {
457       file=new TFile(filename);
458     } // end if first
459     first=kFALSE;
460     file->cd();
461     file->ls();
462     // Get Hits Tree header from file
463     if(trH1) delete trH1;
464     trH1=0;
465     
466     char treeName[20];
467     sprintf(treeName,"TreeH%d",bgrev);
468     trH1 = (TTree*)gDirectory->Get(treeName);
469     if (!trH1) {
470       Error("FillModules","cannot find Hits Tree for event:%d",bgrev);
471     } // end if !trH1
472     // Set branch addresses
473   } // end if addBgr
474   
475   FillModules(fLoader->TreeH(),0); // fill from this file's tree.
476     
477   if (addBgr ) {
478     FillModules(trH1,10000000); // Default mask 10M.
479     TTree *fAli=fLoader->GetRunLoader()->TreeK();
480     TFile *fileAli=0;
481     if (fAli) fileAli =fAli->GetCurrentFile();
482     fileAli->cd();
483   } // end if add
484   
485   
486 }
487
488
489 //______________________________________________________________________
490 void AliITS::FillModules(TTree *treeH, Int_t mask) {
491     // fill the modules with the sorted by module hits; 
492     // can be called many times to do a merging
493     // Inputs:
494     //      TTree *treeH  The tree containing the hits to be copied into
495     //                    the modules.
496     //      Int_t mask    The track number mask to indecate which file
497     //                    this hits came from.
498     // Outputs:
499     //      none.
500     // Return:
501     //      none.
502
503     if (treeH == 0x0)
504      {
505        Error("FillModules","Tree is NULL");
506      }
507     Int_t lay,lad,det,index;
508     AliITShit *itsHit=0;
509     AliITSmodule *mod=0;
510     char branchname[20];
511     sprintf(branchname,"%s",GetName());
512     TBranch *branch = treeH->GetBranch(branchname);
513     if (!branch) {
514         Error("FillModules","%s branch in TreeH not found",branchname);
515         return;
516     } // end if !branch
517     branch->SetAddress(&fHits);
518     Int_t nTracks =(Int_t) treeH->GetEntries();
519     Int_t iPrimTrack,h;
520     for(iPrimTrack=0; iPrimTrack<nTracks; iPrimTrack++){
521         ResetHits();
522         Int_t nBytes = treeH->GetEvent(iPrimTrack);
523         if (nBytes <= 0) continue;
524         Int_t nHits = fHits->GetEntriesFast();
525         for(h=0; h<nHits; h++){
526             itsHit = (AliITShit *)fHits->UncheckedAt(h);
527             itsHit->GetDetectorID(lay,lad,det);
528             if (GetITSgeom()) {
529                 index = GetITSgeom()->GetModuleIndex(lay,lad,det);
530             } else {
531                 index=det-1; // This should not be used.
532             } // end if [You must have fITSgeom for this to work!]
533             mod = GetModule(index);
534             itsHit->SetTrack(itsHit->GetTrack()+mask); // Set track mask.
535             mod->AddHit(itsHit,iPrimTrack,h);
536         } // end loop over hits 
537     } // end loop over tracks
538 }
539
540 //______________________________________________________________________
541 Bool_t AliITS::InitModules(Int_t size,Int_t &nmodules){
542     // Initialize the modules array.
543     // Inputs:
544     //      Int_t size  Size of array of the number of modules to be
545     //                  created. If size <=0 then the number of modules
546     //                  is gotten from AliITSgeom class kept in fITSgeom.
547     // Outputs:
548     //      Int_t &nmodules The number of modules existing.
549     // Return:
550     //      none.
551
552     if(fITSmodules){ 
553         fITSmodules->Delete();
554         delete fITSmodules;
555     } // end fir fITSmoudles
556
557     if(!fDetTypeSim) {
558       Error("InitModules","fDetTypeSim is null!");
559       return kFALSE;
560     }
561
562     Int_t nl,indexMAX,index;
563
564     if(size<=0){ // default to using data stored in AliITSgeom
565         if(fDetTypeSim->GetITSgeom()==0) {
566             Error("InitModules","fITSgeom not defined");
567             return kFALSE;
568         } // end if fITSgeom==0
569         nl = fDetTypeSim->GetITSgeom()->GetNlayers();
570         indexMAX = fDetTypeSim->GetITSgeom()->GetIndexMax();
571         nmodules = indexMAX;
572         fITSmodules = new TObjArray(indexMAX);
573         for(index=0;index<indexMAX;index++){
574             fITSmodules->AddAt( new AliITSmodule(index),index);
575         } // end for index
576     }else{
577         fITSmodules = new TObjArray(size);
578         for(index=0;index<size;index++) {
579             fITSmodules->AddAt( new AliITSmodule(index),index);
580         } // end for index
581
582         nmodules = size;
583     } // end i size<=0
584     return kTRUE;
585 }
586 //______________________________________________________________________
587 void AliITS::Hits2SDigits(){
588     // Standard Hits to summable Digits function.
589     // Inputs:
590     //      none.
591     // Outputs:
592     //      none.
593   
594
595    if(!fDetTypeSim) {
596      Error("Hits2SDigits","fDetTypeSim is null!");
597      return;
598     
599   } 
600      
601   SetDefaults();
602   fLoader->LoadHits("read");
603   fLoader->LoadSDigits("recreate");
604   AliRunLoader* rl = fLoader->GetRunLoader(); 
605   fDetTypeSim->SetLoader((AliITSLoader*)fLoader);
606   for (Int_t iEvent = 0; iEvent < rl->GetNumberOfEvents(); iEvent++) {
607         // Do the Hits to Digits operation. Use Standard input values.
608         // Event number from file, no background hit merging , use size from
609         // AliITSgeom class, option="All", input from this file only.
610     rl->GetEvent(iEvent);
611     if (!fLoader->TreeS()) fLoader->MakeTree("S");
612     MakeBranch("S");
613     SetTreeAddress();
614     HitsToPreDigits(iEvent,0,-1," ",fOpt," ");
615   } // end for iEvent
616     
617   fLoader->UnloadHits();
618   fLoader->UnloadSDigits();
619   
620 }
621 //______________________________________________________________________
622 void AliITS::Hits2Digits(){
623
624   //Conversion from hits to digits
625   if(!fDetTypeSim) {
626     Error("Hits2SDigits","fDetTypeSim is 0!");
627     return;
628   }
629    
630   fDetTypeSim->SetLoader((AliITSLoader*)fLoader);
631   SetDefaults();
632
633   fLoader->LoadHits("read");
634   fLoader->LoadDigits("recreate");
635   AliRunLoader* rl = fLoader->GetRunLoader(); 
636   for (Int_t iEvent = 0; iEvent < rl->GetNumberOfEvents(); iEvent++) {
637     rl->GetEvent(iEvent);
638     if (!fLoader->TreeD()) fLoader->MakeTree("D");
639     MakeBranch("D");
640     SetTreeAddress();   
641     HitsToDigits(iEvent,0,-1," ",fOpt," ");
642   } 
643   
644   fLoader->UnloadHits();
645   fLoader->UnloadDigits();
646   
647 }
648
649 //______________________________________________________________________
650 void AliITS::HitsToDigits(Int_t evNumber,Int_t bgrev,Int_t size,
651                           Option_t *option,Option_t *opt,
652                           const char *filename){
653     //   Keep galice.root for signal and name differently the file for 
654     // background when add! otherwise the track info for signal will be lost !
655     // the condition below will disappear when the geom class will be
656     // initialized for all versions - for the moment it is only for v5 !
657     // 7 is the SDD beam test version.
658     // Inputs:
659     //      Int_t evnt       Event to be processed.
660     //      Int_t bgrev      Background Hit tree number.
661     //      Int_t nmodules   Not used.
662     //      Option_t *option String indicating if merging hits or not. To
663     //                       merge hits set equal to "Add". Otherwise no
664     //                       background hits are considered.
665     //      Test_t *filename File name containing the background hits..
666     // Outputs:
667     //      none.
668     // Return:
669     //      none.
670
671   if(!fDetTypeSim) {
672     Error("HitsToDigits","fDetTypeSim is null!");
673     return;
674   }
675   fDetTypeSim->SetLoader((AliITSLoader*)fLoader);
676   if(!GetITSgeom()) return; // need transformations to do digitization.
677   AliITSgeom *geom = GetITSgeom();
678
679   const char *all = strstr(opt,"All");
680   const char *det[3] = {strstr(opt,"SPD"),strstr(opt,"SDD"),
681                         strstr(opt,"SSD")};
682   static Bool_t setDef=kTRUE;
683   if (setDef) SetDefaultSimulation();
684   setDef=kFALSE;
685   
686   Int_t nmodules;
687   InitModules(size,nmodules);
688   FillModules(evNumber,bgrev,nmodules,option,filename);
689
690   AliITSsimulation *sim      = 0;
691   AliITSmodule     *mod      = 0;
692   Int_t id;
693   for(Int_t module=0;module<geom->GetIndexMax();module++){
694     id       = geom->GetModuleType(module);
695     if (!all && !det[id]) continue;
696     sim      = (AliITSsimulation*)fDetTypeSim->GetSimulationModel(id);
697     if (!sim) {
698       Error("HitsToDigits","The simulation class was not "
699             "instanciated for module %d type %s!",module,
700             geom->GetModuleTypeName(module));
701       exit(1);
702     } // end if !sim
703     mod      = (AliITSmodule *)fITSmodules->At(module);
704     sim->DigitiseModule(mod,module,evNumber);
705     // fills all branches - wasted disk space
706     fLoader->TreeD()->Fill(); 
707     ResetDigits();
708   } // end for module
709   
710   ClearModules();
711   
712   fLoader->TreeD()->GetEntries();
713   fLoader->TreeD()->AutoSave();
714   // reset tree
715   fLoader->TreeD()->Reset();
716 }
717 //_____________________________________________________________________
718 void AliITS::Hits2PreDigits(){ 
719   // Turn hits into SDigits
720
721   if(!fDetTypeSim) {
722     Error("Hits2SDigits","fDetTypeSim is 0!");
723     return;
724   }
725    
726   fDetTypeSim->SetLoader((AliITSLoader*)fLoader);
727   SetDefaults();
728   
729   HitsToPreDigits(fLoader->GetRunLoader()->GetEventNumber(),
730                   0,-1," ",fOpt," ");
731 }
732
733 //______________________________________________________________________
734 void AliITS::HitsToPreDigits(Int_t evNumber,Int_t bgrev,Int_t size,
735                              Option_t *option,Option_t *opt,
736                              const char *filename){
737     //   Keep galice.root for signal and name differently the file for 
738     // background when add! otherwise the track info for signal will be lost !
739     // the condition below will disappear when the geom class will be
740     // initialized for all versions - for the moment it is only for v5 !
741     // 7 is the SDD beam test version.
742     // Inputs:
743     //      Int_t evnt       Event to be processed.
744     //      Int_t bgrev      Background Hit tree number.
745     //      Int_t nmodules   Not used.
746     //      Option_t *option String indicating if merging hits or not. To
747     //                       merge hits set equal to "Add". Otherwise no
748     //                       background hits are considered.
749     //      Test_t *filename File name containing the background hits..
750     // Outputs:
751     //      none.
752     // Return:
753     //      none.
754
755  
756   if(!fDetTypeSim) {
757     Error("HitsToPreDigits","fDetTypeSim is null!");
758     return;
759   }
760   fDetTypeSim->SetLoader((AliITSLoader*)fLoader);
761
762   if(!GetITSgeom()){
763     Error("HitsToPreDigits","fGeom is null!");
764     return; // need transformations to do digitization.
765   }
766   AliITSgeom *geom = GetITSgeom();
767
768   const char *all = strstr(opt,"All");
769   const char *det[3] = {strstr(opt,"SPD"),strstr(opt,"SDD"),
770                         strstr(opt,"SSD")};
771   static Bool_t setDef=kTRUE;
772   if (setDef) SetDefaultSimulation();
773   setDef=kFALSE;
774   
775   Int_t nmodules;
776   InitModules(size,nmodules);
777   FillModules(evNumber,bgrev,nmodules,option,filename);
778   
779
780   AliITSsimulation *sim      = 0;
781   AliITSmodule     *mod      = 0;
782   Int_t id,module;
783   for(module=0;module<geom->GetIndexMax();module++){
784     id       = geom->GetModuleType(module);
785     if (!all && !det[id]) continue;
786     sim      = (AliITSsimulation*)GetSimulationModel(id);
787     if (!sim) {
788       Error("HitsToPreDigits","The simulation class was not "
789             "instanciated for module %d type %s!",module,
790             geom->GetModuleTypeName(module));
791       exit(1);
792     } // end if !sim
793     mod      = (AliITSmodule *)fITSmodules->At(module);
794     sim->SDigitiseModule(mod,module,evNumber);
795     // fills all branches - wasted disk space
796     fLoader->TreeS()->Fill(); 
797     fDetTypeSim->ResetSDigits();
798   } // end for module
799
800   ClearModules();
801
802   
803   fLoader->TreeS()->GetEntries();
804   fLoader->TreeS()->AutoSave();
805   fLoader->WriteSDigits("OVERWRITE");
806   // reset tree
807   fLoader->TreeS()->Reset();
808 }
809
810 //_____________________________________________________________________
811 void AliITS::HitsToFastRecPoints(Int_t evNumber,Int_t bgrev,Int_t size,
812                                   Option_t *opt0,Option_t *opt1,
813                                  const char *flnm){
814     // keep galice.root for signal and name differently the file for 
815     // background when add! otherwise the track info for signal will be lost !
816     // the condition below will disappear when the geom class will be
817     // initialized for all versions - for the moment it is only for v5 !
818     // Inputs:
819     //      Int_t evnt       Event to be processed.
820     //      Int_t bgrev      Background Hit tree number.
821     //      Int_t size       Size used by InitModules. See InitModules.
822     //      Option_t *opt0   Option passed to FillModules. See FillModules.
823     //      Option_t *opt1   String indicating if merging hits or not. To
824     //                       merge hits set equal to "Add". Otherwise no
825     //                       background hits are considered.
826     //      Test_t *flnm     File name containing the background hits..
827     // Outputs:
828     //      none.
829     // Return:
830     //      none.
831
832
833
834   if(!GetITSgeom()){
835     Error("HitsToPreDigits","fGeom is null!");
836     return; // need transformations to do digitization.
837   }
838   AliITSgeom *geom = GetITSgeom();
839
840   AliITSLoader *pITSloader = (AliITSLoader*)fLoader;
841
842   const char *all = strstr(opt1,"All");
843   const char *det[3] ={strstr(opt1,"SPD"),strstr(opt1,"SDD"),
844                        strstr(opt1,"SSD")};
845   Int_t nmodules;
846   InitModules(size,nmodules);
847   FillModules(evNumber,bgrev,nmodules,opt0,flnm);
848
849   AliITSsimulation *sim      = 0;
850   AliITSmodule     *mod      = 0;
851   Int_t id,module;
852
853   TTree *lTR = pITSloader->TreeR();
854   if(!lTR) {
855     pITSloader->MakeTree("R");
856     lTR = pITSloader->TreeR();
857   }
858   
859   TClonesArray* ptarray = new TClonesArray("AliITSRecPoint",1000);
860   TBranch* branch = (TBranch*)lTR->Branch("ITSRecPointsF",&ptarray);
861   branch->SetAddress(&ptarray);
862   //m.b. : this change is nothing but a nice way to make sure
863   //the CPU goes up !    
864   for(module=0;module<geom->GetIndexMax();module++){
865     id       = geom->GetModuleType(module);
866     if (!all && !det[id]) continue;
867     sim      = (AliITSsimulation*)GetSimulationModel(id);
868     if (!sim) {
869       Error("HitsToFastPoints","The simulation class was not "
870             "instanciated for module %d type %x!",module,
871             geom->GetModuleTypeName(module));
872       exit(1);
873     } // end if !sim
874     mod      = (AliITSmodule *)fITSmodules->At(module);
875     sim->CreateFastRecPoints(mod,module,gRandom,ptarray);
876     lTR->Fill();
877   } // end for module
878
879   ClearModules();
880   fLoader->WriteRecPoints("OVERWRITE");
881   delete ptarray;
882 }
883 //_____________________________________________________________________
884 Int_t AliITS::Hits2Clusters(TTree *hTree, TTree *cTree) {
885   //------------------------------------------------------------
886   // This function creates ITS clusters
887   //------------------------------------------------------------
888   if(!GetITSgeom()){
889     Error("HitsToPreDigits","fGeom is null!");
890     return 1; // need transformations to do digitization.
891   }
892   AliITSgeom *geom=GetITSgeom();
893   Int_t mmax=geom->GetIndexMax();
894
895   InitModules(-1,mmax);
896   FillModules(hTree,0);
897
898   TClonesArray *points = new TClonesArray("AliITSRecPoint",1000);
899   TBranch *branch=cTree->GetBranch("ITSRecPoints");
900   if (!branch) cTree->Branch("ITSRecPoints",&points);
901   else branch->SetAddress(&points);
902
903   AliITSsimulationFastPoints sim;
904   Int_t ncl=0;
905   for (Int_t m=0; m<mmax; m++) {
906     AliITSmodule *mod=GetModule(m);      
907     sim.CreateFastRecPoints(mod,m,gRandom,points);      
908     ncl+=points->GetEntriesFast();
909     cTree->Fill();
910     points->Clear();
911   }
912
913   Info("Hits2Clusters","Number of found fast clusters : %d",ncl);
914
915   //cTree->Write();
916
917   delete points;
918   return 0;
919 }
920
921 //_____________________________________________________________________
922 void AliITS::CheckLabels(Int_t lab[3]) const {
923   //------------------------------------------------------------
924   // Tries to find mother's labels
925   //------------------------------------------------------------
926
927   if(lab[0]<0 && lab[1]<0 && lab[2]<0) return; // In case of no labels just exit
928
929   Int_t ntracks = gAlice->GetMCApp()->GetNtrack();
930   for (Int_t i=0;i<3;i++){
931     Int_t label = lab[i];
932     if (label>=0 && label<ntracks) {
933       TParticle *part=(TParticle*)gAlice->GetMCApp()->Particle(label);
934       if (part->P() < 0.005) {
935         Int_t m=part->GetFirstMother();
936         if (m<0) {      
937           continue;
938         }
939         if (part->GetStatusCode()>0) {
940           continue;
941         }
942         lab[i]=m;       
943       }
944     }    
945   }
946   
947 }
948
949 //______________________________________________________________________
950 void AliITS::SDigitsToDigits(Option_t *opt){
951     // Standard Summable digits to Digits function.
952     // Inputs:
953     //      none.
954     // Outputs:
955     //      none.
956     if(!fDetTypeSim) {
957       Error("SDigitsToSDigits","fDetTypeSim is 0!");
958       return;
959     }
960    
961     fDetTypeSim->SetLoader((AliITSLoader*)fLoader);
962     SetDefaults();
963     fDetTypeSim->SDigitsToDigits(opt,(Char_t*)GetName());
964
965 }
966
967 //______________________________________________________________________
968 void AliITS::ResetDigits(){
969     // Reset number of digits and the digits array for the ITS detector.
970     // Inputs:
971     //      none.
972     // Outputs:
973     //      none.
974     if(!fDetTypeSim) {
975       Error("ResetDigits","fDetTypeSim is 0!");
976       return;
977     }
978    
979     fDetTypeSim->ResetDigits();
980
981
982 }
983 //______________________________________________________________________
984 void AliITS::ResetDigits(Int_t branch){
985     // Reset number of digits and the digits array for this branch.
986     // Inputs:
987     //      none.
988     // Outputs:
989     //      none.
990
991     if(!fDetTypeSim) {
992       Error("ResetDigits","fDetTypeSim is 0!");
993       return;
994     }
995    
996     fDetTypeSim->ResetDigits(branch);
997
998 }
999 //______________________________________________________________________
1000 void AliITS::AddSumDigit(AliITSpListItem &sdig){
1001     // Adds the a module full of summable digits to the summable digits tree.
1002     // Inputs:
1003     //      AliITSpListItem &sdig   SDigit to be added to SDigits tree.
1004     // Outputs:
1005     //      none.
1006     // Return:
1007     //      none.
1008
1009     if(!fDetTypeSim) {
1010       Error("AddSumDigit","fDetTypeSim is 0!");
1011       return;
1012     }
1013     fDetTypeSim->AddSumDigit(sdig);
1014     
1015 }
1016 //______________________________________________________________________
1017 void AliITS::AddRealDigit(Int_t branch, Int_t *digits){
1018     //   Add a real digit - as coming from data.
1019     // Inputs:
1020     //      Int_t id        Detector type number.
1021     //      Int_t *digits   Integer array containing the digits info. See 
1022     //                      AliITSdigit.h
1023     // Outputs:
1024     //      none.
1025     // Return:
1026     //      none.
1027
1028     if(!fDetTypeSim) {
1029       Error("AddRealDigit","fDetTypeSim is 0!");
1030       return;
1031     }
1032     fDetTypeSim->AddRealDigit(branch,digits);
1033
1034 }
1035 //______________________________________________________________________
1036 void AliITS::AddSimDigit(Int_t branch, AliITSdigit *d){
1037     //    Add a simulated digit.
1038     // Inputs:
1039     //      Int_t id        Detector type number.
1040     //      AliITSdigit *d  Digit to be added to the Digits Tree. See 
1041     //                      AliITSdigit.h
1042     // Outputs:
1043     //      none.
1044     // Return:
1045     //      none.
1046
1047     if(!fDetTypeSim) {
1048       Error("AddSimDigit","fDetTypeSim is 0!");
1049       return;
1050     }
1051     fDetTypeSim->AddSimDigit(branch,d);
1052
1053 }
1054 //______________________________________________________________________
1055 void AliITS::AddSimDigit(Int_t branch,Float_t phys,Int_t *digits,Int_t *tracks,
1056                          Int_t *hits,Float_t *charges){
1057   //   Add a simulated digit to the list.
1058   // Inputs:
1059   //      Int_t id        Detector type number.
1060   //      Float_t phys    Physics indicator. See AliITSdigits.h
1061   //      Int_t *digits   Integer array containing the digits info. See 
1062   //                      AliITSdigit.h
1063   //      Int_t *tracks   Integer array [AliITSdigitS?D::GetNTracks()] 
1064   //                      containing the track numbers that contributed to
1065   //                      this digit.
1066   //      Int_t *hits     Integer array [AliITSdigitS?D::GetNTracks()]
1067   //                      containing the hit numbers, from AliITSmodule, that
1068   //                      contributed to this digit.
1069   //      Float_t *charge Floating point array of the signals contributed
1070   //                      to this digit by each track.
1071   // Outputs:
1072   //      none.
1073   // Return:
1074   //      none.
1075
1076     if(!fDetTypeSim) {
1077       Error("AddSimDigit","fDetTypeSim is 0!");
1078       return;
1079     }
1080     fDetTypeSim->AddSimDigit(branch,phys,digits,tracks,hits,charges);
1081
1082 }
1083 //______________________________________________________________________
1084 void AliITS::Digits2Raw(){
1085     // convert digits of the current event to raw data
1086
1087   if(!fDetTypeSim) {
1088     Error("Digits2Raw","fDetTypeSim is 0!");
1089     return;
1090   }
1091   fDetTypeSim->SetLoader((AliITSLoader*)fLoader);
1092   SetDefaults();
1093   fDetTypeSim->GetLoader()->LoadDigits();
1094   TTree* digits = fDetTypeSim->GetLoader()->TreeD();
1095   if (!digits) {
1096       Error("Digits2Raw", "no digits tree");
1097       return;
1098   }
1099   fDetTypeSim->SetTreeAddressD(digits,(Char_t*)GetName());
1100   AliITSDDLModuleMapSDD* ddlsdd=fDetTypeSim->GetDDLModuleMapSDD();
1101
1102   AliITSDDLRawData rawWriter;
1103   //Verbose level
1104   // 0: Silent
1105   // 1: cout messages
1106   // 2: txt files with digits 
1107   //BE CAREFUL, verbose level 2 MUST be used only for debugging and
1108   //it is highly suggested to use this mode only for debugging digits files
1109   //reasonably small, because otherwise the size of the txt files can reach
1110   //quickly several MB wasting time and disk space.
1111   rawWriter.SetVerbose(0);
1112     
1113   //SILICON PIXEL DETECTOR
1114   Info("Digits2Raw", "Formatting raw data for SPD");
1115   rawWriter.RawDataSPD(digits->GetBranch("ITSDigitsSPD"));
1116     
1117   //SILICON DRIFT DETECTOR
1118   Info("Digits2Raw", "Formatting raw data for SDD");
1119   rawWriter.RawDataSDD(digits->GetBranch("ITSDigitsSDD"),ddlsdd);
1120     
1121   //SILICON STRIP DETECTOR
1122   Info("Digits2Raw", "Formatting raw data for SSD");
1123   rawWriter.RawDataSSD(digits->GetBranch("ITSDigitsSSD"));
1124
1125   fLoader->UnloadDigits();
1126 }
1127 //______________________________________________________________________
1128 AliLoader* AliITS::MakeLoader(const char* topfoldername){ 
1129     //builds ITSgetter (AliLoader type)
1130     //if detector wants to use castomized getter, it must overload this method
1131
1132     AliDebug(1,Form("Creating AliITSLoader. Top folder is %s.",
1133          topfoldername));
1134     fLoader = new AliITSLoader(GetName(),topfoldername);
1135     return fLoader;
1136 }
1137
1138 Bool_t AliITS::Raw2SDigits(AliRawReader* rawReader)
1139 {
1140   //
1141   // Converts RAW data to SDigits
1142   //
1143   // Get TreeS
1144   //
1145     Int_t last   = -1;
1146     Int_t size   = GetITSgeom()->GetIndexMax();
1147     TClonesArray** modA = new TClonesArray*[size];
1148     for (Int_t mod = 0; mod < size; mod++) modA[mod] = new TClonesArray("AliITSpListItem", 10000);
1149     
1150     AliLoader* loader =  (gAlice->GetRunLoader())->GetLoader("ITSLoader");
1151     if (!loader)
1152     {
1153         Error("Open","Can not get ITS loader from Run Loader");
1154         return kFALSE;
1155     }
1156
1157     TTree* tree = 0;
1158     tree = loader->TreeS();
1159     if (!tree)
1160     {
1161         loader->MakeTree("S");
1162         tree = loader->TreeS();
1163     }
1164     //
1165     // Array for SDigits
1166     // 
1167     TClonesArray aSDigits("AliITSpListItem",10000), *itsSDigits=&aSDigits;
1168     Int_t bufsize = 32000;
1169     tree->Branch("ITS", &itsSDigits, bufsize);
1170     Int_t npx = 0;
1171     //
1172     // SPD
1173     //
1174     AliITSsegmentationSPD* segSPD = (AliITSsegmentationSPD*) fDetTypeSim->GetSegmentationModel(0);
1175     if(!segSPD){
1176       AliWarning("Set AliITS defaults");
1177       SetDefaults();
1178       segSPD = (AliITSsegmentationSPD*) fDetTypeSim->GetSegmentationModel(0);
1179     }
1180     npx = segSPD->Npx();
1181     Double_t thr, sigma; 
1182     
1183     AliITSRawStreamSPD inputSPD(rawReader);
1184     while(1){
1185         Bool_t next  = inputSPD.Next();
1186         if (!next) break;
1187
1188         Int_t module = inputSPD.GetModuleID();
1189         Int_t column = inputSPD.GetColumn();
1190         Int_t row    = inputSPD.GetRow();
1191         Int_t index  = npx * column + row;
1192
1193         if (module >= size) continue;
1194  
1195         last = (modA[module])->GetEntries();
1196         TClonesArray& dum = *modA[module];
1197         fDetTypeSim->GetCalibrationModel(module)->Thresholds(thr,sigma);
1198         thr += 1.;
1199         new (dum[last]) AliITSpListItem(-1, -1, module, index, thr);
1200     }
1201     rawReader->Reset();
1202
1203     //
1204     // SDD
1205     // 
1206     AliITSsegmentationSDD* segSDD = (AliITSsegmentationSDD*) fDetTypeSim->GetSegmentationModel(1);
1207     npx = segSDD->Npx();
1208     AliITSRawStreamSDD inputSDD(rawReader);
1209     AliITSDDLModuleMapSDD* ddlmap=fDetTypeSim->GetDDLModuleMapSDD();
1210     inputSDD.SetDDLModuleMap(ddlmap);
1211     while(1){
1212         Bool_t next  = inputSDD.Next();
1213         if (!next) break;
1214
1215         Int_t module = inputSDD.GetModuleID();
1216         Int_t anode  = inputSDD.GetAnode();
1217         Int_t time   = inputSDD.GetTime();
1218         Int_t signal10 = inputSDD.GetSignal();
1219         Int_t index  = npx * anode + time;
1220
1221         if (module >= size) continue;
1222         /* 8->10 bit expansion is done in AliITSRawStreamSDD
1223         // 8bit -> 10 bit
1224         AliITSresponseSDD *resSDD = (AliITSresponseSDD*) fDetTypeSim->GetResponse(1);
1225         Int_t signal10 = resSDD->Convert8to10(signal);  // signal is a 8 bit value (if the compression is active)
1226         */
1227         last = modA[module]->GetEntries();
1228         TClonesArray& dum = *modA[module];
1229         new (dum[last]) AliITSpListItem(-1, -1, module, index, Double_t(signal10));
1230         ((AliITSpListItem*) dum.At(last))->AddSignalAfterElect(module, index, Double_t(signal10));
1231         
1232     }
1233     rawReader->Reset();
1234
1235     //
1236     // SSD
1237     // 
1238     AliITSsegmentationSSD* segSSD = (AliITSsegmentationSSD*) fDetTypeSim->GetSegmentationModel(2);
1239     npx = segSSD->Npx();
1240     AliITSRawStreamSSD inputSSD(rawReader);
1241     while(1){
1242         Bool_t next  = inputSSD.Next();
1243         if (!next) break;
1244
1245         Int_t module  = inputSSD.GetModuleID();
1246         Int_t side    = inputSSD.GetSideFlag();
1247         Int_t strip   = inputSSD.GetStrip();
1248         Int_t signal  = inputSSD.GetSignal();
1249         Int_t index  = npx * side + strip;
1250
1251         if (module >= size) continue;
1252         
1253         last = modA[module]->GetEntries();
1254         TClonesArray& dum = *modA[module];
1255         new (dum[last]) AliITSpListItem(-1, -1, module, index, Double_t(signal));
1256     }
1257     rawReader->Reset();
1258      AliITSpListItem* sdig = 0;
1259     
1260     for (Int_t mod = 0; mod < size; mod++)
1261     {
1262         Int_t nsdig =  modA[mod]->GetEntries();
1263         for (Int_t ie = 0; ie < nsdig; ie++) {
1264             sdig = (AliITSpListItem*) (modA[mod]->At(ie));
1265             new (aSDigits[ie]) AliITSpListItem(-1, -1, mod, sdig->GetIndex(), sdig->GetSignal());
1266             Float_t sig = sdig->GetSignalAfterElect();
1267             if (sig > 0.) {
1268                 sdig = (AliITSpListItem*)aSDigits[ie];
1269                 sdig->AddSignalAfterElect(mod, sdig->GetIndex(), Double_t(sig));
1270             }
1271         }
1272         
1273         tree->Fill();
1274         aSDigits.Clear();
1275         modA[mod]->Clear();
1276     }
1277     loader->WriteSDigits("OVERWRITE");    
1278     delete modA;
1279     return kTRUE;
1280 }
1281
1282
1283 //______________________________________________________________________
1284 void AliITS::UpdateInternalGeometry(){
1285
1286   //reads new geometry from TGeo 
1287 //   AliDebug(1,"Delete ITSgeom and create a new one reading TGeo");
1288
1289   AliITSVersion_t version = (AliITSVersion_t)IsVersion();
1290   Int_t minor = 0;
1291   if(version==kvPPRasymmFMD) minor=2;  // default minor version for this geom.
1292   AliITSInitGeometry initgeom;
1293   AliITSgeom* geom = initgeom.CreateAliITSgeom(version,minor);
1294   SetITSgeom(geom);
1295 }
1296