]> git.uio.no Git - u/mrichter/AliRoot.git/blob - STEER/AliSimulation.cxx
Added the method AddDateToComment, adding the current date to the comment datamember.
[u/mrichter/AliRoot.git] / STEER / AliSimulation.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 // class for running generation, simulation and digitization                 //
21 //                                                                           //
22 // Hits, sdigits and digits are created for all detectors by typing:         //
23 //                                                                           //
24 //   AliSimulation sim;                                                      //
25 //   sim.Run();                                                              //
26 //                                                                           //
27 // The Run method returns kTRUE in case of successful execution.             //
28 // The number of events can be given as argument to the Run method or it     //
29 // can be set by                                                             //
30 //                                                                           //
31 //   sim.SetNumberOfEvents(n);                                               //
32 //                                                                           //
33 // The name of the configuration file can be passed as argument to the       //
34 // AliSimulation constructor or can be specified by                          //
35 //                                                                           //
36 //   sim.SetConfigFile("...");                                               //
37 //                                                                           //
38 // The generation of particles and the simulation of detector hits can be    //
39 // switched on or off by                                                     //
40 //                                                                           //
41 //   sim.SetRunGeneration(kTRUE);   // generation of primary particles       //
42 //   sim.SetRunSimulation(kFALSE);  // but no tracking                       //
43 //                                                                           //
44 // For which detectors sdigits and digits will be created, can be steered    //
45 // by                                                                        //
46 //                                                                           //
47 //   sim.SetMakeSDigits("ALL");     // make sdigits for all detectors        //
48 //   sim.SetMakeDigits("ITS TPC");  // make digits only for ITS and TPC      //
49 //                                                                           //
50 // The argument is a (case sensitive) string with the names of the           //
51 // detectors separated by a space. An empty string ("") can be used to       //
52 // disable the creation of sdigits or digits. The special string "ALL"       //
53 // selects all available detectors. This is the default.                     //
54 //                                                                           //
55 // The creation of digits from hits instead of from sdigits can be selected  //
56 // by                                                                        //
57 //                                                                           //
58 //   sim.SetMakeDigitsFromHits("TRD");                                       //
59 //                                                                           //
60 // The argument is again a string with the selected detectors. Be aware that //
61 // this feature is not available for all detectors and that merging is not   //
62 // possible, when digits are created directly from hits.                     //
63 //                                                                           //
64 // Background events can be merged by calling                                //
65 //                                                                           //
66 //   sim.MergeWith("background/galice.root", 2);                             //
67 //                                                                           //
68 // The first argument is the file name of the background galice file. The    //
69 // second argument is the number of signal events per background event.      //
70 // By default this number is calculated from the number of available         //
71 // background events. MergeWith can be called several times to merge more    //
72 // than two event streams. It is assumed that the sdigits were already       //
73 // produced for the background events.                                       //
74 //                                                                           //
75 // The output of raw data can be switched on by calling                      //
76 //                                                                           //
77 //   sim.SetWriteRawData("MUON");   // write raw data for MUON               //
78 //                                                                           //
79 // The default output format of the raw data are DDL files. They are         //
80 // converted to a DATE file, if a file name is given as second argument.     //
81 // For this conversion the program "dateStream" is required. If the file     //
82 // name has the extension ".root", the DATE file is converted to a root      //
83 // file. The program "alimdc" is used for this purpose. For the conversion   //
84 // to DATE and root format the two conversion programs have to be installed. //
85 // Only the raw data in the final format is kept if the third argument is    //
86 // kTRUE.                                                                    //
87 //                                                                           //
88 // The methods RunSimulation, RunSDigitization, RunDigitization,             //
89 // RunHitsDigitization and WriteRawData can be used to run only parts of     //
90 // the full simulation chain. The creation of raw data DDL files and their   //
91 // conversion to the DATE or root format can be run directly by calling      //
92 // the methods WriteRawFiles, ConvertRawFilesToDate and ConvertDateToRoot.   //
93 //                                                                           //
94 // The default number of events per file, which is usually set in the        //
95 // config file, can be changed for individual detectors and data types       //
96 // by calling                                                                //
97 //                                                                           //
98 //   sim.SetEventsPerFile("PHOS", "Reconstructed Points", 3);                //
99 //                                                                           //
100 // The first argument is the detector, the second one the data type and the  //
101 // last one the number of events per file. Valid data types are "Hits",      //
102 // "Summable Digits", "Digits", "Reconstructed Points" and "Tracks".         //
103 // The number of events per file has to be set before the simulation of      //
104 // hits. Otherwise it has no effect.                                         //
105 //                                                                           //
106 ///////////////////////////////////////////////////////////////////////////////
107
108 #include <TCint.h>
109 #include <TFile.h>
110 #include <TGeoGlobalMagField.h>
111 #include <TGeoManager.h>
112 #include <TObjString.h>
113 #include <TROOT.h>
114 #include <TSystem.h>
115 #include <TVirtualMC.h>
116 #include <TVirtualMCApplication.h>
117 #include <TDatime.h>
118
119 #include "AliAlignObj.h"
120 #include "AliCDBEntry.h"
121 #include "AliCDBManager.h"
122 #include "AliCDBStorage.h"
123 #include "AliCTPRawData.h"
124 #include "AliCentralTrigger.h"
125 #include "AliCentralTrigger.h"
126 #include "AliCodeTimer.h"
127 #include "AliDAQ.h"
128 #include "AliDigitizer.h"
129 #include "AliESDEvent.h"
130 #include "AliGRPObject.h"
131 #include "AliGenEventHeader.h"
132 #include "AliGenerator.h"
133 #include "AliGeomManager.h"
134 #include "AliHLTSimulation.h"
135 #include "AliHeader.h"
136 #include "AliLego.h"
137 #include "AliLegoGenerator.h"
138 #include "AliLog.h"
139 #include "AliMC.h"
140 #include "AliMagF.h"
141 #include "AliModule.h"
142 #include "AliPDG.h"
143 #include "AliRawReaderDate.h"
144 #include "AliRawReaderFile.h"
145 #include "AliRawReaderRoot.h"
146 #include "AliRun.h"
147 #include "AliRunDigitizer.h"
148 #include "AliRunLoader.h"
149 #include "AliSimulation.h"
150 #include "AliSysInfo.h"
151 #include "AliVertexGenFile.h"
152
153 ClassImp(AliSimulation)
154
155 AliSimulation *AliSimulation::fgInstance = 0;
156 const char* AliSimulation::fgkDetectorName[AliSimulation::fgkNDetectors] = {"ITS", "TPC", "TRD", "TOF", "PHOS", "HMPID", "EMCAL", "MUON", "FMD", "ZDC", "PMD", "T0", "VZERO", "ACORDE", "HLT"};
157
158 //_____________________________________________________________________________
159 AliSimulation::AliSimulation(const char* configFileName,
160                              const char* name, const char* title) :
161   TNamed(name, title),
162
163   fRunGeneration(kTRUE),
164   fRunSimulation(kTRUE),
165   fLoadAlignFromCDB(kTRUE),
166   fLoadAlObjsListOfDets("ALL"),
167   fMakeSDigits("ALL"),
168   fMakeDigits("ALL"),
169   fTriggerConfig(""),
170   fMakeDigitsFromHits(""),
171   fWriteRawData(""),
172   fRawDataFileName(""),
173   fDeleteIntermediateFiles(kFALSE),
174   fWriteSelRawData(kFALSE),
175   fStopOnError(kFALSE),
176   fNEvents(1),
177   fConfigFileName(configFileName),
178   fGAliceFileName("galice.root"),
179   fEventsPerFile(),
180   fBkgrdFileNames(NULL),
181   fAlignObjArray(NULL),
182   fUseBkgrdVertex(kTRUE),
183   fRegionOfInterest(kFALSE),
184   fCDBUri(""),
185   fQARefUri(""), 
186   fSpecCDBUri(),
187   fRun(-1),
188   fSeed(0),
189   fInitCDBCalled(kFALSE),
190   fInitRunNumberCalled(kFALSE),
191   fSetRunNumberFromDataCalled(kFALSE),
192   fEmbeddingFlag(kFALSE),
193   fLego(NULL),
194   fQADetectors("ALL"),                  
195   fQATasks("ALL"),      
196   fRunQA(kTRUE), 
197   fEventSpecie(AliRecoParam::kDefault),
198   fWriteQAExpertData(kTRUE), 
199   fGeometryFile(),
200   fRunHLT("default"),
201   fpHLT(NULL),
202   fWriteGRPEntry(kTRUE)
203 {
204 // create simulation object with default parameters
205   fgInstance = this;
206   SetGAliceFile("galice.root");
207   
208 // for QA
209         AliQAManager * qam = AliQAManager::QAManager(AliQAv1::kSIMMODE) ; 
210         qam->SetActiveDetectors(fQADetectors) ; 
211         fQATasks = Form("%d %d %d", AliQAv1::kHITS, AliQAv1::kSDIGITS, AliQAv1::kDIGITS) ; 
212         qam->SetTasks(fQATasks) ;       
213 }
214
215 //_____________________________________________________________________________
216 AliSimulation::~AliSimulation()
217 {
218 // clean up
219
220   fEventsPerFile.Delete();
221 //  if(fAlignObjArray) fAlignObjArray->Delete(); // fAlignObjArray->RemoveAll() ???
222 //  delete fAlignObjArray; fAlignObjArray=0;
223
224   if (fBkgrdFileNames) {
225     fBkgrdFileNames->Delete();
226     delete fBkgrdFileNames;
227   }
228
229   fSpecCDBUri.Delete();
230   if (fgInstance==this) fgInstance = 0;
231
232   AliQAManager::QAManager()->ShowQA() ; 
233   AliQAManager::Destroy() ;     
234   AliCodeTimer::Instance()->Print();
235 }
236
237
238 //_____________________________________________________________________________
239 void AliSimulation::SetNumberOfEvents(Int_t nEvents)
240 {
241 // set the number of events for one run
242
243   fNEvents = nEvents;
244 }
245
246 //_____________________________________________________________________________
247 void AliSimulation::InitQA()
248 {
249   // activate a default CDB storage
250   // First check if we have any CDB storage set, because it is used 
251   // to retrieve the calibration and alignment constants
252   
253   if (fInitCDBCalled) return;
254   fInitCDBCalled = kTRUE;
255
256   AliQAManager * qam = AliQAManager::QAManager(AliQAv1::kSIMMODE) ; 
257   qam->SetActiveDetectors(fQADetectors) ; 
258   fQATasks = Form("%d %d %d", AliQAv1::kHITS, AliQAv1::kSDIGITS, AliQAv1::kDIGITS) ; 
259   qam->SetTasks(fQATasks) ;
260         if (fWriteQAExpertData)
261     qam->SetWriteExpert() ; 
262   
263   if (qam->IsDefaultStorageSet()) {
264     AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
265     AliWarning("Default QA reference storage has been already set !");
266     AliWarning(Form("Ignoring the default storage declared in AliSimulation: %s",fQARefUri.Data()));
267     AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
268     fQARefUri = qam->GetDefaultStorage()->GetURI();
269   } else {
270       if (fQARefUri.Length() > 0) {
271         AliDebug(2,"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
272         AliDebug(2, Form("Default QA reference storage is set to: %s", fQARefUri.Data()));
273         AliDebug(2, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
274       } else {
275         fQARefUri="local://$ALICE_ROOT/QARef";
276         AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
277         AliWarning("Default QA reference storage not yet set !!!!");
278         AliWarning(Form("Setting it now to: %s", fQARefUri.Data()));
279         AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
280       }
281     qam->SetDefaultStorage(fQARefUri);
282   }
283 }
284
285 //_____________________________________________________________________________
286 void AliSimulation::InitCDB()
287 {
288 // activate a default CDB storage
289 // First check if we have any CDB storage set, because it is used 
290 // to retrieve the calibration and alignment constants
291
292   if (fInitCDBCalled) return;
293   fInitCDBCalled = kTRUE;
294
295   AliCDBManager* man = AliCDBManager::Instance();
296   if (man->IsDefaultStorageSet())
297   {
298     AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
299     AliWarning("Default CDB storage has been already set !");
300     AliWarning(Form("Ignoring the default storage declared in AliSimulation: %s",fCDBUri.Data()));
301     AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
302     fCDBUri = man->GetDefaultStorage()->GetURI();
303   }
304   else {
305     if (fCDBUri.Length() > 0) 
306     {
307         AliDebug(2,"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
308         AliDebug(2, Form("Default CDB storage is set to: %s", fCDBUri.Data()));
309         AliDebug(2, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
310     } else {
311         fCDBUri="local://$ALICE_ROOT/OCDB";
312         AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
313         AliWarning("Default CDB storage not yet set !!!!");
314         AliWarning(Form("Setting it now to: %s", fCDBUri.Data()));
315         AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
316                 
317     }
318     man->SetDefaultStorage(fCDBUri);
319   }
320
321   // Now activate the detector specific CDB storage locations
322   for (Int_t i = 0; i < fSpecCDBUri.GetEntriesFast(); i++) {
323     TObject* obj = fSpecCDBUri[i];
324     if (!obj) continue;
325     AliDebug(2, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
326     AliDebug(2, Form("Specific CDB storage for %s is set to: %s",obj->GetName(),obj->GetTitle()));
327     AliDebug(2, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
328     man->SetSpecificStorage(obj->GetName(), obj->GetTitle());
329   }
330       
331 }
332
333 //_____________________________________________________________________________
334 void AliSimulation::InitRunNumber(){
335 // check run number. If not set, set it to 0 !!!!
336   
337   if (fInitRunNumberCalled) return;
338   fInitRunNumberCalled = kTRUE;
339   
340   AliCDBManager* man = AliCDBManager::Instance();
341   if (man->GetRun() >= 0)
342   {
343         AliFatal(Form("Run number cannot be set in AliCDBManager before start of simulation: "
344                         "Use external variable DC_RUN or AliSimulation::SetRun()!"));
345   }
346     
347   if(fRun >= 0) {
348         AliDebug(2, Form("Setting CDB run number to: %d",fRun));
349   } else {
350         fRun=0;
351         AliWarning(Form("Run number not yet set !!!! Setting it now to: %d",
352                         fRun));
353   }
354   man->SetRun(fRun);
355
356   man->Print();
357
358 }
359
360 //_____________________________________________________________________________
361 void AliSimulation::SetCDBLock() {
362   // Set CDB lock: from now on it is forbidden to reset the run number
363   // or the default storage or to activate any further storage!
364   
365   AliCDBManager::Instance()->SetLock(1);
366 }
367
368 //_____________________________________________________________________________
369 void AliSimulation::SetDefaultStorage(const char* uri) {
370   // Store the desired default CDB storage location
371   // Activate it later within the Run() method
372   
373   fCDBUri = uri;
374   
375 }
376
377 //_____________________________________________________________________________
378 void AliSimulation::SetQARefDefaultStorage(const char* uri) {
379   // Store the desired default CDB storage location
380   // Activate it later within the Run() method
381   
382   fQARefUri = uri;
383   AliQAv1::SetQARefStorage(fQARefUri.Data()) ;
384 }
385
386 //_____________________________________________________________________________
387 void AliSimulation::SetSpecificStorage(const char* calibType, const char* uri) {
388 // Store a detector-specific CDB storage location
389 // Activate it later within the Run() method
390
391   AliCDBPath aPath(calibType);
392   if(!aPath.IsValid()){
393         AliError(Form("Not a valid path: %s", calibType));
394         return;
395   }
396
397   TObject* obj = fSpecCDBUri.FindObject(calibType);
398   if (obj) fSpecCDBUri.Remove(obj);
399   fSpecCDBUri.Add(new TNamed(calibType, uri));
400
401 }
402
403 //_____________________________________________________________________________
404 void AliSimulation::SetRunNumber(Int_t run)
405 {
406 // sets run number
407 // Activate it later within the Run() method
408
409         fRun = run;
410 }
411
412 //_____________________________________________________________________________
413 void AliSimulation::SetSeed(Int_t seed)
414 {
415 // sets seed number
416 // Activate it later within the Run() method
417
418         fSeed = seed;
419 }
420
421 //_____________________________________________________________________________
422 Bool_t AliSimulation::SetRunNumberFromData()
423 {
424   // Set the CDB manager run number
425   // The run number is retrieved from gAlice
426
427     if (fSetRunNumberFromDataCalled) return kTRUE;
428     fSetRunNumberFromDataCalled = kTRUE;    
429   
430     AliCDBManager* man = AliCDBManager::Instance();
431     Int_t runData = -1, runCDB = -1;
432   
433     AliRunLoader* runLoader = LoadRun("READ");
434     if (!runLoader) return kFALSE;
435     else {
436         runData = runLoader->GetHeader()->GetRun();
437         delete runLoader;
438     }
439   
440     runCDB = man->GetRun();
441     if(runCDB >= 0) {
442         if (runCDB != runData) {
443                 AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
444                 AliWarning(Form("A run number was previously set in AliCDBManager: %d !", runCDB));
445                 AliWarning(Form("It will be replaced with the run number got from run header: %d !", runData));
446                 AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");    
447         }
448         
449     }
450       
451     man->SetRun(runData);
452     fRun = runData;
453     
454     if(man->GetRun() < 0) {
455         AliError("Run number not properly initalized!");
456         return kFALSE;
457     }
458   
459     man->Print();
460     
461     return kTRUE;
462 }
463
464 //_____________________________________________________________________________
465 void AliSimulation::SetConfigFile(const char* fileName)
466 {
467 // set the name of the config file
468
469   fConfigFileName = fileName;
470 }
471
472 //_____________________________________________________________________________
473 void AliSimulation::SetGAliceFile(const char* fileName)
474 {
475 // set the name of the galice file
476 // the path is converted to an absolute one if it is relative
477
478   fGAliceFileName = fileName;
479   if (!gSystem->IsAbsoluteFileName(fGAliceFileName)) {
480     char* absFileName = gSystem->ConcatFileName(gSystem->WorkingDirectory(),
481                                                 fGAliceFileName);
482     fGAliceFileName = absFileName;
483     delete[] absFileName;
484   }
485
486   AliDebug(2, Form("galice file name set to %s", fileName));
487 }
488
489 //_____________________________________________________________________________
490 void AliSimulation::SetEventsPerFile(const char* detector, const char* type, 
491                                      Int_t nEvents)
492 {
493 // set the number of events per file for the given detector and data type
494 // ("Hits", "Summable Digits", "Digits", "Reconstructed Points" or "Tracks")
495
496   TNamed* obj = new TNamed(detector, type);
497   obj->SetUniqueID(nEvents);
498   fEventsPerFile.Add(obj);
499 }
500
501 //_____________________________________________________________________________
502 Bool_t AliSimulation::MisalignGeometry(AliRunLoader *runLoader)
503 {
504   // Read the alignment objects from CDB.
505   // Each detector is supposed to have the
506   // alignment objects in DET/Align/Data CDB path.
507   // All the detector objects are then collected,
508   // sorted by geometry level (starting from ALIC) and
509   // then applied to the TGeo geometry.
510   // Finally an overlaps check is performed.
511
512   if (!AliGeomManager::GetGeometry() || !AliGeomManager::GetGeometry()->IsClosed()) {
513     AliError("Can't apply the misalignment! Geometry is not loaded or it is still opened!");
514     return kFALSE;
515   }  
516   
517   // initialize CDB storage, run number, set CDB lock
518   InitCDB();
519 //  if (!SetRunNumberFromData()) if (fStopOnError) return kFALSE;
520   SetCDBLock();
521     
522   Bool_t delRunLoader = kFALSE;
523   if (!runLoader) {
524     runLoader = LoadRun("READ");
525     if (!runLoader) return kFALSE;
526     delRunLoader = kTRUE;
527   }
528   
529   // Export ideal geometry 
530   if(!IsGeometryFromFile()) AliGeomManager::GetGeometry()->Export("geometry.root");
531
532   // Load alignment data from CDB and apply to geometry through AliGeomManager
533   if(fLoadAlignFromCDB){
534     
535     TString detStr = fLoadAlObjsListOfDets;
536     TString loadAlObjsListOfDets = "";
537     
538     TObjArray* detArray = runLoader->GetAliRun()->Detectors();
539     for (Int_t iDet = 0; iDet < detArray->GetEntriesFast(); iDet++) {
540       AliModule* det = (AliModule*) detArray->At(iDet);
541       if (!det || !det->IsActive()) continue;
542       if (IsSelected(det->GetName(), detStr)) {
543         //add det to list of dets to be aligned from CDB
544         loadAlObjsListOfDets += det->GetName();
545         loadAlObjsListOfDets += " ";
546       }
547     } // end loop over detectors
548     loadAlObjsListOfDets.Prepend("GRP "); //add alignment objects for non-sensitive modules
549     AliGeomManager::ApplyAlignObjsFromCDB(loadAlObjsListOfDets.Data());
550   }else{
551     // Check if the array with alignment objects was
552     // provided by the user. If yes, apply the objects
553     // to the present TGeo geometry
554     if (fAlignObjArray) {
555       if (AliGeomManager::ApplyAlignObjsToGeom(*fAlignObjArray) == kFALSE) {
556         AliError("The misalignment of one or more volumes failed!"
557                  "Compare the list of simulated detectors and the list of detector alignment data!");
558         if (delRunLoader) delete runLoader;
559         return kFALSE;
560       }
561     }
562   }
563
564   // Update the internal geometry of modules (ITS needs it)
565   TString detStr = fLoadAlObjsListOfDets;
566   TObjArray* detArray = runLoader->GetAliRun()->Detectors();
567   for (Int_t iDet = 0; iDet < detArray->GetEntriesFast(); iDet++) {
568
569     AliModule* det = (AliModule*) detArray->At(iDet);
570     if (!det || !det->IsActive()) continue;
571     if (IsSelected(det->GetName(), detStr)) {
572       det->UpdateInternalGeometry();
573     }
574   } // end loop over detectors
575
576
577   if (delRunLoader) delete runLoader;
578
579   return kTRUE;
580 }
581
582 //_____________________________________________________________________________
583 void AliSimulation::MergeWith(const char* fileName, Int_t nSignalPerBkgrd)
584 {
585 // add a file with background events for merging
586
587   TObjString* fileNameStr = new TObjString(fileName);
588   fileNameStr->SetUniqueID(nSignalPerBkgrd);
589   if (!fBkgrdFileNames) fBkgrdFileNames = new TObjArray;
590   fBkgrdFileNames->Add(fileNameStr);
591 }
592
593 void AliSimulation::EmbedInto(const char* fileName, Int_t nSignalPerBkgrd)
594 {
595 // add a file with background events for embeddin
596   MergeWith(fileName, nSignalPerBkgrd);
597   fEmbeddingFlag = kTRUE;
598 }
599
600 //_____________________________________________________________________________
601 Bool_t AliSimulation::Run(Int_t nEvents)
602 {
603 // run the generation, simulation and digitization
604
605  
606   AliCodeTimerAuto("",0)
607   AliSysInfo::AddStamp("Start_Run");
608   
609   // Load run number and seed from environmental vars
610   ProcessEnvironmentVars();
611   AliSysInfo::AddStamp("ProcessEnvironmentVars");
612
613   gRandom->SetSeed(fSeed);
614    
615   if (nEvents > 0) fNEvents = nEvents;
616
617   // create and setup the HLT instance
618   if (!fRunHLT.IsNull() && !CreateHLT()) {
619     if (fStopOnError) return kFALSE;
620     // disable HLT
621     fRunHLT="";
622   }
623   
624   // generation and simulation -> hits
625   if (fRunGeneration) {
626     if (!RunSimulation()) if (fStopOnError) return kFALSE;
627   }
628   AliSysInfo::AddStamp("RunSimulation");
629            
630   // initialize CDB storage from external environment
631   // (either CDB manager or AliSimulation setters),
632   // if not already done in RunSimulation()
633   InitCDB();
634   AliSysInfo::AddStamp("InitCDB");
635   
636   // Set run number in CDBManager from data 
637   // From this point on the run number must be always loaded from data!
638   if (!SetRunNumberFromData()) if (fStopOnError) return kFALSE;
639   
640   // Set CDB lock: from now on it is forbidden to reset the run number
641   // or the default storage or to activate any further storage!
642   SetCDBLock();
643
644   // If RunSimulation was not called, load the geometry and misalign it
645   if (!AliGeomManager::GetGeometry()) {
646     // Initialize the geometry manager
647     AliGeomManager::LoadGeometry("geometry.root");
648   AliSysInfo::AddStamp("GetGeometry");
649
650     
651 //    // Check that the consistency of symbolic names for the activated subdetectors
652 //    // in the geometry loaded by AliGeomManager
653 //    AliRunLoader* runLoader = LoadRun("READ");
654 //    if (!runLoader) return kFALSE;
655 //
656 //    TString detsToBeChecked = "";
657 //    TObjArray* detArray = runLoader->GetAliRun()->Detectors();
658 //    for (Int_t iDet = 0; iDet < detArray->GetEntriesFast(); iDet++) {
659 //      AliModule* det = (AliModule*) detArray->At(iDet);
660 //      if (!det || !det->IsActive()) continue;
661 //      detsToBeChecked += det->GetName();
662 //      detsToBeChecked += " ";
663 //    } // end loop over detectors
664 //    if(!AliGeomManager::CheckSymNamesLUT(detsToBeChecked.Data()))
665     if(!AliGeomManager::CheckSymNamesLUT("ALL"))
666         AliFatalClass("Current loaded geometry differs in the definition of symbolic names!");
667         
668     if (!AliGeomManager::GetGeometry()) if (fStopOnError) return kFALSE;
669     // Misalign geometry
670     if(!MisalignGeometry()) if (fStopOnError) return kFALSE;
671   }
672   AliSysInfo::AddStamp("MissalignGeometry");
673
674
675   // hits -> summable digits
676   AliSysInfo::AddStamp("Start_sdigitization");
677   if (!fMakeSDigits.IsNull()) {
678     if (!RunSDigitization(fMakeSDigits)) if (fStopOnError) return kFALSE;
679  
680   }
681   AliSysInfo::AddStamp("Stop_sdigitization");
682   
683   AliSysInfo::AddStamp("Start_digitization");  
684   // summable digits -> digits  
685   if (!fMakeDigits.IsNull()) {
686     if (!RunDigitization(fMakeDigits, fMakeDigitsFromHits)) {
687       if (fStopOnError) return kFALSE;
688     }
689    }
690   AliSysInfo::AddStamp("Stop_digitization");
691
692   
693   
694   // hits -> digits
695   if (!fMakeDigitsFromHits.IsNull()) {
696     if (fBkgrdFileNames && (fBkgrdFileNames->GetEntriesFast() > 0)) {
697       AliWarning(Form("Merging and direct creation of digits from hits " 
698                  "was selected for some detectors. "
699                  "No merging will be done for the following detectors: %s",
700                  fMakeDigitsFromHits.Data()));
701     }
702     if (!RunHitsDigitization(fMakeDigitsFromHits)) {
703       if (fStopOnError) return kFALSE;
704     }
705   }
706
707   AliSysInfo::AddStamp("Hits2Digits");
708   
709   
710   // digits -> trigger
711   if (!RunTrigger(fTriggerConfig,fMakeDigits)) {
712     if (fStopOnError) return kFALSE;
713   }
714
715   AliSysInfo::AddStamp("RunTrigger");
716   
717   
718   // digits -> raw data
719   if (!fWriteRawData.IsNull()) {
720     if (!WriteRawData(fWriteRawData, fRawDataFileName, 
721                       fDeleteIntermediateFiles,fWriteSelRawData)) {
722       if (fStopOnError) return kFALSE;
723     }
724   }
725
726   AliSysInfo::AddStamp("WriteRaw");
727   
728   // run HLT simulation on simulated digit data if raw data is not
729   // simulated, otherwise its called as part of WriteRawData
730   if (!fRunHLT.IsNull() && fWriteRawData.IsNull()) {
731     if (!RunHLT()) {
732       if (fStopOnError) return kFALSE;
733     }
734   }
735
736   AliSysInfo::AddStamp("RunHLT");
737   
738   //QA
739         if (fRunQA) {
740                 Bool_t rv = RunQA() ; 
741                 if (!rv)
742                         if (fStopOnError) 
743                                 return kFALSE ;         
744         }
745
746   AliSysInfo::AddStamp("RunQA");
747
748   // Cleanup of CDB manager: cache and active storages!
749   AliCDBManager::Instance()->ClearCache();
750
751   return kTRUE;
752 }
753
754 //_______________________________________________________________________
755 Bool_t AliSimulation::RunLego(const char *setup, Int_t nc1, Float_t c1min,
756                      Float_t c1max,Int_t nc2,Float_t c2min,Float_t c2max,
757                      Float_t rmin,Float_t rmax,Float_t zmax, AliLegoGenerator* gener, Int_t nev)
758 {
759   //
760   // Generates lego plots of:
761   //    - radiation length map phi vs theta
762   //    - radiation length map phi vs eta
763   //    - interaction length map
764   //    - g/cm2 length map
765   //
766   //  ntheta    bins in theta, eta
767   //  themin    minimum angle in theta (degrees)
768   //  themax    maximum angle in theta (degrees)
769   //  nphi      bins in phi
770   //  phimin    minimum angle in phi (degrees)
771   //  phimax    maximum angle in phi (degrees)
772   //  rmin      minimum radius
773   //  rmax      maximum radius
774   //  
775   //
776   //  The number of events generated = ntheta*nphi
777   //  run input parameters in macro setup (default="Config.C")
778   //
779   //  Use macro "lego.C" to visualize the 3 lego plots in spherical coordinates
780   //Begin_Html
781   /*
782     <img src="picts/AliRunLego1.gif">
783   */
784   //End_Html
785   //Begin_Html
786   /*
787     <img src="picts/AliRunLego2.gif">
788   */
789   //End_Html
790   //Begin_Html
791   /*
792     <img src="picts/AliRunLego3.gif">
793   */
794   //End_Html
795   //
796
797 // run the generation and simulation
798
799   AliCodeTimerAuto("",0)
800
801   // initialize CDB storage and run number from external environment
802   // (either CDB manager or AliSimulation setters)
803   InitCDB();
804   InitRunNumber();
805   SetCDBLock();
806   
807   if (!gAlice) {
808     AliError("no gAlice object. Restart aliroot and try again.");
809     return kFALSE;
810   }
811   if (gAlice->Modules()->GetEntries() > 0) {
812     AliError("gAlice was already run. Restart aliroot and try again.");
813     return kFALSE;
814   }
815
816   AliInfo(Form("initializing gAlice with config file %s",
817           fConfigFileName.Data()));
818
819   // Number of events 
820     if (nev == -1) nev  = nc1 * nc2;
821     
822   // check if initialisation has been done
823   // If runloader has been initialized, set the number of events per file to nc1 * nc2
824     
825   // Set new generator
826   if (!gener) gener  = new AliLegoGenerator();
827   //
828   // Configure Generator
829
830   gener->SetRadiusRange(rmin, rmax);
831   gener->SetZMax(zmax);
832   gener->SetCoor1Range(nc1, c1min, c1max);
833   gener->SetCoor2Range(nc2, c2min, c2max);
834   
835   
836   //Create Lego object  
837   fLego = new AliLego("lego",gener);
838
839   //__________________________________________________________________________
840
841   gAlice->Announce();
842
843   gROOT->LoadMacro(setup);
844   gInterpreter->ProcessLine(gAlice->GetConfigFunction());
845
846   if(AliCDBManager::Instance()->GetRun() >= 0) { 
847     SetRunNumber(AliCDBManager::Instance()->GetRun());
848   } else {
849     AliWarning("Run number not initialized!!");
850   }
851
852   AliRunLoader::Instance()->CdGAFile();
853   
854   AliPDG::AddParticlesToPdgDataBase();  
855   
856   gMC->SetMagField(TGeoGlobalMagField::Instance()->GetField());
857
858   gAlice->GetMCApp()->Init();
859   
860   
861   //Must be here because some MCs (G4) adds detectors here and not in Config.C
862   gAlice->InitLoaders();
863   AliRunLoader::Instance()->MakeTree("E");
864   
865   //
866   // Save stuff at the beginning of the file to avoid file corruption
867   AliRunLoader::Instance()->CdGAFile();
868   gAlice->Write();
869
870   //Save current generator
871   AliGenerator *gen=gAlice->GetMCApp()->Generator();
872   gAlice->GetMCApp()->ResetGenerator(gener);
873   //Prepare MC for Lego Run
874   gMC->InitLego();
875   
876   //Run Lego Object
877   
878   
879   AliRunLoader::Instance()->SetNumberOfEventsPerFile(nev);
880   gMC->ProcessRun(nev);
881   
882   // End of this run, close files
883   FinishRun();
884   // Restore current generator
885   gAlice->GetMCApp()->ResetGenerator(gen);
886   // Delete Lego Object
887   delete fLego;
888
889   return kTRUE;
890 }
891
892 //_____________________________________________________________________________
893 Bool_t AliSimulation::RunTrigger(const char* config, const char* detectors)
894 {
895   // run the trigger
896
897   AliCodeTimerAuto("",0)
898
899   // initialize CDB storage from external environment
900   // (either CDB manager or AliSimulation setters),
901   // if not already done in RunSimulation()
902   InitCDB();
903   
904   // Set run number in CDBManager from data 
905   // From this point on the run number must be always loaded from data!
906   if (!SetRunNumberFromData()) if (fStopOnError) return kFALSE;
907   
908   // Set CDB lock: from now on it is forbidden to reset the run number
909   // or the default storage or to activate any further storage!
910   SetCDBLock();
911    
912    AliRunLoader* runLoader = LoadRun("READ");
913    if (!runLoader) return kFALSE;
914    TString trconfiguration = config;
915
916    if (trconfiguration.IsNull()) {
917      if(!fTriggerConfig.IsNull()) {
918        trconfiguration = fTriggerConfig;
919      }
920      else
921        AliWarning("No trigger descriptor is specified. Loading the one that is in the CDB.");
922    }
923
924    runLoader->MakeTree( "GG" );
925    AliCentralTrigger* aCTP = runLoader->GetTrigger();
926    // Load Configuration
927    if (!aCTP->LoadConfiguration( trconfiguration ))
928      return kFALSE;
929
930    // digits -> trigger
931    if( !aCTP->RunTrigger( runLoader , detectors ) ) {
932       if (fStopOnError) {
933         //  delete aCTP;
934         return kFALSE;
935       }
936    }
937
938    delete runLoader;
939
940    return kTRUE;
941 }
942
943 //_____________________________________________________________________________
944 Bool_t AliSimulation::WriteTriggerRawData()
945 {
946   // Writes the CTP (trigger) DDL raw data
947   // Details of the format are given in the
948   // trigger TDR - pages 134 and 135.
949   AliCTPRawData writer;
950   writer.RawData();
951
952   return kTRUE;
953 }
954
955 //_____________________________________________________________________________
956 Bool_t AliSimulation::RunSimulation(Int_t nEvents)
957 {
958 // run the generation and simulation
959
960   AliCodeTimerAuto("",0)
961
962   // initialize CDB storage and run number from external environment
963   // (either CDB manager or AliSimulation setters)
964   AliSysInfo::AddStamp("RunSimulation_Begin");
965   InitCDB();
966   AliSysInfo::AddStamp("RunSimulation_InitCDB");
967   InitRunNumber();
968   SetCDBLock();
969   AliSysInfo::AddStamp("RunSimulation_SetCDBLock");
970   
971   if (!gAlice) {
972     AliError("no gAlice object. Restart aliroot and try again.");
973     return kFALSE;
974   }
975   if (gAlice->Modules()->GetEntries() > 0) {
976     AliError("gAlice was already run. Restart aliroot and try again.");
977     return kFALSE;
978   }
979
980   AliInfo(Form("initializing gAlice with config file %s",
981           fConfigFileName.Data()));
982
983   //
984   // Initialize ALICE Simulation run
985   //
986
987   gAlice->Announce();
988
989   gROOT->LoadMacro(fConfigFileName.Data());
990   gInterpreter->ProcessLine(gAlice->GetConfigFunction());
991   AliSysInfo::AddStamp("RunSimulation_Config");
992
993   if(AliCDBManager::Instance()->GetRun() >= 0) { 
994     AliRunLoader::Instance()->SetRunNumber(AliCDBManager::Instance()->GetRun());
995     AliRunLoader::Instance()->SetNumberOfEventsPerRun(fNEvents);
996   } else {
997         AliWarning("Run number not initialized!!");
998   }
999   
1000    AliRunLoader::Instance()->CdGAFile();
1001     
1002    AliPDG::AddParticlesToPdgDataBase();  
1003
1004    gMC->SetMagField(TGeoGlobalMagField::Instance()->GetField());
1005    AliSysInfo::AddStamp("RunSimulation_GetField");
1006    
1007    gAlice->GetMCApp()->Init();
1008    AliSysInfo::AddStamp("RunSimulation_InitMCApp");
1009
1010    //Must be here because some MCs (G4) adds detectors here and not in Config.C
1011    gAlice->InitLoaders();
1012    AliRunLoader::Instance()->MakeTree("E");
1013    AliRunLoader::Instance()->LoadKinematics("RECREATE");
1014    AliRunLoader::Instance()->LoadTrackRefs("RECREATE");
1015    AliRunLoader::Instance()->LoadHits("all","RECREATE");
1016    //
1017    // Save stuff at the beginning of the file to avoid file corruption
1018    AliRunLoader::Instance()->CdGAFile();
1019    gAlice->Write();
1020    gAlice->SetEventNrInRun(-1); //important - we start Begin event from increasing current number in run
1021    AliSysInfo::AddStamp("RunSimulation_InitLoaders");
1022   //___________________________________________________________________________________________
1023   
1024   AliSysInfo::AddStamp("RunSimulation_TriggerDescriptor");
1025
1026   // Set run number in CDBManager
1027   AliInfo(Form("Run number: %d",AliCDBManager::Instance()->GetRun()));
1028
1029   AliRunLoader* runLoader = AliRunLoader::Instance();
1030   if (!runLoader) {
1031              AliError(Form("gAlice has no run loader object. "
1032                              "Check your config file: %s", fConfigFileName.Data()));
1033              return kFALSE;
1034   }
1035   SetGAliceFile(runLoader->GetFileName());
1036       
1037   // Misalign geometry
1038 #if ROOT_VERSION_CODE < 331527
1039   AliGeomManager::SetGeometry(gGeoManager);
1040   
1041   // Check that the consistency of symbolic names for the activated subdetectors
1042   // in the geometry loaded by AliGeomManager
1043   TString detsToBeChecked = "";
1044   TObjArray* detArray = runLoader->GetAliRun()->Detectors();
1045   for (Int_t iDet = 0; iDet < detArray->GetEntriesFast(); iDet++) {
1046     AliModule* det = (AliModule*) detArray->At(iDet);
1047     if (!det || !det->IsActive()) continue;
1048     detsToBeChecked += det->GetName();
1049     detsToBeChecked += " ";
1050   } // end loop over detectors
1051   if(!AliGeomManager::CheckSymNamesLUT(detsToBeChecked.Data()))
1052     AliFatalClass("Current loaded geometry differs in the definition of symbolic names!");
1053   MisalignGeometry(runLoader);
1054   AliSysInfo::AddStamp("RunSimulation_MisalignGeometry");
1055 #endif
1056
1057 //   AliRunLoader* runLoader = AliRunLoader::Instance();
1058 //   if (!runLoader) {
1059 //     AliError(Form("gAlice has no run loader object. "
1060 //                   "Check your config file: %s", fConfigFileName.Data()));
1061 //     return kFALSE;
1062 //   }
1063 //   SetGAliceFile(runLoader->GetFileName());
1064
1065   if (!gAlice->GetMCApp()->Generator()) {
1066     AliError(Form("gAlice has no generator object. "
1067                   "Check your config file: %s", fConfigFileName.Data()));
1068     return kFALSE;
1069   }
1070
1071   // Write GRP entry corresponding to the setting found in Cofig.C
1072   if (fWriteGRPEntry)
1073     WriteGRPEntry();
1074   AliSysInfo::AddStamp("RunSimulation_WriteGRP");
1075
1076   if (nEvents <= 0) nEvents = fNEvents;
1077
1078   // get vertex from background file in case of merging
1079   if (fUseBkgrdVertex &&
1080       fBkgrdFileNames && (fBkgrdFileNames->GetEntriesFast() > 0)) {
1081     Int_t signalPerBkgrd = GetNSignalPerBkgrd(nEvents);
1082     const char* fileName = ((TObjString*)
1083                             (fBkgrdFileNames->At(0)))->GetName();
1084     AliInfo(Form("The vertex will be taken from the background "
1085                  "file %s with nSignalPerBackground = %d", 
1086                  fileName, signalPerBkgrd));
1087     AliVertexGenFile* vtxGen = new AliVertexGenFile(fileName, signalPerBkgrd);
1088     gAlice->GetMCApp()->Generator()->SetVertexGenerator(vtxGen);
1089   }
1090
1091   if (!fRunSimulation) {
1092     gAlice->GetMCApp()->Generator()->SetTrackingFlag(0);
1093   }
1094
1095   // set the number of events per file for given detectors and data types
1096   for (Int_t i = 0; i < fEventsPerFile.GetEntriesFast(); i++) {
1097     if (!fEventsPerFile[i]) continue;
1098     const char* detName = fEventsPerFile[i]->GetName();
1099     const char* typeName = fEventsPerFile[i]->GetTitle();
1100     TString loaderName(detName);
1101     loaderName += "Loader";
1102     AliLoader* loader = runLoader->GetLoader(loaderName);
1103     if (!loader) {
1104       AliError(Form("RunSimulation", "no loader for %s found\n"
1105                     "Number of events per file not set for %s %s", 
1106                     detName, typeName, detName));
1107       continue;
1108     }
1109     AliDataLoader* dataLoader = 
1110       loader->GetDataLoader(typeName);
1111     if (!dataLoader) {
1112       AliError(Form("no data loader for %s found\n"
1113                     "Number of events per file not set for %s %s", 
1114                     typeName, detName, typeName));
1115       continue;
1116     }
1117     dataLoader->SetNumberOfEventsPerFile(fEventsPerFile[i]->GetUniqueID());
1118     AliDebug(1, Form("number of events per file set to %d for %s %s",
1119                      fEventsPerFile[i]->GetUniqueID(), detName, typeName));
1120   }
1121
1122   AliInfo("running gAlice");
1123   AliSysInfo::AddStamp("Start_ProcessRun");
1124
1125   // Create the Root Tree with one branch per detector
1126   //Hits moved to begin event -> now we are crating separate tree for each event
1127
1128   gMC->ProcessRun(nEvents);
1129
1130   // End of this run, close files
1131   if(nEvents>0) FinishRun();
1132
1133   AliSysInfo::AddStamp("Stop_ProcessRun");
1134   delete runLoader;
1135
1136   return kTRUE;
1137 }
1138
1139 //_____________________________________________________________________________
1140 Bool_t AliSimulation::RunSDigitization(const char* detectors)
1141 {
1142 // run the digitization and produce summable digits
1143   static Int_t eventNr=0;
1144   AliCodeTimerAuto("",0) ;
1145
1146   // initialize CDB storage, run number, set CDB lock
1147   InitCDB();
1148   if (!SetRunNumberFromData()) if (fStopOnError) return kFALSE;
1149   SetCDBLock();
1150   
1151   AliRunLoader* runLoader = LoadRun();
1152   if (!runLoader) return kFALSE;
1153
1154   TString detStr = detectors;
1155   TObjArray* detArray = runLoader->GetAliRun()->Detectors();
1156   for (Int_t iDet = 0; iDet < detArray->GetEntriesFast(); iDet++) {
1157     AliModule* det = (AliModule*) detArray->At(iDet);
1158     if (!det || !det->IsActive()) continue;
1159     if (IsSelected(det->GetName(), detStr)) {
1160       AliInfo(Form("creating summable digits for %s", det->GetName()));
1161       AliCodeTimerStart(Form("creating summable digits for %s", det->GetName()));
1162       det->Hits2SDigits();
1163       AliCodeTimerStop(Form("creating summable digits for %s", det->GetName()));
1164       AliSysInfo::AddStamp(Form("Digit_%s_%d",det->GetName(),eventNr), 0,1, eventNr);
1165     }
1166   }
1167
1168   if ((detStr.CompareTo("ALL") != 0) && !detStr.IsNull()) {
1169     AliError(Form("the following detectors were not found: %s",
1170                   detStr.Data()));
1171     if (fStopOnError) return kFALSE;
1172   }
1173   eventNr++;
1174   delete runLoader;
1175
1176   return kTRUE;
1177 }
1178
1179
1180 //_____________________________________________________________________________
1181 Bool_t AliSimulation::RunDigitization(const char* detectors, 
1182                                       const char* excludeDetectors)
1183 {
1184 // run the digitization and produce digits from sdigits
1185
1186   AliCodeTimerAuto("",0)
1187
1188   // initialize CDB storage, run number, set CDB lock
1189   InitCDB();
1190   if (!SetRunNumberFromData()) if (fStopOnError) return kFALSE;
1191   SetCDBLock();
1192   
1193   delete AliRunLoader::Instance();
1194   delete gAlice;
1195   gAlice = NULL;
1196
1197   Int_t nStreams = 1;
1198   if (fBkgrdFileNames) nStreams = fBkgrdFileNames->GetEntriesFast() + 1;
1199   Int_t signalPerBkgrd = GetNSignalPerBkgrd();
1200   AliRunDigitizer* manager = new AliRunDigitizer(nStreams, signalPerBkgrd);
1201   // manager->SetEmbeddingFlag(fEmbeddingFlag);
1202   manager->SetInputStream(0, fGAliceFileName.Data());
1203   for (Int_t iStream = 1; iStream < nStreams; iStream++) {
1204     const char* fileName = ((TObjString*)
1205                             (fBkgrdFileNames->At(iStream-1)))->GetName();
1206     manager->SetInputStream(iStream, fileName);
1207   }
1208
1209   TString detStr = detectors;
1210   TString detExcl = excludeDetectors;
1211   manager->GetInputStream(0)->ImportgAlice();
1212   AliRunLoader* runLoader = 
1213     AliRunLoader::GetRunLoader(manager->GetInputStream(0)->GetFolderName());
1214   TObjArray* detArray = runLoader->GetAliRun()->Detectors();
1215   for (Int_t iDet = 0; iDet < detArray->GetEntriesFast(); iDet++) {
1216     AliModule* det = (AliModule*) detArray->At(iDet);
1217     if (!det || !det->IsActive()) continue;
1218     if (IsSelected(det->GetName(), detStr) && 
1219         !IsSelected(det->GetName(), detExcl)) {
1220       AliDigitizer* digitizer = det->CreateDigitizer(manager);
1221       
1222       if (!digitizer) {
1223         AliError(Form("no digitizer for %s", det->GetName()));
1224         if (fStopOnError) return kFALSE;
1225       } else {
1226         digitizer->SetRegionOfInterest(fRegionOfInterest);
1227       }
1228     }
1229   }
1230
1231   if ((detStr.CompareTo("ALL") != 0) && !detStr.IsNull()) {
1232     AliError(Form("the following detectors were not found: %s", 
1233                   detStr.Data()));
1234     if (fStopOnError) return kFALSE;
1235   }
1236
1237   if (!manager->GetListOfTasks()->IsEmpty()) {
1238     AliInfo("executing digitization");
1239     manager->Exec("");
1240   }
1241
1242   delete manager;
1243
1244   return kTRUE;
1245 }
1246
1247 //_____________________________________________________________________________
1248 Bool_t AliSimulation::RunHitsDigitization(const char* detectors)
1249 {
1250 // run the digitization and produce digits from hits
1251
1252   AliCodeTimerAuto("",0)
1253
1254   // initialize CDB storage, run number, set CDB lock
1255   InitCDB();
1256   if (!SetRunNumberFromData()) if (fStopOnError) return kFALSE;
1257   SetCDBLock();
1258   
1259   AliRunLoader* runLoader = LoadRun("READ");
1260   if (!runLoader) return kFALSE;
1261
1262   TString detStr = detectors;
1263   TObjArray* detArray = runLoader->GetAliRun()->Detectors();
1264   for (Int_t iDet = 0; iDet < detArray->GetEntriesFast(); iDet++) {
1265     AliModule* det = (AliModule*) detArray->At(iDet);
1266     if (!det || !det->IsActive()) continue;
1267     if (IsSelected(det->GetName(), detStr)) {
1268       AliInfo(Form("creating digits from hits for %s", det->GetName()));
1269       det->Hits2Digits();
1270     }
1271   }
1272
1273   if ((detStr.CompareTo("ALL") != 0) && !detStr.IsNull()) {
1274     AliError(Form("the following detectors were not found: %s", 
1275                   detStr.Data()));
1276     if (fStopOnError) return kFALSE;
1277   }
1278
1279   return kTRUE;
1280 }
1281
1282 //_____________________________________________________________________________
1283 Bool_t AliSimulation::WriteRawData(const char* detectors, 
1284                                    const char* fileName,
1285                                    Bool_t deleteIntermediateFiles,
1286                                    Bool_t selrawdata)
1287 {
1288 // convert the digits to raw data
1289 // First DDL raw data files for the given detectors are created.
1290 // If a file name is given, the DDL files are then converted to a DATE file.
1291 // If deleteIntermediateFiles is true, the DDL raw files are deleted 
1292 // afterwards.
1293 // If the file name has the extension ".root", the DATE file is converted
1294 // to a root file.
1295 // If deleteIntermediateFiles is true, the DATE file is deleted afterwards.
1296 // 'selrawdata' flag can be used to enable writing of detectors raw data
1297 // accoring to the trigger cluster.
1298
1299   AliCodeTimerAuto("",0)
1300   AliSysInfo::AddStamp("WriteRawData_Start");
1301   
1302   TString detStr = detectors;
1303   if (!WriteRawFiles(detStr.Data())) {
1304     if (fStopOnError) return kFALSE;
1305   }
1306   AliSysInfo::AddStamp("WriteRawFiles");
1307
1308   // run HLT simulation on simulated DDL raw files
1309   // and produce HLT ddl raw files to be included in date/root file
1310   // bugfix 2009-06-26: the decision whether to write HLT raw data
1311   // is taken in RunHLT. Here HLT always needs to be run in order to
1312   // create HLT digits, unless its switched off. This is due to the
1313   // special placement of the HLT between the generation of DDL files
1314   // and conversion to DATE/Root file.
1315   detStr.ReplaceAll("HLT", "");
1316   if (!fRunHLT.IsNull()) {
1317     if (!RunHLT()) {
1318       if (fStopOnError) return kFALSE;
1319     }
1320   }
1321   AliSysInfo::AddStamp("WriteRawData_RunHLT");
1322
1323   TString dateFileName(fileName);
1324   if (!dateFileName.IsNull()) {
1325     Bool_t rootOutput = dateFileName.EndsWith(".root");
1326     if (rootOutput) dateFileName += ".date";
1327     TString selDateFileName;
1328     if (selrawdata) {
1329       selDateFileName = "selected.";
1330       selDateFileName+= dateFileName;
1331     }
1332     if (!ConvertRawFilesToDate(dateFileName,selDateFileName)) {
1333       if (fStopOnError) return kFALSE;
1334     }
1335     AliSysInfo::AddStamp("ConvertRawFilesToDate");
1336     if (deleteIntermediateFiles) {
1337       AliRunLoader* runLoader = LoadRun("READ");
1338       if (runLoader) for (Int_t iEvent = 0; 
1339                           iEvent < runLoader->GetNumberOfEvents(); iEvent++) {
1340         char command[256];
1341         sprintf(command, "rm -r raw%d", iEvent);
1342         gSystem->Exec(command);
1343       }
1344     }
1345
1346     if (rootOutput) {
1347       if (!ConvertDateToRoot(dateFileName, fileName)) {
1348         if (fStopOnError) return kFALSE;
1349       }
1350       AliSysInfo::AddStamp("ConvertDateToRoot");
1351       if (deleteIntermediateFiles) {
1352         gSystem->Unlink(dateFileName);
1353       }
1354       if (selrawdata) {
1355         TString selFileName = "selected.";
1356         selFileName        += fileName;
1357         if (!ConvertDateToRoot(selDateFileName, selFileName)) {
1358           if (fStopOnError) return kFALSE;
1359         }
1360         if (deleteIntermediateFiles) {
1361           gSystem->Unlink(selDateFileName);
1362         }
1363       }
1364     }
1365   }
1366
1367   return kTRUE;
1368 }
1369
1370 //_____________________________________________________________________________
1371 Bool_t AliSimulation::WriteRawFiles(const char* detectors)
1372 {
1373 // convert the digits to raw data DDL files
1374
1375   AliCodeTimerAuto("",0)
1376   
1377   AliRunLoader* runLoader = LoadRun("READ");
1378   if (!runLoader) return kFALSE;
1379
1380   // write raw data to DDL files
1381   for (Int_t iEvent = 0; iEvent < runLoader->GetNumberOfEvents(); iEvent++) {
1382     AliInfo(Form("processing event %d", iEvent));
1383     runLoader->GetEvent(iEvent);
1384     TString baseDir = gSystem->WorkingDirectory();
1385     char dirName[256];
1386     sprintf(dirName, "raw%d", iEvent);
1387     gSystem->MakeDirectory(dirName);
1388     if (!gSystem->ChangeDirectory(dirName)) {
1389       AliError(Form("couldn't change to directory %s", dirName));
1390       if (fStopOnError) return kFALSE; else continue;
1391     }
1392
1393     ofstream runNbFile(Form("run%u",runLoader->GetHeader()->GetRun()));
1394     runNbFile.close();
1395
1396     TString detStr = detectors;
1397     if (IsSelected("HLT", detStr)) {
1398       // Do nothing. "HLT" will be removed from detStr and HLT raw
1399       // data files are generated in RunHLT.
1400     }
1401
1402     TObjArray* detArray = runLoader->GetAliRun()->Detectors();
1403     for (Int_t iDet = 0; iDet < detArray->GetEntriesFast(); iDet++) {
1404       AliModule* det = (AliModule*) detArray->At(iDet);
1405       if (!det || !det->IsActive()) continue;
1406       if (IsSelected(det->GetName(), detStr)) {
1407         AliInfo(Form("creating raw data from digits for %s", det->GetName()));
1408         det->Digits2Raw();
1409       }
1410     }
1411
1412     if (!WriteTriggerRawData())
1413       if (fStopOnError) return kFALSE;
1414
1415     gSystem->ChangeDirectory(baseDir);
1416     if ((detStr.CompareTo("ALL") != 0) && !detStr.IsNull()) {
1417       AliError(Form("the following detectors were not found: %s", 
1418                     detStr.Data()));
1419       if (fStopOnError) return kFALSE;
1420     }
1421   }
1422
1423   delete runLoader;
1424   
1425   return kTRUE;
1426 }
1427
1428 //_____________________________________________________________________________
1429 Bool_t AliSimulation::ConvertRawFilesToDate(const char* dateFileName,
1430                                             const char* selDateFileName)
1431 {
1432 // convert raw data DDL files to a DATE file with the program "dateStream"
1433 // The second argument is not empty when the user decides to write
1434 // the detectors raw data according to the trigger cluster.
1435
1436   AliCodeTimerAuto("",0)
1437   
1438   char* path = gSystem->Which(gSystem->Getenv("PATH"), "dateStream");
1439   if (!path) {
1440     AliError("the program dateStream was not found");
1441     if (fStopOnError) return kFALSE;
1442   } else {
1443     delete[] path;
1444   }
1445
1446   AliRunLoader* runLoader = LoadRun("READ");
1447   if (!runLoader) return kFALSE;
1448
1449   AliInfo(Form("converting raw data DDL files to DATE file %s", dateFileName));
1450   Bool_t selrawdata = kFALSE;
1451   if (strcmp(selDateFileName,"") != 0) selrawdata = kTRUE;
1452
1453   char command[256];
1454   // Note the option -s. It is used in order to avoid
1455   // the generation of SOR/EOR events.
1456   sprintf(command, "dateStream -c -s -D -o %s -# %d -C -run %d", 
1457           dateFileName, runLoader->GetNumberOfEvents(),runLoader->GetHeader()->GetRun());
1458   FILE* pipe = gSystem->OpenPipe(command, "w");
1459
1460   if (!pipe) {
1461     AliError(Form("Cannot execute command: %s",command));
1462     return kFALSE;
1463   }
1464
1465   Int_t selEvents = 0;
1466   for (Int_t iEvent = 0; iEvent < runLoader->GetNumberOfEvents(); iEvent++) {
1467
1468     UInt_t detectorPattern = 0;
1469     runLoader->GetEvent(iEvent);
1470     if (!runLoader->LoadTrigger()) {
1471       AliCentralTrigger *aCTP = runLoader->GetTrigger();
1472       detectorPattern = aCTP->GetClusterMask();
1473       // Check if the event was triggered by CTP
1474       if (selrawdata) {
1475         if (aCTP->GetClassMask()) selEvents++;
1476       }
1477     }
1478     else {
1479       AliWarning("No trigger can be loaded! Some fields in the event header will be empty !");
1480       if (selrawdata) {
1481         AliWarning("No trigger can be loaded! Writing of selected raw data is abandoned !");
1482         selrawdata = kFALSE;
1483       }
1484     }
1485
1486     fprintf(pipe, "GDC DetectorPattern %u\n", detectorPattern);
1487     Float_t ldc = 0;
1488     Int_t prevLDC = -1;
1489
1490     // loop over detectors and DDLs
1491     for (Int_t iDet = 0; iDet < AliDAQ::kNDetectors; iDet++) {
1492       for (Int_t iDDL = 0; iDDL < AliDAQ::NumberOfDdls(iDet); iDDL++) {
1493
1494         Int_t ddlID = AliDAQ::DdlID(iDet,iDDL);
1495         Int_t ldcID = Int_t(ldc + 0.0001);
1496         ldc += AliDAQ::NumberOfLdcs(iDet) / AliDAQ::NumberOfDdls(iDet);
1497
1498         char rawFileName[256];
1499         sprintf(rawFileName, "raw%d/%s", 
1500                 iEvent, AliDAQ::DdlFileName(iDet,iDDL));
1501
1502         // check existence and size of raw data file
1503         FILE* file = fopen(rawFileName, "rb");
1504         if (!file) continue;
1505         fseek(file, 0, SEEK_END);
1506         unsigned long size = ftell(file);
1507         fclose(file);
1508         if (!size) continue;
1509
1510         if (ldcID != prevLDC) {
1511           fprintf(pipe, " LDC Id %d\n", ldcID);
1512           prevLDC = ldcID;
1513         }
1514         fprintf(pipe, "  Equipment Id %d Payload %s\n", ddlID, rawFileName);
1515       }
1516     }
1517   }
1518
1519   Int_t result = gSystem->ClosePipe(pipe);
1520
1521   if (!(selrawdata && selEvents > 0)) {
1522     delete runLoader;
1523     return (result == 0);
1524   }
1525
1526   AliInfo(Form("converting selected by trigger cluster raw data DDL files to DATE file %s", selDateFileName));
1527   
1528   sprintf(command, "dateStream -c -s -D -o %s -# %d -C -run %d", 
1529           selDateFileName,selEvents,runLoader->GetHeader()->GetRun());
1530   FILE* pipe2 = gSystem->OpenPipe(command, "w");
1531
1532   for (Int_t iEvent = 0; iEvent < runLoader->GetNumberOfEvents(); iEvent++) {
1533
1534     // Get the trigger decision and cluster
1535     UInt_t detectorPattern = 0;
1536     TString detClust;
1537     runLoader->GetEvent(iEvent);
1538     if (!runLoader->LoadTrigger()) {
1539       AliCentralTrigger *aCTP = runLoader->GetTrigger();
1540       if (aCTP->GetClassMask() == 0) continue;
1541       detectorPattern = aCTP->GetClusterMask();
1542       detClust = AliDAQ::ListOfTriggeredDetectors(detectorPattern);
1543       AliInfo(Form("List of detectors to be read out: %s",detClust.Data()));
1544     }
1545
1546     fprintf(pipe2, "GDC DetectorPattern %u\n", detectorPattern);
1547     Float_t ldc = 0;
1548     Int_t prevLDC = -1;
1549
1550     // loop over detectors and DDLs
1551     for (Int_t iDet = 0; iDet < AliDAQ::kNDetectors; iDet++) {
1552       // Write only raw data from detectors that
1553       // are contained in the trigger cluster(s)
1554       if (!IsSelected(AliDAQ::DetectorName(iDet),detClust)) continue;
1555
1556       for (Int_t iDDL = 0; iDDL < AliDAQ::NumberOfDdls(iDet); iDDL++) {
1557
1558         Int_t ddlID = AliDAQ::DdlID(iDet,iDDL);
1559         Int_t ldcID = Int_t(ldc + 0.0001);
1560         ldc += AliDAQ::NumberOfLdcs(iDet) / AliDAQ::NumberOfDdls(iDet);
1561
1562         char rawFileName[256];
1563         sprintf(rawFileName, "raw%d/%s", 
1564                 iEvent, AliDAQ::DdlFileName(iDet,iDDL));
1565
1566         // check existence and size of raw data file
1567         FILE* file = fopen(rawFileName, "rb");
1568         if (!file) continue;
1569         fseek(file, 0, SEEK_END);
1570         unsigned long size = ftell(file);
1571         fclose(file);
1572         if (!size) continue;
1573
1574         if (ldcID != prevLDC) {
1575           fprintf(pipe2, " LDC Id %d\n", ldcID);
1576           prevLDC = ldcID;
1577         }
1578         fprintf(pipe2, "  Equipment Id %d Payload %s\n", ddlID, rawFileName);
1579       }
1580     }
1581   }
1582
1583   Int_t result2 = gSystem->ClosePipe(pipe2);
1584
1585   delete runLoader;
1586   return ((result == 0) && (result2 == 0));
1587 }
1588
1589 //_____________________________________________________________________________
1590 Bool_t AliSimulation::ConvertDateToRoot(const char* dateFileName,
1591                                         const char* rootFileName)
1592 {
1593 // convert a DATE file to a root file with the program "alimdc"
1594
1595   // ALIMDC setup
1596   const Int_t kDBSize = 2000000000;
1597   const Int_t kTagDBSize = 1000000000;
1598   const Bool_t kFilter = kFALSE;
1599   const Int_t kCompression = 1;
1600
1601   char* path = gSystem->Which(gSystem->Getenv("PATH"), "alimdc");
1602   if (!path) {
1603     AliError("the program alimdc was not found");
1604     if (fStopOnError) return kFALSE;
1605   } else {
1606     delete[] path;
1607   }
1608
1609   AliInfo(Form("converting DATE file %s to root file %s", 
1610                dateFileName, rootFileName));
1611
1612   const char* rawDBFS[2] = { "/tmp/mdc1", "/tmp/mdc2" };
1613   const char* tagDBFS    = "/tmp/mdc1/tags";
1614
1615   // User defined file system locations
1616   if (gSystem->Getenv("ALIMDC_RAWDB1")) 
1617     rawDBFS[0] = gSystem->Getenv("ALIMDC_RAWDB1");
1618   if (gSystem->Getenv("ALIMDC_RAWDB2")) 
1619     rawDBFS[1] = gSystem->Getenv("ALIMDC_RAWDB2");
1620   if (gSystem->Getenv("ALIMDC_TAGDB")) 
1621     tagDBFS = gSystem->Getenv("ALIMDC_TAGDB");
1622
1623   gSystem->Exec(Form("rm -rf %s",rawDBFS[0]));
1624   gSystem->Exec(Form("rm -rf %s",rawDBFS[1]));
1625   gSystem->Exec(Form("rm -rf %s",tagDBFS));
1626
1627   gSystem->Exec(Form("mkdir %s",rawDBFS[0]));
1628   gSystem->Exec(Form("mkdir %s",rawDBFS[1]));
1629   gSystem->Exec(Form("mkdir %s",tagDBFS));
1630
1631   Int_t result = gSystem->Exec(Form("alimdc %d %d %d %d %s", 
1632                                     kDBSize, kTagDBSize, kFilter, kCompression, dateFileName));
1633   gSystem->Exec(Form("mv %s/*.root %s", rawDBFS[0], rootFileName));
1634
1635   gSystem->Exec(Form("rm -rf %s",rawDBFS[0]));
1636   gSystem->Exec(Form("rm -rf %s",rawDBFS[1]));
1637   gSystem->Exec(Form("rm -rf %s",tagDBFS));
1638
1639   return (result == 0);
1640 }
1641
1642
1643 //_____________________________________________________________________________
1644 AliRunLoader* AliSimulation::LoadRun(const char* mode) const
1645 {
1646 // delete existing run loaders, open a new one and load gAlice
1647
1648   delete AliRunLoader::Instance();
1649   AliRunLoader* runLoader = 
1650     AliRunLoader::Open(fGAliceFileName.Data(), 
1651                        AliConfig::GetDefaultEventFolderName(), mode);
1652   if (!runLoader) {
1653     AliError(Form("no run loader found in file %s", fGAliceFileName.Data()));
1654     return NULL;
1655   }
1656   runLoader->LoadgAlice();
1657   runLoader->LoadHeader();
1658   gAlice = runLoader->GetAliRun();
1659   if (!gAlice) {
1660     AliError(Form("no gAlice object found in file %s", 
1661                   fGAliceFileName.Data()));
1662     return NULL;
1663   }
1664   return runLoader;
1665 }
1666
1667 //_____________________________________________________________________________
1668 Int_t AliSimulation::GetNSignalPerBkgrd(Int_t nEvents) const
1669 {
1670 // get or calculate the number of signal events per background event
1671
1672   if (!fBkgrdFileNames) return 1;
1673   Int_t nBkgrdFiles = fBkgrdFileNames->GetEntriesFast();
1674   if (nBkgrdFiles == 0) return 1;
1675
1676   // get the number of signal events
1677   if (nEvents <= 0) {
1678     AliRunLoader* runLoader = 
1679         AliRunLoader::Open(fGAliceFileName.Data(), "SIGNAL");
1680     if (!runLoader) return 1;
1681     
1682     nEvents = runLoader->GetNumberOfEvents();
1683     delete runLoader;
1684   }
1685
1686   Int_t result = 0;
1687   for (Int_t iBkgrdFile = 0; iBkgrdFile < nBkgrdFiles; iBkgrdFile++) {
1688     // get the number of background events
1689     const char* fileName = ((TObjString*)
1690                             (fBkgrdFileNames->At(iBkgrdFile)))->GetName();
1691     AliRunLoader* runLoader =
1692       AliRunLoader::Open(fileName, "BKGRD");
1693     if (!runLoader) continue;
1694     Int_t nBkgrdEvents = runLoader->GetNumberOfEvents();
1695     delete runLoader;
1696   
1697     // get or calculate the number of signal per background events
1698     Int_t nSignalPerBkgrd = fBkgrdFileNames->At(iBkgrdFile)->GetUniqueID();
1699     if (nSignalPerBkgrd <= 0) {
1700       nSignalPerBkgrd = (nEvents-1) / nBkgrdEvents + 1;
1701     } else if (result && (result != nSignalPerBkgrd)) {
1702       AliInfo(Form("the number of signal events per background event "
1703                    "will be changed from %d to %d for stream %d", 
1704                    nSignalPerBkgrd, result, iBkgrdFile+1));
1705       nSignalPerBkgrd = result;
1706     }
1707
1708     if (!result) result = nSignalPerBkgrd;
1709     if (nSignalPerBkgrd * nBkgrdEvents < nEvents) {
1710       AliWarning(Form("not enough background events (%d) for %d signal events "
1711                       "using %d signal per background events for stream %d",
1712                       nBkgrdEvents, nEvents, nSignalPerBkgrd, iBkgrdFile+1));
1713     }
1714   }
1715
1716   return result;
1717 }
1718
1719 //_____________________________________________________________________________
1720 Bool_t AliSimulation::IsSelected(TString detName, TString& detectors) const
1721 {
1722 // check whether detName is contained in detectors
1723 // if yes, it is removed from detectors
1724
1725   // check if all detectors are selected
1726   if ((detectors.CompareTo("ALL") == 0) ||
1727       detectors.BeginsWith("ALL ") ||
1728       detectors.EndsWith(" ALL") ||
1729       detectors.Contains(" ALL ")) {
1730     detectors = "ALL";
1731     return kTRUE;
1732   }
1733
1734   // search for the given detector
1735   Bool_t result = kFALSE;
1736   if ((detectors.CompareTo(detName) == 0) ||
1737       detectors.BeginsWith(detName+" ") ||
1738       detectors.EndsWith(" "+detName) ||
1739       detectors.Contains(" "+detName+" ")) {
1740     detectors.ReplaceAll(detName, "");
1741     result = kTRUE;
1742   }
1743
1744   // clean up the detectors string
1745   while (detectors.Contains("  ")) detectors.ReplaceAll("  ", " ");
1746   while (detectors.BeginsWith(" ")) detectors.Remove(0, 1);
1747   while (detectors.EndsWith(" ")) detectors.Remove(detectors.Length()-1, 1);
1748
1749   return result;
1750 }
1751
1752 //_____________________________________________________________________________
1753 Bool_t AliSimulation::ConvertRaw2SDigits(const char* rawDirectory, const char* esdFileName) 
1754 {
1755 //
1756 // Steering routine  to convert raw data in directory rawDirectory/ to fake SDigits. 
1757 // These can be used for embedding of MC tracks into RAW data using the standard 
1758 // merging procedure.
1759 //
1760 // If an ESD file is given the reconstructed vertex is taken from it and stored in the event header.
1761 //
1762   if (!gAlice) {
1763     AliError("no gAlice object. Restart aliroot and try again.");
1764     return kFALSE;
1765   }
1766   if (gAlice->Modules()->GetEntries() > 0) {
1767     AliError("gAlice was already run. Restart aliroot and try again.");
1768     return kFALSE;
1769   }
1770   
1771   AliInfo(Form("initializing gAlice with config file %s",fConfigFileName.Data()));
1772   
1773   gAlice->Announce();
1774   
1775   gROOT->LoadMacro(fConfigFileName.Data());
1776   gInterpreter->ProcessLine(gAlice->GetConfigFunction());
1777   
1778   if(AliCDBManager::Instance()->GetRun() >= 0) { 
1779         SetRunNumber(AliCDBManager::Instance()->GetRun());
1780   } else {
1781         AliWarning("Run number not initialized!!");
1782   }
1783   
1784    AliRunLoader::Instance()->CdGAFile();
1785     
1786    AliPDG::AddParticlesToPdgDataBase();  
1787
1788    gMC->SetMagField(TGeoGlobalMagField::Instance()->GetField());
1789    
1790    gAlice->GetMCApp()->Init();
1791
1792    //Must be here because some MCs (G4) adds detectors here and not in Config.C
1793    gAlice->InitLoaders();
1794    AliRunLoader::Instance()->MakeTree("E");
1795    AliRunLoader::Instance()->LoadKinematics("RECREATE");
1796    AliRunLoader::Instance()->LoadTrackRefs("RECREATE");
1797    AliRunLoader::Instance()->LoadHits("all","RECREATE");
1798    //
1799    // Save stuff at the beginning of the file to avoid file corruption
1800    AliRunLoader::Instance()->CdGAFile();
1801    gAlice->Write();
1802 //
1803 //  Initialize CDB     
1804     InitCDB();
1805     //AliCDBManager* man = AliCDBManager::Instance();
1806     //man->SetRun(0); // Should this come from rawdata header ?
1807     
1808     Int_t iDet;
1809     //
1810     // Get the runloader
1811     AliRunLoader* runLoader = AliRunLoader::Instance();
1812     //
1813     // Open esd file if available
1814     TFile* esdFile = TFile::Open(esdFileName);
1815     TTree* treeESD = 0;
1816     AliESDEvent* esd = new AliESDEvent();
1817     esdFile->GetObject("esdTree", treeESD);
1818     if (treeESD) esd->ReadFromTree(treeESD);
1819
1820     //
1821     // Create the RawReader
1822     TString fileName(rawDirectory);
1823     AliRawReader* rawReader = 0x0;
1824     if (fileName.EndsWith("/")) {
1825       rawReader = new AliRawReaderFile(fileName);
1826     } else if (fileName.EndsWith(".root")) {
1827       rawReader = new AliRawReaderRoot(fileName);
1828     } else if (!fileName.IsNull()) {
1829       rawReader = new AliRawReaderDate(fileName);
1830     }
1831 //     if (!fEquipIdMap.IsNull() && fRawReader)
1832 //       fRawReader->LoadEquipmentIdsMap(fEquipIdMap);
1833     //
1834     // Get list of detectors
1835     TObjArray* detArray = runLoader->GetAliRun()->Detectors();
1836     //
1837     // Get Header
1838     AliHeader* header = runLoader->GetHeader();
1839     //
1840     TString detStr = fMakeSDigits;
1841     // Event loop
1842     Int_t nev = 0;
1843     while(kTRUE) {
1844         if (!(rawReader->NextEvent())) break;
1845         //
1846         // Detector loop
1847         for (iDet = 0; iDet < detArray->GetEntriesFast(); iDet++) {
1848             AliModule* det = (AliModule*) detArray->At(iDet);
1849             if (!det || !det->IsActive()) continue;
1850             if (IsSelected(det->GetName(), detStr)) {
1851               AliInfo(Form("Calling Raw2SDigits for %s\n", det->GetName()));
1852               det->Raw2SDigits(rawReader);
1853               rawReader->Reset();
1854             }
1855         } // detectors
1856
1857
1858         //
1859         //  If ESD information available obtain reconstructed vertex and store in header.
1860         if (treeESD) {
1861             treeESD->GetEvent(nev);
1862             const AliESDVertex* esdVertex = esd->GetPrimaryVertex();
1863             Double_t position[3];
1864             esdVertex->GetXYZ(position);
1865             AliGenEventHeader* mcHeader = new  AliGenEventHeader("ESD");
1866             TArrayF mcV;
1867             mcV.Set(3);
1868             for (Int_t i = 0; i < 3; i++) mcV[i] = position[i];
1869             mcHeader->SetPrimaryVertex(mcV);
1870             header->Reset(0,nev);
1871             header->SetGenEventHeader(mcHeader);
1872             printf("***** Saved vertex %f %f %f \n", position[0], position[1], position[2]);
1873         }
1874         nev++;
1875 //
1876 //      Finish the event
1877         runLoader->TreeE()->Fill();
1878         runLoader->SetNextEvent();
1879     } // events
1880  
1881     delete rawReader;
1882 //
1883 //  Finish the run 
1884     runLoader->CdGAFile();
1885     runLoader->WriteHeader("OVERWRITE");
1886     runLoader->WriteRunLoader();
1887
1888     return kTRUE;
1889 }
1890
1891 //_____________________________________________________________________________
1892 void AliSimulation::FinishRun()
1893 {
1894   //
1895   // Called at the end of the run.
1896   //
1897
1898   if(IsLegoRun()) 
1899    {
1900     AliDebug(1, "Finish Lego");
1901     AliRunLoader::Instance()->CdGAFile();
1902     fLego->FinishRun();
1903    }
1904   
1905   // Clean detector information
1906   TIter next(gAlice->Modules());
1907   AliModule *detector;
1908   while((detector = dynamic_cast<AliModule*>(next()))) {
1909     AliDebug(2, Form("%s->FinishRun()", detector->GetName()));
1910     detector->FinishRun();
1911   }
1912   
1913   AliDebug(1, "AliRunLoader::Instance()->WriteHeader(OVERWRITE)");
1914   AliRunLoader::Instance()->WriteHeader("OVERWRITE");
1915
1916   // Write AliRun info and all detectors parameters
1917   AliRunLoader::Instance()->CdGAFile();
1918   gAlice->Write(0,TObject::kOverwrite);//write AliRun
1919   AliRunLoader::Instance()->Write(0,TObject::kOverwrite);//write RunLoader itself
1920   
1921   if(gAlice->GetMCApp()) gAlice->GetMCApp()->FinishRun();  
1922   AliRunLoader::Instance()->Synchronize();
1923 }
1924
1925 //_____________________________________________________________________________
1926 Int_t AliSimulation::GetDetIndex(const char* detector)
1927 {
1928   // return the detector index corresponding to detector
1929   Int_t index = -1 ; 
1930   for (index = 0; index < fgkNDetectors ; index++) {
1931     if ( strcmp(detector, fgkDetectorName[index]) == 0 )
1932           break ; 
1933   }     
1934   return index ; 
1935 }
1936
1937 //_____________________________________________________________________________
1938 Bool_t AliSimulation::CreateHLT()
1939 {
1940   // Init the HLT simulation.
1941   // The function  loads the library and creates the instance of AliHLTSimulation.
1942   // the main reason for the decoupled creation is to set the transient OCDB
1943   // objects before the OCDB is locked
1944
1945   // load the library dynamically
1946   gSystem->Load(ALIHLTSIMULATION_LIBRARY);
1947
1948   // check for the library version
1949   AliHLTSimulationGetLibraryVersion_t fctVersion=(AliHLTSimulationGetLibraryVersion_t)(gSystem->DynFindSymbol(ALIHLTSIMULATION_LIBRARY, ALIHLTSIMULATION_GET_LIBRARY_VERSION));
1950   if (!fctVersion) {
1951     AliError(Form("can not load library %s", ALIHLTSIMULATION_LIBRARY));
1952     return kFALSE;
1953   }
1954   if (fctVersion()!= ALIHLTSIMULATION_LIBRARY_VERSION) {
1955     AliWarning(Form("%s version does not match: compiled for version %d, loaded %d", ALIHLTSIMULATION_LIBRARY, ALIHLTSIMULATION_LIBRARY_VERSION, fctVersion()));
1956   }
1957
1958   // print compile info
1959   typedef void (*CompileInfo)( const char*& date, const char*& time);
1960   CompileInfo fctInfo=(CompileInfo)gSystem->DynFindSymbol(ALIHLTSIMULATION_LIBRARY, "CompileInfo");
1961   if (fctInfo) {
1962     const char* date="";
1963     const char* time="";
1964     (*fctInfo)(date, time);
1965     if (!date) date="unknown";
1966     if (!time) time="unknown";
1967     AliInfo(Form("%s build on %s (%s)", ALIHLTSIMULATION_LIBRARY, date, time));
1968   } else {
1969     AliInfo(Form("no build info available for %s", ALIHLTSIMULATION_LIBRARY));
1970   }
1971
1972   // create instance of the HLT simulation
1973   AliHLTSimulationCreateInstance_t fctCreate=(AliHLTSimulationCreateInstance_t)(gSystem->DynFindSymbol(ALIHLTSIMULATION_LIBRARY, ALIHLTSIMULATION_CREATE_INSTANCE));
1974   if (fctCreate==NULL || (fpHLT=(fctCreate()))==NULL) {
1975     AliError(Form("can not create instance of HLT simulation (creator %p)", fctCreate));
1976     return kFALSE;    
1977   }
1978
1979   TString specObjects;
1980   for (Int_t i = 0; i < fSpecCDBUri.GetEntriesFast(); i++) {
1981     if (specObjects.Length()>0) specObjects+=" ";
1982     specObjects+=fSpecCDBUri[i]->GetName();
1983   }
1984
1985   AliHLTSimulationSetup_t fctSetup=(AliHLTSimulationSetup_t)(gSystem->DynFindSymbol(ALIHLTSIMULATION_LIBRARY, ALIHLTSIMULATION_SETUP));
1986   if (fctSetup==NULL || fctSetup(fpHLT, this, specObjects.Data())<0) {
1987     AliWarning(Form("failed to setup HLT simulation (function %p)", fctSetup));
1988   }
1989
1990   return kTRUE;
1991 }
1992
1993 //_____________________________________________________________________________
1994 Bool_t AliSimulation::RunHLT()
1995 {
1996   // Run the HLT simulation
1997   // HLT simulation is implemented in HLT/sim/AliHLTSimulation
1998   // Disabled if fRunHLT is empty, default vaule is "default".
1999   // AliSimulation::SetRunHLT can be used to set the options for HLT simulation
2000   // The default simulation depends on the HLT component libraries and their
2001   // corresponding agents which define components and chains to run. See
2002   // http://web.ift.uib.no/~kjeks/doc/alice-hlt-current/
2003   // http://web.ift.uib.no/~kjeks/doc/alice-hlt-current/classAliHLTModuleAgent.html
2004   //
2005   // The libraries to be loaded can be specified as an option.
2006   // <pre>
2007   // AliSimulation sim;
2008   // sim.SetRunHLT("libAliHLTSample.so");
2009   // </pre>
2010   // will only load <tt>libAliHLTSample.so</tt>
2011
2012   // Other available options:
2013   // \li loglevel=<i>level</i> <br>
2014   //     logging level for this processing
2015   // \li alilog=off
2016   //     disable redirection of log messages to AliLog class
2017   // \li config=<i>macro</i>
2018   //     configuration macro
2019   // \li chains=<i>configuration</i>
2020   //     comma separated list of configurations to be run during simulation
2021   // \li rawfile=<i>file</i>
2022   //     source for the RawReader to be created, the default is <i>./</i> if
2023   //     raw data is simulated
2024
2025   int iResult=0;
2026
2027   if (!fpHLT && !CreateHLT()) {
2028     return kFALSE;
2029   }
2030   AliHLTSimulation* pHLT=fpHLT;
2031
2032   AliRunLoader* pRunLoader = LoadRun("READ");
2033   if (!pRunLoader) return kFALSE;
2034
2035   // initialize CDB storage, run number, set CDB lock
2036   // thats for the case of running HLT simulation without all the other steps
2037   // multiple calls are handled by the function, so we can just call
2038   InitCDB();
2039   if (!SetRunNumberFromData()) if (fStopOnError) return kFALSE;
2040   SetCDBLock();
2041   
2042   // init the HLT simulation
2043   TString options;
2044   if (fRunHLT.CompareTo("default")!=0) options=fRunHLT;
2045   TString detStr = fWriteRawData;
2046   if (!IsSelected("HLT", detStr)) {
2047     options+=" writerawfiles=";
2048   } else {
2049     options+=" writerawfiles=HLT";
2050   }
2051
2052   if (!detStr.IsNull() && !options.Contains("rawfile=")) {
2053     // as a matter of fact, HLT will run reconstruction and needs the RawReader
2054     // in order to get detector data. By default, RawReaderFile is used to read
2055     // the already simulated ddl files. Date and Root files from the raw data
2056     // are generated after the HLT simulation.
2057     options+=" rawfile=./";
2058   }
2059
2060   AliHLTSimulationInit_t fctInit=(AliHLTSimulationInit_t)(gSystem->DynFindSymbol(ALIHLTSIMULATION_LIBRARY, ALIHLTSIMULATION_INIT));
2061   if (fctInit==NULL || (iResult=(fctInit(pHLT, pRunLoader, options.Data())))<0) {
2062     AliError(Form("can not init HLT simulation: error %d (init %p)", iResult, fctInit));
2063   } else {
2064     // run the HLT simulation
2065     AliHLTSimulationRun_t fctRun=(AliHLTSimulationRun_t)(gSystem->DynFindSymbol(ALIHLTSIMULATION_LIBRARY, ALIHLTSIMULATION_RUN));
2066     if (fctRun==NULL || (iResult=(fctRun(pHLT, pRunLoader)))<0) {
2067       AliError(Form("can not run HLT simulation: error %d (run %p)", iResult, fctRun));
2068     }
2069   }
2070
2071   // delete the instance
2072   AliHLTSimulationDeleteInstance_t fctDelete=(AliHLTSimulationDeleteInstance_t)(gSystem->DynFindSymbol(ALIHLTSIMULATION_LIBRARY, ALIHLTSIMULATION_DELETE_INSTANCE));
2073   if (fctDelete==NULL || fctDelete(pHLT)<0) {
2074     AliError(Form("can not delete instance of HLT simulation (creator %p)", fctDelete));
2075   }
2076   pHLT=NULL;
2077
2078   return iResult>=0?kTRUE:kFALSE;
2079 }
2080
2081 //_____________________________________________________________________________
2082 Bool_t AliSimulation::RunQA()
2083 {
2084         // run the QA on summable hits, digits or digits
2085         
2086   if(!gAlice) return kFALSE;
2087         AliQAManager::QAManager()->SetRunLoader(AliRunLoader::Instance()) ;
2088
2089         TString detectorsw("") ;  
2090         Bool_t rv = kTRUE ; 
2091   AliQAManager::QAManager()->SetEventSpecie(fEventSpecie) ;
2092         detectorsw = AliQAManager::QAManager()->Run(fQADetectors.Data()) ; 
2093         if ( detectorsw.IsNull() ) 
2094                 rv = kFALSE ; 
2095         return rv ; 
2096 }
2097
2098 //_____________________________________________________________________________
2099 Bool_t AliSimulation::SetRunQA(TString detAndAction) 
2100 {
2101         // Allows to run QA for a selected set of detectors
2102         // and a selected set of tasks among HITS, SDIGITS and DIGITS
2103         // all selected detectors run the same selected tasks
2104         
2105         if (!detAndAction.Contains(":")) {
2106                 AliError( Form("%s is a wrong syntax, use \"DetectorList:ActionList\" \n", detAndAction.Data()) ) ;
2107                 fRunQA = kFALSE ;
2108                 return kFALSE ;                 
2109         }
2110         Int_t colon = detAndAction.Index(":") ; 
2111         fQADetectors = detAndAction(0, colon) ; 
2112         if (fQADetectors.Contains("ALL") ){
2113     TString tmp = Form("%s %s", fMakeDigits.Data(), fMakeDigitsFromHits.Data()) ; 
2114     Int_t minus = fQADetectors.Last('-') ; 
2115     TString toKeep = Form("%s %s", fMakeDigits.Data(), fMakeDigitsFromHits.Data()) ; 
2116     TString toRemove("") ;
2117     while (minus >= 0) {
2118       toRemove = fQADetectors(minus+1, fQADetectors.Length()) ; 
2119       toRemove = toRemove.Strip() ; 
2120       toKeep.ReplaceAll(toRemove, "") ; 
2121       fQADetectors.ReplaceAll(Form("-%s", toRemove.Data()), "") ; 
2122       minus = fQADetectors.Last('-') ; 
2123     }
2124     fQADetectors = toKeep ; 
2125   }
2126   fQATasks   = detAndAction(colon+1, detAndAction.Sizeof() ) ; 
2127         if (fQATasks.Contains("ALL") ) {
2128                 fQATasks = Form("%d %d %d", AliQAv1::kHITS, AliQAv1::kSDIGITS, AliQAv1::kDIGITS) ; 
2129         } else {
2130                 fQATasks.ToUpper() ; 
2131                 TString tempo("") ; 
2132                 if ( fQATasks.Contains("HIT") ) 
2133                         tempo = Form("%d ", AliQAv1::kHITS) ; 
2134                 if ( fQATasks.Contains("SDIGIT") ) 
2135                         tempo += Form("%d ", AliQAv1::kSDIGITS) ; 
2136                 if ( fQATasks.Contains("DIGIT") ) 
2137                         tempo += Form("%d ", AliQAv1::kDIGITS) ; 
2138                 fQATasks = tempo ; 
2139                 if (fQATasks.IsNull()) {
2140                         AliInfo("No QA requested\n")  ;
2141                         fRunQA = kFALSE ;
2142                         return kTRUE ; 
2143                 }
2144         }       
2145         TString tempo(fQATasks) ; 
2146     tempo.ReplaceAll(Form("%d", AliQAv1::kHITS), AliQAv1::GetTaskName(AliQAv1::kHITS))  ;
2147     tempo.ReplaceAll(Form("%d", AliQAv1::kSDIGITS), AliQAv1::GetTaskName(AliQAv1::kSDIGITS)) ;  
2148     tempo.ReplaceAll(Form("%d", AliQAv1::kDIGITS), AliQAv1::GetTaskName(AliQAv1::kDIGITS)) ;    
2149         AliInfo( Form("QA will be done on \"%s\" for \"%s\"\n", fQADetectors.Data(), tempo.Data()) ) ;  
2150         fRunQA = kTRUE ;
2151         AliQAManager::QAManager()->SetActiveDetectors(fQADetectors) ; 
2152         AliQAManager::QAManager()->SetTasks(fQATasks) ; 
2153   for (Int_t det = 0 ; det < AliQAv1::kNDET ; det++) 
2154     AliQAManager::QAManager()->SetWriteExpert(AliQAv1::DETECTORINDEX_t(det)) ;
2155   
2156         return kTRUE; 
2157
2158
2159 //_____________________________________________________________________________
2160 void AliSimulation::ProcessEnvironmentVars()
2161 {
2162 // Extract run number and random generator seed from env variables
2163
2164     AliInfo("Processing environment variables");
2165     
2166     // Random Number seed
2167     
2168     // first check that seed is not already set
2169     if (fSeed == 0) {
2170         if (gSystem->Getenv("CONFIG_SEED")) {
2171                 fSeed = atoi(gSystem->Getenv("CONFIG_SEED"));
2172         }
2173     } else {
2174         if (gSystem->Getenv("CONFIG_SEED")) {
2175                 AliInfo(Form("Seed for random number generation already set (%d)"
2176                              ": CONFIG_SEED variable ignored!", fSeed));
2177         }
2178     }
2179    
2180     AliInfo(Form("Seed for random number generation = %d ", fSeed)); 
2181
2182     // Run Number
2183     
2184     // first check that run number is not already set
2185     if(fRun < 0) {    
2186         if (gSystem->Getenv("DC_RUN")) {
2187                 fRun = atoi(gSystem->Getenv("DC_RUN"));
2188         }
2189     } else {
2190         if (gSystem->Getenv("DC_RUN")) {
2191                 AliInfo(Form("Run number already set (%d): DC_RUN variable ignored!", fRun));
2192         }
2193     }
2194     
2195     AliInfo(Form("Run number = %d", fRun)); 
2196 }
2197
2198 //---------------------------------------------------------------------
2199 void AliSimulation::WriteGRPEntry()
2200 {
2201   // Get the necessary information from galice (generator, trigger etc) and
2202   // write a GRP entry corresponding to the settings in the Config.C used
2203   // note that Hall probes and Cavern and Surface Atmos pressures are not simulated.
2204
2205
2206   AliInfo("Writing global run parameters entry into the OCDB");
2207
2208   AliGRPObject* grpObj = new AliGRPObject();
2209
2210   grpObj->SetRunType("PHYSICS");
2211   grpObj->SetTimeStart(0);
2212   TDatime curtime;
2213   grpObj->SetTimeStart(0);
2214   grpObj->SetTimeEnd(curtime.Convert()); 
2215   grpObj->SetBeamEnergyIsSqrtSHalfGeV(); // new format of GRP: store sqrt(s)/2 in GeV
2216
2217   const AliGenerator *gen = gAlice->GetMCApp()->Generator();
2218   if (gen) {
2219     grpObj->SetBeamEnergy(gen->GetEnergyCMS()/2);
2220     TString projectile;
2221     Int_t a,z;
2222     gen->GetProjectile(projectile,a,z);
2223     TString target;
2224     gen->GetTarget(target,a,z);
2225     TString beamType = projectile + "-" + target;
2226     beamType.ReplaceAll(" ","");
2227     if (!beamType.CompareTo("-")) {
2228       grpObj->SetBeamType("UNKNOWN");
2229     }
2230     else {
2231       grpObj->SetBeamType(beamType);
2232       // Heavy ion run, the event specie is set to kHighMult
2233       fEventSpecie = AliRecoParam::kHighMult;
2234       if ((strcmp(beamType,"p-p") == 0) ||
2235           (strcmp(beamType,"p-")  == 0) ||
2236           (strcmp(beamType,"-p")  == 0) ||
2237           (strcmp(beamType,"P-P") == 0) ||
2238           (strcmp(beamType,"P-")  == 0) ||
2239           (strcmp(beamType,"-P")  == 0)) {
2240         // Proton run, the event specie is set to kLowMult
2241         fEventSpecie = AliRecoParam::kLowMult;
2242       } 
2243     }
2244   } else {
2245     AliWarning("Unknown beam type and energy! Setting energy to 0");
2246     grpObj->SetBeamEnergy(0);
2247     grpObj->SetBeamType("UNKNOWN");
2248   }
2249
2250   UInt_t detectorPattern  = 0;
2251   Int_t nDets = 0;
2252   TObjArray *detArray = gAlice->Detectors();
2253   for (Int_t iDet = 0; iDet < AliDAQ::kNDetectors-1; iDet++) {
2254     if (detArray->FindObject(AliDAQ::OfflineModuleName(iDet))) {
2255       detectorPattern |= (1 << iDet);
2256       nDets++;
2257     }
2258   }
2259   // CTP
2260   if (!fTriggerConfig.IsNull())
2261     detectorPattern |= (1 << AliDAQ::DetectorID("TRG"));
2262
2263   // HLT
2264   if (!fRunHLT.IsNull())
2265     detectorPattern |= (1 << AliDAQ::kHLTId);
2266
2267   grpObj->SetNumberOfDetectors((Char_t)nDets);
2268   grpObj->SetDetectorMask((Int_t)detectorPattern);
2269   grpObj->SetLHCPeriod("LHC08c");
2270   grpObj->SetLHCState("STABLE_BEAMS");
2271   //
2272   AliMagF *field = (AliMagF*)TGeoGlobalMagField::Instance()->GetField();
2273   Float_t solenoidField = field ? TMath::Abs(field->SolenoidField()) : 0;
2274
2275   Float_t factorSol     = field ? field->GetFactorSol() : 0;
2276   Float_t currentSol    = TMath::Abs(factorSol)>1E-6 ? 
2277     TMath::Nint(TMath::Abs(solenoidField/factorSol))/5.*30000.*TMath::Abs(factorSol) : 0;
2278   //
2279   Float_t factorDip     = field ? field->GetFactorDip() : 0;
2280   Float_t currentDip    = 6000.*TMath::Abs(factorDip);
2281   //
2282   grpObj->SetL3Current(currentSol,(AliGRPObject::Stats)0);
2283   grpObj->SetDipoleCurrent(currentDip,(AliGRPObject::Stats)0);  
2284   grpObj->SetL3Polarity(factorSol>0 ? 0:1);  
2285   grpObj->SetDipolePolarity(factorDip>0 ? 0:1);
2286   grpObj->SetUniformBMap(field->IsUniform());            // for special MC with k5kGUniform map
2287   grpObj->SetPolarityConventionLHC();                    // LHC convention +/+ current -> -/- field main components
2288   //
2289   grpObj->SetCavernTemperature(0,(AliGRPObject::Stats)0);
2290   
2291   //grpMap->Add(new TObjString("fCavernPressure"),new TObjString("0")); ---> not inserted in simulation with the new object, since it is now an AliDCSSensor
2292
2293   // Now store the entry in OCDB
2294   AliCDBManager* man = AliCDBManager::Instance();
2295
2296   AliCDBId id("GRP/GRP/Data", man->GetRun(), man->GetRun(), 1, 1);
2297   AliCDBMetaData *metadata= new AliCDBMetaData();
2298
2299   metadata->SetResponsible("alice-off@cern.ch");
2300   metadata->SetComment("Automatically produced GRP entry for Monte Carlo");
2301  
2302   man->Put(grpObj,id,metadata);
2303 }
2304
2305