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