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