1 /**************************************************************************
2 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
4 * Author: The ALICE Off-line Project. *
5 * Contributors are mentioned in the code where appropriate. *
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 **************************************************************************/
18 ///////////////////////////////////////////////////////////////////////////////
20 // class for running generation, simulation and digitization //
22 // Hits, sdigits and digits are created for all detectors by typing: //
24 // AliSimulation sim; //
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 //
31 // sim.SetNumberOfEvents(n); //
33 // The name of the configuration file can be passed as argument to the //
34 // AliSimulation constructor or can be specified by //
36 // sim.SetConfigFile("..."); //
38 // The generation of particles and the simulation of detector hits can be //
39 // switched on or off by //
41 // sim.SetRunGeneration(kTRUE); // generation of primary particles //
42 // sim.SetRunSimulation(kFALSE); // but no tracking //
44 // For which detectors sdigits and digits will be created, can be steered //
47 // sim.SetMakeSDigits("ALL"); // make sdigits for all detectors //
48 // sim.SetMakeDigits("ITS TPC"); // make digits only for ITS and TPC //
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. //
55 // The creation of digits from hits instead of from sdigits can be selected //
58 // sim.SetMakeDigitsFromHits("TRD"); //
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. //
64 // Background events can be merged by calling //
66 // sim.MergeWith("background/galice.root", 2); //
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. //
75 // The output of raw data can be switched on by calling //
77 // sim.SetWriteRawData("MUON"); // write raw data for MUON //
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 //
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. //
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 //
98 // sim.SetEventsPerFile("PHOS", "Reconstructed Points", 3); //
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. //
106 ///////////////////////////////////////////////////////////////////////////////
110 #include <TGeoGlobalMagField.h>
111 #include <TGeoManager.h>
112 #include <TObjString.h>
115 #include <TVirtualMC.h>
116 #include <TVirtualMCApplication.h>
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"
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"
138 #include "AliLegoGenerator.h"
142 #include "AliModule.h"
144 #include "AliRawReaderDate.h"
145 #include "AliRawReaderFile.h"
146 #include "AliRawReaderRoot.h"
148 #include "AliRunDigitizer.h"
149 #include "AliRunLoader.h"
150 #include "AliSimulation.h"
151 #include "AliSysInfo.h"
152 #include "AliVertexGenFile.h"
154 ClassImp(AliSimulation)
156 AliSimulation *AliSimulation::fgInstance = 0;
157 const char* AliSimulation::fgkDetectorName[AliSimulation::fgkNDetectors] = {"ITS", "TPC", "TRD", "TOF", "PHOS", "HMPID", "EMCAL", "MUON", "FMD", "ZDC", "PMD", "T0", "VZERO", "ACORDE", "HLT"};
159 //_____________________________________________________________________________
160 AliSimulation::AliSimulation(const char* configFileName,
161 const char* name, const char* title) :
164 fRunGeneration(kTRUE),
165 fRunSimulation(kTRUE),
166 fLoadAlignFromCDB(kTRUE),
167 fLoadAlObjsListOfDets("ALL"),
171 fMakeDigitsFromHits(""),
173 fRawDataFileName(""),
174 fDeleteIntermediateFiles(kFALSE),
175 fWriteSelRawData(kFALSE),
176 fStopOnError(kFALSE),
178 fConfigFileName(configFileName),
179 fGAliceFileName("galice.root"),
181 fBkgrdFileNames(NULL),
182 fAlignObjArray(NULL),
183 fUseBkgrdVertex(kTRUE),
184 fRegionOfInterest(kFALSE),
190 fInitCDBCalled(kFALSE),
191 fInitRunNumberCalled(kFALSE),
192 fSetRunNumberFromDataCalled(kFALSE),
193 fEmbeddingFlag(kFALSE),
196 fUseVertexFromCDB(0),
197 fUseMagFieldFromGRP(0),
198 fGRPWriteLocation(Form("local://%s", gSystem->pwd())),
199 fUseTimeStampFromCDB(0),
205 fEventSpecie(AliRecoParam::kDefault),
206 fWriteQAExpertData(kTRUE),
210 fWriteGRPEntry(kTRUE)
212 // create simulation object with default parameters
214 SetGAliceFile("galice.root");
217 AliQAManager * qam = AliQAManager::QAManager(AliQAv1::kSIMMODE) ;
218 qam->SetActiveDetectors(fQADetectors) ;
219 fQATasks = Form("%d %d %d", AliQAv1::kHITS, AliQAv1::kSDIGITS, AliQAv1::kDIGITS) ;
220 qam->SetTasks(fQATasks) ;
223 //_____________________________________________________________________________
224 AliSimulation::~AliSimulation()
228 fEventsPerFile.Delete();
229 // if(fAlignObjArray) fAlignObjArray->Delete(); // fAlignObjArray->RemoveAll() ???
230 // delete fAlignObjArray; fAlignObjArray=0;
232 if (fBkgrdFileNames) {
233 fBkgrdFileNames->Delete();
234 delete fBkgrdFileNames;
237 fSpecCDBUri.Delete();
238 if (fgInstance==this) fgInstance = 0;
240 AliQAManager::QAManager()->ShowQA() ;
241 AliQAManager::Destroy() ;
242 AliCodeTimer::Instance()->Print();
246 //_____________________________________________________________________________
247 void AliSimulation::SetNumberOfEvents(Int_t nEvents)
249 // set the number of events for one run
254 //_____________________________________________________________________________
255 void AliSimulation::InitQA()
257 // activate a default CDB storage
258 // First check if we have any CDB storage set, because it is used
259 // to retrieve the calibration and alignment constants
261 if (fInitCDBCalled) return;
262 fInitCDBCalled = kTRUE;
264 AliQAManager * qam = AliQAManager::QAManager(AliQAv1::kSIMMODE) ;
265 qam->SetActiveDetectors(fQADetectors) ;
266 fQATasks = Form("%d %d %d", AliQAv1::kHITS, AliQAv1::kSDIGITS, AliQAv1::kDIGITS) ;
267 qam->SetTasks(fQATasks) ;
268 if (fWriteQAExpertData)
269 qam->SetWriteExpert() ;
271 if (qam->IsDefaultStorageSet()) {
272 AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
273 AliWarning("Default QA reference storage has been already set !");
274 AliWarning(Form("Ignoring the default storage declared in AliSimulation: %s",fQARefUri.Data()));
275 AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
276 fQARefUri = qam->GetDefaultStorage()->GetURI();
278 if (fQARefUri.Length() > 0) {
279 AliDebug(2,"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
280 AliDebug(2, Form("Default QA reference storage is set to: %s", fQARefUri.Data()));
281 AliDebug(2, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
283 fQARefUri="local://$ALICE_ROOT/QARef";
284 AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
285 AliWarning("Default QA reference storage not yet set !!!!");
286 AliWarning(Form("Setting it now to: %s", fQARefUri.Data()));
287 AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
289 qam->SetDefaultStorage(fQARefUri);
293 //_____________________________________________________________________________
294 void AliSimulation::InitCDB()
296 // activate a default CDB storage
297 // First check if we have any CDB storage set, because it is used
298 // to retrieve the calibration and alignment constants
300 if (fInitCDBCalled) return;
301 fInitCDBCalled = kTRUE;
303 AliCDBManager* man = AliCDBManager::Instance();
304 if (man->IsDefaultStorageSet())
306 AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
307 AliWarning("Default CDB storage has been already set !");
308 AliWarning(Form("Ignoring the default storage declared in AliSimulation: %s",fCDBUri.Data()));
309 AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
310 fCDBUri = man->GetDefaultStorage()->GetURI();
313 if (fCDBUri.Length() > 0)
315 AliDebug(2,"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
316 AliDebug(2, Form("Default CDB storage is set to: %s", fCDBUri.Data()));
317 AliDebug(2, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
319 fCDBUri="local://$ALICE_ROOT/OCDB";
320 AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
321 AliWarning("Default CDB storage not yet set !!!!");
322 AliWarning(Form("Setting it now to: %s", fCDBUri.Data()));
323 AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
326 man->SetDefaultStorage(fCDBUri);
329 // Now activate the detector specific CDB storage locations
330 for (Int_t i = 0; i < fSpecCDBUri.GetEntriesFast(); i++) {
331 TObject* obj = fSpecCDBUri[i];
333 AliDebug(2, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
334 AliDebug(2, Form("Specific CDB storage for %s is set to: %s",obj->GetName(),obj->GetTitle()));
335 AliDebug(2, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
336 man->SetSpecificStorage(obj->GetName(), obj->GetTitle());
341 //_____________________________________________________________________________
342 void AliSimulation::InitRunNumber(){
343 // check run number. If not set, set it to 0 !!!!
345 if (fInitRunNumberCalled) return;
346 fInitRunNumberCalled = kTRUE;
348 AliCDBManager* man = AliCDBManager::Instance();
349 if (man->GetRun() >= 0)
351 AliFatal(Form("Run number cannot be set in AliCDBManager before start of simulation: "
352 "Use external variable DC_RUN or AliSimulation::SetRun()!"));
356 AliDebug(2, Form("Setting CDB run number to: %d",fRun));
359 AliWarning(Form("Run number not yet set !!!! Setting it now to: %d",
368 //_____________________________________________________________________________
369 void AliSimulation::SetCDBLock() {
370 // Set CDB lock: from now on it is forbidden to reset the run number
371 // or the default storage or to activate any further storage!
373 ULong_t key = AliCDBManager::Instance()->SetLock(1);
377 //_____________________________________________________________________________
378 void AliSimulation::SetDefaultStorage(const char* uri) {
379 // Store the desired default CDB storage location
380 // Activate it later within the Run() method
386 //_____________________________________________________________________________
387 void AliSimulation::SetQARefDefaultStorage(const char* uri) {
388 // Store the desired default CDB storage location
389 // Activate it later within the Run() method
392 AliQAv1::SetQARefStorage(fQARefUri.Data()) ;
395 //_____________________________________________________________________________
396 void AliSimulation::SetSpecificStorage(const char* calibType, const char* uri) {
397 // Store a detector-specific CDB storage location
398 // Activate it later within the Run() method
400 AliCDBPath aPath(calibType);
401 if(!aPath.IsValid()){
402 AliError(Form("Not a valid path: %s", calibType));
406 TObject* obj = fSpecCDBUri.FindObject(calibType);
407 if (obj) fSpecCDBUri.Remove(obj);
408 fSpecCDBUri.Add(new TNamed(calibType, uri));
412 //_____________________________________________________________________________
413 void AliSimulation::SetRunNumber(Int_t run)
416 // Activate it later within the Run() method
421 //_____________________________________________________________________________
422 void AliSimulation::SetSeed(Int_t seed)
425 // Activate it later within the Run() method
430 //_____________________________________________________________________________
431 Bool_t AliSimulation::SetRunNumberFromData()
433 // Set the CDB manager run number
434 // The run number is retrieved from gAlice
436 if (fSetRunNumberFromDataCalled) return kTRUE;
437 fSetRunNumberFromDataCalled = kTRUE;
439 AliCDBManager* man = AliCDBManager::Instance();
440 Int_t runData = -1, runCDB = -1;
442 AliRunLoader* runLoader = LoadRun("READ");
443 if (!runLoader) return kFALSE;
445 runData = runLoader->GetHeader()->GetRun();
449 runCDB = man->GetRun();
451 if (runCDB != runData) {
452 AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
453 AliWarning(Form("A run number was previously set in AliCDBManager: %d !", runCDB));
454 AliWarning(Form("It will be replaced with the run number got from run header: %d !", runData));
455 AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
460 man->SetRun(runData);
463 if(man->GetRun() < 0) {
464 AliError("Run number not properly initalized!");
473 //_____________________________________________________________________________
474 void AliSimulation::SetConfigFile(const char* fileName)
476 // set the name of the config file
478 fConfigFileName = fileName;
481 //_____________________________________________________________________________
482 void AliSimulation::SetGAliceFile(const char* fileName)
484 // set the name of the galice file
485 // the path is converted to an absolute one if it is relative
487 fGAliceFileName = fileName;
488 if (!gSystem->IsAbsoluteFileName(fGAliceFileName)) {
489 char* absFileName = gSystem->ConcatFileName(gSystem->WorkingDirectory(),
491 fGAliceFileName = absFileName;
492 delete[] absFileName;
495 AliDebug(2, Form("galice file name set to %s", fileName));
498 //_____________________________________________________________________________
499 void AliSimulation::SetEventsPerFile(const char* detector, const char* type,
502 // set the number of events per file for the given detector and data type
503 // ("Hits", "Summable Digits", "Digits", "Reconstructed Points" or "Tracks")
505 TNamed* obj = new TNamed(detector, type);
506 obj->SetUniqueID(nEvents);
507 fEventsPerFile.Add(obj);
510 //_____________________________________________________________________________
511 Bool_t AliSimulation::MisalignGeometry(AliRunLoader *runLoader)
513 // Read the alignment objects from CDB.
514 // Each detector is supposed to have the
515 // alignment objects in DET/Align/Data CDB path.
516 // All the detector objects are then collected,
517 // sorted by geometry level (starting from ALIC) and
518 // then applied to the TGeo geometry.
519 // Finally an overlaps check is performed.
521 if (!AliGeomManager::GetGeometry() || !AliGeomManager::GetGeometry()->IsClosed()) {
522 AliError("Can't apply the misalignment! Geometry is not loaded or it is still opened!");
526 // initialize CDB storage, run number, set CDB lock
528 // if (!SetRunNumberFromData()) if (fStopOnError) return kFALSE;
531 Bool_t delRunLoader = kFALSE;
533 runLoader = LoadRun("READ");
534 if (!runLoader) return kFALSE;
535 delRunLoader = kTRUE;
538 // Export ideal geometry
539 if(!IsGeometryFromFile()) AliGeomManager::GetGeometry()->Export("geometry.root");
541 // Load alignment data from CDB and apply to geometry through AliGeomManager
542 if(fLoadAlignFromCDB){
544 TString detStr = fLoadAlObjsListOfDets;
545 TString loadAlObjsListOfDets = "";
547 TObjArray* detArray = runLoader->GetAliRun()->Detectors();
548 for (Int_t iDet = 0; iDet < detArray->GetEntriesFast(); iDet++) {
549 AliModule* det = (AliModule*) detArray->At(iDet);
550 if (!det || !det->IsActive()) continue;
551 if (IsSelected(det->GetName(), detStr)) {
552 //add det to list of dets to be aligned from CDB
553 loadAlObjsListOfDets += det->GetName();
554 loadAlObjsListOfDets += " ";
556 } // end loop over detectors
557 loadAlObjsListOfDets.Prepend("GRP "); //add alignment objects for non-sensitive modules
558 AliGeomManager::ApplyAlignObjsFromCDB(loadAlObjsListOfDets.Data());
560 // Check if the array with alignment objects was
561 // provided by the user. If yes, apply the objects
562 // to the present TGeo geometry
563 if (fAlignObjArray) {
564 if (AliGeomManager::ApplyAlignObjsToGeom(*fAlignObjArray) == kFALSE) {
565 AliError("The misalignment of one or more volumes failed!"
566 "Compare the list of simulated detectors and the list of detector alignment data!");
567 if (delRunLoader) delete runLoader;
573 // Update the internal geometry of modules (ITS needs it)
574 TString detStr = fLoadAlObjsListOfDets;
575 TObjArray* detArray = runLoader->GetAliRun()->Detectors();
576 for (Int_t iDet = 0; iDet < detArray->GetEntriesFast(); iDet++) {
578 AliModule* det = (AliModule*) detArray->At(iDet);
579 if (!det || !det->IsActive()) continue;
580 if (IsSelected(det->GetName(), detStr)) {
581 det->UpdateInternalGeometry();
583 } // end loop over detectors
586 if (delRunLoader) delete runLoader;
591 //_____________________________________________________________________________
592 void AliSimulation::MergeWith(const char* fileName, Int_t nSignalPerBkgrd)
594 // add a file with background events for merging
596 TObjString* fileNameStr = new TObjString(fileName);
597 fileNameStr->SetUniqueID(nSignalPerBkgrd);
598 if (!fBkgrdFileNames) fBkgrdFileNames = new TObjArray;
599 fBkgrdFileNames->Add(fileNameStr);
602 void AliSimulation::EmbedInto(const char* fileName, Int_t nSignalPerBkgrd)
604 // add a file with background events for embeddin
605 MergeWith(fileName, nSignalPerBkgrd);
606 fEmbeddingFlag = kTRUE;
609 //_____________________________________________________________________________
610 Bool_t AliSimulation::Run(Int_t nEvents)
612 // run the generation, simulation and digitization
615 AliCodeTimerAuto("",0)
616 AliSysInfo::AddStamp("Start_Run");
618 // Load run number and seed from environmental vars
619 ProcessEnvironmentVars();
620 AliSysInfo::AddStamp("ProcessEnvironmentVars");
622 gRandom->SetSeed(fSeed);
624 if (nEvents > 0) fNEvents = nEvents;
626 // create and setup the HLT instance
627 if (!fRunHLT.IsNull() && !CreateHLT()) {
628 if (fStopOnError) return kFALSE;
633 // generation and simulation -> hits
634 if (fRunGeneration) {
635 if (!RunSimulation()) if (fStopOnError) return kFALSE;
637 AliSysInfo::AddStamp("RunSimulation");
639 // initialize CDB storage from external environment
640 // (either CDB manager or AliSimulation setters),
641 // if not already done in RunSimulation()
643 AliSysInfo::AddStamp("InitCDB");
645 // Set run number in CDBManager from data
646 // From this point on the run number must be always loaded from data!
647 if (!SetRunNumberFromData()) if (fStopOnError) return kFALSE;
649 // Set CDB lock: from now on it is forbidden to reset the run number
650 // or the default storage or to activate any further storage!
653 // If RunSimulation was not called, load the geometry and misalign it
654 if (!AliGeomManager::GetGeometry()) {
655 // Initialize the geometry manager
656 AliGeomManager::LoadGeometry("geometry.root");
657 AliSysInfo::AddStamp("GetGeometry");
658 // // Check that the consistency of symbolic names for the activated subdetectors
659 // // in the geometry loaded by AliGeomManager
660 // AliRunLoader* runLoader = LoadRun("READ");
661 // if (!runLoader) return kFALSE;
663 // TString detsToBeChecked = "";
664 // TObjArray* detArray = runLoader->GetAliRun()->Detectors();
665 // for (Int_t iDet = 0; iDet < detArray->GetEntriesFast(); iDet++) {
666 // AliModule* det = (AliModule*) detArray->At(iDet);
667 // if (!det || !det->IsActive()) continue;
668 // detsToBeChecked += det->GetName();
669 // detsToBeChecked += " ";
670 // } // end loop over detectors
671 // if(!AliGeomManager::CheckSymNamesLUT(detsToBeChecked.Data()))
672 if(!AliGeomManager::CheckSymNamesLUT("ALL"))
673 AliFatalClass("Current loaded geometry differs in the definition of symbolic names!");
675 if (!AliGeomManager::GetGeometry()) if (fStopOnError) return kFALSE;
677 if(!MisalignGeometry()) if (fStopOnError) return kFALSE;
679 AliSysInfo::AddStamp("MissalignGeometry");
682 // hits -> summable digits
683 AliSysInfo::AddStamp("Start_sdigitization");
684 if (!fMakeSDigits.IsNull()) {
685 if (!RunSDigitization(fMakeSDigits)) if (fStopOnError) return kFALSE;
688 AliSysInfo::AddStamp("Stop_sdigitization");
690 AliSysInfo::AddStamp("Start_digitization");
691 // summable digits -> digits
692 if (!fMakeDigits.IsNull()) {
693 if (!RunDigitization(fMakeDigits, fMakeDigitsFromHits)) {
694 if (fStopOnError) return kFALSE;
697 AliSysInfo::AddStamp("Stop_digitization");
702 if (!fMakeDigitsFromHits.IsNull()) {
703 if (fBkgrdFileNames && (fBkgrdFileNames->GetEntriesFast() > 0)) {
704 AliWarning(Form("Merging and direct creation of digits from hits "
705 "was selected for some detectors. "
706 "No merging will be done for the following detectors: %s",
707 fMakeDigitsFromHits.Data()));
709 if (!RunHitsDigitization(fMakeDigitsFromHits)) {
710 if (fStopOnError) return kFALSE;
714 AliSysInfo::AddStamp("Hits2Digits");
718 if (!fTriggerConfig.IsNull() && !RunTrigger(fTriggerConfig,fMakeDigits)) {
719 if (fStopOnError) return kFALSE;
722 AliSysInfo::AddStamp("RunTrigger");
725 // digits -> raw data
726 if (!fWriteRawData.IsNull()) {
727 if (!WriteRawData(fWriteRawData, fRawDataFileName,
728 fDeleteIntermediateFiles,fWriteSelRawData)) {
729 if (fStopOnError) return kFALSE;
733 AliSysInfo::AddStamp("WriteRaw");
735 // run HLT simulation on simulated digit data if raw data is not
736 // simulated, otherwise its called as part of WriteRawData
737 if (!fRunHLT.IsNull() && fWriteRawData.IsNull()) {
739 if (fStopOnError) return kFALSE;
743 AliSysInfo::AddStamp("RunHLT");
747 Bool_t rv = RunQA() ;
753 AliSysInfo::AddStamp("RunQA");
755 // Cleanup of CDB manager: cache and active storages!
756 AliCDBManager::Instance()->ClearCache();
761 //_______________________________________________________________________
762 Bool_t AliSimulation::RunLego(const char *setup, Int_t nc1, Float_t c1min,
763 Float_t c1max,Int_t nc2,Float_t c2min,Float_t c2max,
764 Float_t rmin,Float_t rmax,Float_t zmax, AliLegoGenerator* gener, Int_t nev)
767 // Generates lego plots of:
768 // - radiation length map phi vs theta
769 // - radiation length map phi vs eta
770 // - interaction length map
771 // - g/cm2 length map
773 // ntheta bins in theta, eta
774 // themin minimum angle in theta (degrees)
775 // themax maximum angle in theta (degrees)
777 // phimin minimum angle in phi (degrees)
778 // phimax maximum angle in phi (degrees)
779 // rmin minimum radius
780 // rmax maximum radius
783 // The number of events generated = ntheta*nphi
784 // run input parameters in macro setup (default="Config.C")
786 // Use macro "lego.C" to visualize the 3 lego plots in spherical coordinates
789 <img src="picts/AliRunLego1.gif">
794 <img src="picts/AliRunLego2.gif">
799 <img src="picts/AliRunLego3.gif">
804 // run the generation and simulation
806 AliCodeTimerAuto("",0)
808 // initialize CDB storage and run number from external environment
809 // (either CDB manager or AliSimulation setters)
815 AliError("no gAlice object. Restart aliroot and try again.");
818 if (gAlice->Modules()->GetEntries() > 0) {
819 AliError("gAlice was already run. Restart aliroot and try again.");
823 AliInfo(Form("initializing gAlice with config file %s",
824 fConfigFileName.Data()));
827 if (nev == -1) nev = nc1 * nc2;
829 // check if initialisation has been done
830 // If runloader has been initialized, set the number of events per file to nc1 * nc2
833 if (!gener) gener = new AliLegoGenerator();
835 // Configure Generator
837 gener->SetRadiusRange(rmin, rmax);
838 gener->SetZMax(zmax);
839 gener->SetCoor1Range(nc1, c1min, c1max);
840 gener->SetCoor2Range(nc2, c2min, c2max);
844 fLego = new AliLego("lego",gener);
846 //__________________________________________________________________________
850 gROOT->LoadMacro(setup);
851 gInterpreter->ProcessLine(gAlice->GetConfigFunction());
853 if(AliCDBManager::Instance()->GetRun() >= 0) {
854 SetRunNumber(AliCDBManager::Instance()->GetRun());
856 AliWarning("Run number not initialized!!");
859 AliRunLoader::Instance()->CdGAFile();
861 AliPDG::AddParticlesToPdgDataBase();
863 gMC->SetMagField(TGeoGlobalMagField::Instance()->GetField());
865 gAlice->GetMCApp()->Init();
868 //Must be here because some MCs (G4) adds detectors here and not in Config.C
869 gAlice->InitLoaders();
870 AliRunLoader::Instance()->MakeTree("E");
873 // Save stuff at the beginning of the file to avoid file corruption
874 AliRunLoader::Instance()->CdGAFile();
877 //Save current generator
878 AliGenerator *gen=gAlice->GetMCApp()->Generator();
879 gAlice->GetMCApp()->ResetGenerator(gener);
880 //Prepare MC for Lego Run
886 AliRunLoader::Instance()->SetNumberOfEventsPerFile(nev);
887 gMC->ProcessRun(nev);
889 // End of this run, close files
891 // Restore current generator
892 gAlice->GetMCApp()->ResetGenerator(gen);
893 // Delete Lego Object
899 //_____________________________________________________________________________
900 Bool_t AliSimulation::RunTrigger(const char* config, const char* detectors)
904 AliCodeTimerAuto("",0)
906 // initialize CDB storage from external environment
907 // (either CDB manager or AliSimulation setters),
908 // if not already done in RunSimulation()
911 // Set run number in CDBManager from data
912 // From this point on the run number must be always loaded from data!
913 if (!SetRunNumberFromData()) if (fStopOnError) return kFALSE;
915 // Set CDB lock: from now on it is forbidden to reset the run number
916 // or the default storage or to activate any further storage!
919 AliRunLoader* runLoader = LoadRun("READ");
920 if (!runLoader) return kFALSE;
921 TString trconfiguration = config;
923 if (trconfiguration.IsNull()) {
924 if(!fTriggerConfig.IsNull()) {
925 trconfiguration = fTriggerConfig;
928 AliWarning("No trigger descriptor is specified. Loading the one that is in the CDB.");
931 runLoader->MakeTree( "GG" );
932 AliCentralTrigger* aCTP = runLoader->GetTrigger();
933 // Load Configuration
934 if (!aCTP->LoadConfiguration( trconfiguration ))
938 if( !aCTP->RunTrigger( runLoader , detectors ) ) {
950 //_____________________________________________________________________________
951 Bool_t AliSimulation::WriteTriggerRawData()
953 // Writes the CTP (trigger) DDL raw data
954 // Details of the format are given in the
955 // trigger TDR - pages 134 and 135.
956 AliCTPRawData writer;
962 //_____________________________________________________________________________
963 Bool_t AliSimulation::RunSimulation(Int_t nEvents)
965 // run the generation and simulation
967 AliCodeTimerAuto("",0)
969 // initialize CDB storage and run number from external environment
970 // (either CDB manager or AliSimulation setters)
971 AliSysInfo::AddStamp("RunSimulation_Begin");
973 AliSysInfo::AddStamp("RunSimulation_InitCDB");
976 AliSysInfo::AddStamp("RunSimulation_SetCDBLock");
979 AliError("no gAlice object. Restart aliroot and try again.");
982 if (gAlice->Modules()->GetEntries() > 0) {
983 AliError("gAlice was already run. Restart aliroot and try again.");
987 AliInfo(Form("initializing gAlice with config file %s",
988 fConfigFileName.Data()));
991 // Initialize ALICE Simulation run
996 // If requested set the mag. field from the GRP entry.
997 // After this the field is loccked and cannot be changed by Config.C
998 if (fUseMagFieldFromGRP) {
1000 grpM.ReadGRPEntry();
1002 AliInfo("Field is locked now. It cannot be changed in Config.C");
1006 gROOT->LoadMacro(fConfigFileName.Data());
1007 gInterpreter->ProcessLine(gAlice->GetConfigFunction());
1008 AliSysInfo::AddStamp("RunSimulation_Config");
1011 // If requested obtain the vertex position and vertex sigma_z from the CDB
1012 // This overwrites the settings from the Config.C
1013 if (fUseVertexFromCDB) {
1014 Double_t vtxPos[3] = {0., 0., 0.};
1015 Double_t vtxSig[3] = {0., 0., 0.};
1016 AliCDBEntry* entry = AliCDBManager::Instance()->Get("GRP/Calib/MeanVertex");
1018 AliESDVertex* vertex = dynamic_cast<AliESDVertex*> (entry->GetObject());
1020 if(vertex->GetXRes()>2.8) { // > pipe radius --> it's a dummy object, don't use it
1021 entry = AliCDBManager::Instance()->Get("GRP/Calib/MeanVertexSPD");
1022 if (entry) vertex = dynamic_cast<AliESDVertex*> (entry->GetObject());
1026 vertex->GetXYZ(vtxPos);
1027 vertex->GetSigmaXYZ(vtxSig);
1028 AliInfo("Overwriting Config.C vertex settings !");
1029 AliInfo(Form("Vertex position from OCDB entry: x = %13.3f, y = %13.3f, z = %13.3f (sigma = %13.3f)\n",
1030 vtxPos[0], vtxPos[1], vtxPos[2], vtxSig[2]));
1032 AliGenerator *gen = gAlice->GetMCApp()->Generator();
1033 gen->SetOrigin(vtxPos[0], vtxPos[1], vtxPos[2]); // vertex position
1034 gen->SetSigmaZ(vtxSig[2]);
1039 // If requested we take the SOR and EOR time-stamps from the GRP and use them
1040 // in order to generate the event time-stamps
1041 if (fUseTimeStampFromCDB) {
1043 grpM.ReadGRPEntry();
1044 const AliGRPObject *grpObj = grpM.GetGRPData();
1045 if (!grpObj || (grpObj->GetTimeEnd() <= grpObj->GetTimeStart())) {
1046 AliError("Missing GRP or bad SOR/EOR time-stamps! Switching off the time-stamp generation from GRP!");
1047 fTimeStart = fTimeEnd = 0;
1048 fUseTimeStampFromCDB = kFALSE;
1051 fTimeStart = grpObj->GetTimeStart();
1052 fTimeEnd = grpObj->GetTimeEnd();
1056 if(AliCDBManager::Instance()->GetRun() >= 0) {
1057 AliRunLoader::Instance()->SetRunNumber(AliCDBManager::Instance()->GetRun());
1058 AliRunLoader::Instance()->SetNumberOfEventsPerRun(fNEvents);
1060 AliWarning("Run number not initialized!!");
1063 AliRunLoader::Instance()->CdGAFile();
1066 AliPDG::AddParticlesToPdgDataBase();
1068 gMC->SetMagField(TGeoGlobalMagField::Instance()->GetField());
1069 AliSysInfo::AddStamp("RunSimulation_GetField");
1071 gAlice->GetMCApp()->Init();
1072 AliSysInfo::AddStamp("RunSimulation_InitMCApp");
1074 //Must be here because some MCs (G4) adds detectors here and not in Config.C
1075 gAlice->InitLoaders();
1076 AliRunLoader::Instance()->MakeTree("E");
1077 AliRunLoader::Instance()->LoadKinematics("RECREATE");
1078 AliRunLoader::Instance()->LoadTrackRefs("RECREATE");
1079 AliRunLoader::Instance()->LoadHits("all","RECREATE");
1081 // Save stuff at the beginning of the file to avoid file corruption
1082 AliRunLoader::Instance()->CdGAFile();
1084 gAlice->SetEventNrInRun(-1); //important - we start Begin event from increasing current number in run
1085 AliSysInfo::AddStamp("RunSimulation_InitLoaders");
1086 //___________________________________________________________________________________________
1088 AliSysInfo::AddStamp("RunSimulation_TriggerDescriptor");
1090 // Set run number in CDBManager
1091 AliInfo(Form("Run number: %d",AliCDBManager::Instance()->GetRun()));
1093 AliRunLoader* runLoader = AliRunLoader::Instance();
1095 AliError(Form("gAlice has no run loader object. "
1096 "Check your config file: %s", fConfigFileName.Data()));
1099 SetGAliceFile(runLoader->GetFileName());
1101 // Misalign geometry
1102 #if ROOT_VERSION_CODE < 331527
1103 AliGeomManager::SetGeometry(gGeoManager);
1105 // Check that the consistency of symbolic names for the activated subdetectors
1106 // in the geometry loaded by AliGeomManager
1107 TString detsToBeChecked = "";
1108 TObjArray* detArray = runLoader->GetAliRun()->Detectors();
1109 for (Int_t iDet = 0; iDet < detArray->GetEntriesFast(); iDet++) {
1110 AliModule* det = (AliModule*) detArray->At(iDet);
1111 if (!det || !det->IsActive()) continue;
1112 detsToBeChecked += det->GetName();
1113 detsToBeChecked += " ";
1114 } // end loop over detectors
1115 if(!AliGeomManager::CheckSymNamesLUT(detsToBeChecked.Data()))
1116 AliFatalClass("Current loaded geometry differs in the definition of symbolic names!");
1117 MisalignGeometry(runLoader);
1118 AliSysInfo::AddStamp("RunSimulation_MisalignGeometry");
1121 // AliRunLoader* runLoader = AliRunLoader::Instance();
1122 // if (!runLoader) {
1123 // AliError(Form("gAlice has no run loader object. "
1124 // "Check your config file: %s", fConfigFileName.Data()));
1127 // SetGAliceFile(runLoader->GetFileName());
1129 if (!gAlice->GetMCApp()->Generator()) {
1130 AliError(Form("gAlice has no generator object. "
1131 "Check your config file: %s", fConfigFileName.Data()));
1135 // Write GRP entry corresponding to the setting found in Cofig.C
1138 AliSysInfo::AddStamp("RunSimulation_WriteGRP");
1140 if (nEvents <= 0) nEvents = fNEvents;
1142 // get vertex from background file in case of merging
1143 if (fUseBkgrdVertex &&
1144 fBkgrdFileNames && (fBkgrdFileNames->GetEntriesFast() > 0)) {
1145 Int_t signalPerBkgrd = GetNSignalPerBkgrd(nEvents);
1146 const char* fileName = ((TObjString*)
1147 (fBkgrdFileNames->At(0)))->GetName();
1148 AliInfo(Form("The vertex will be taken from the background "
1149 "file %s with nSignalPerBackground = %d",
1150 fileName, signalPerBkgrd));
1151 AliVertexGenFile* vtxGen = new AliVertexGenFile(fileName, signalPerBkgrd);
1152 gAlice->GetMCApp()->Generator()->SetVertexGenerator(vtxGen);
1155 if (!fRunSimulation) {
1156 gAlice->GetMCApp()->Generator()->SetTrackingFlag(0);
1159 // set the number of events per file for given detectors and data types
1160 for (Int_t i = 0; i < fEventsPerFile.GetEntriesFast(); i++) {
1161 if (!fEventsPerFile[i]) continue;
1162 const char* detName = fEventsPerFile[i]->GetName();
1163 const char* typeName = fEventsPerFile[i]->GetTitle();
1164 TString loaderName(detName);
1165 loaderName += "Loader";
1166 AliLoader* loader = runLoader->GetLoader(loaderName);
1168 AliError(Form("RunSimulation no loader for %s found\n Number of events per file not set for %s %s",
1169 detName, typeName, detName));
1172 AliDataLoader* dataLoader =
1173 loader->GetDataLoader(typeName);
1175 AliError(Form("no data loader for %s found\n"
1176 "Number of events per file not set for %s %s",
1177 typeName, detName, typeName));
1180 dataLoader->SetNumberOfEventsPerFile(fEventsPerFile[i]->GetUniqueID());
1181 AliDebug(1, Form("number of events per file set to %d for %s %s",
1182 fEventsPerFile[i]->GetUniqueID(), detName, typeName));
1185 AliInfo("running gAlice");
1186 AliSysInfo::AddStamp("Start_ProcessRun");
1188 // Create the Root Tree with one branch per detector
1189 //Hits moved to begin event -> now we are crating separate tree for each event
1191 gMC->ProcessRun(nEvents);
1193 // End of this run, close files
1194 if(nEvents>0) FinishRun();
1196 AliSysInfo::AddStamp("Stop_ProcessRun");
1202 //_____________________________________________________________________________
1203 Bool_t AliSimulation::RunSDigitization(const char* detectors)
1205 // run the digitization and produce summable digits
1206 static Int_t eventNr=0;
1207 AliCodeTimerAuto("",0) ;
1209 // initialize CDB storage, run number, set CDB lock
1211 if (!SetRunNumberFromData()) if (fStopOnError) return kFALSE;
1214 AliRunLoader* runLoader = LoadRun();
1215 if (!runLoader) return kFALSE;
1217 TString detStr = detectors;
1218 TObjArray* detArray = runLoader->GetAliRun()->Detectors();
1219 for (Int_t iDet = 0; iDet < detArray->GetEntriesFast(); iDet++) {
1220 AliModule* det = (AliModule*) detArray->At(iDet);
1221 if (!det || !det->IsActive()) continue;
1222 if (IsSelected(det->GetName(), detStr)) {
1223 AliInfo(Form("creating summable digits for %s", det->GetName()));
1224 AliCodeTimerStart(Form("creating summable digits for %s", det->GetName()));
1225 det->Hits2SDigits();
1226 AliCodeTimerStop(Form("creating summable digits for %s", det->GetName()));
1227 AliSysInfo::AddStamp(Form("Digit_%s_%d",det->GetName(),eventNr), 0,1, eventNr);
1231 if ((detStr.CompareTo("ALL") != 0) && !detStr.IsNull()) {
1232 AliError(Form("the following detectors were not found: %s",
1234 if (fStopOnError) return kFALSE;
1243 //_____________________________________________________________________________
1244 Bool_t AliSimulation::RunDigitization(const char* detectors,
1245 const char* excludeDetectors)
1247 // run the digitization and produce digits from sdigits
1249 AliCodeTimerAuto("",0)
1251 // initialize CDB storage, run number, set CDB lock
1253 if (!SetRunNumberFromData()) if (fStopOnError) return kFALSE;
1256 delete AliRunLoader::Instance();
1261 if (fBkgrdFileNames) nStreams = fBkgrdFileNames->GetEntriesFast() + 1;
1262 Int_t signalPerBkgrd = GetNSignalPerBkgrd();
1263 AliRunDigitizer* manager = new AliRunDigitizer(nStreams, signalPerBkgrd);
1264 // manager->SetEmbeddingFlag(fEmbeddingFlag);
1265 manager->SetInputStream(0, fGAliceFileName.Data());
1266 for (Int_t iStream = 1; iStream < nStreams; iStream++) {
1267 const char* fileName = ((TObjString*)
1268 (fBkgrdFileNames->At(iStream-1)))->GetName();
1269 manager->SetInputStream(iStream, fileName);
1272 TString detStr = detectors;
1273 TString detExcl = excludeDetectors;
1274 manager->GetInputStream(0)->ImportgAlice();
1275 AliRunLoader* runLoader =
1276 AliRunLoader::GetRunLoader(manager->GetInputStream(0)->GetFolderName());
1277 TObjArray* detArray = runLoader->GetAliRun()->Detectors();
1278 for (Int_t iDet = 0; iDet < detArray->GetEntriesFast(); iDet++) {
1279 AliModule* det = (AliModule*) detArray->At(iDet);
1280 if (!det || !det->IsActive()) continue;
1281 if (IsSelected(det->GetName(), detStr) &&
1282 !IsSelected(det->GetName(), detExcl)) {
1283 AliDigitizer* digitizer = det->CreateDigitizer(manager);
1286 AliError(Form("no digitizer for %s", det->GetName()));
1287 if (fStopOnError) return kFALSE;
1289 digitizer->SetRegionOfInterest(fRegionOfInterest);
1294 if ((detStr.CompareTo("ALL") != 0) && !detStr.IsNull()) {
1295 AliError(Form("the following detectors were not found: %s",
1297 if (fStopOnError) return kFALSE;
1300 if (!manager->GetListOfTasks()->IsEmpty()) {
1301 AliInfo("executing digitization");
1310 //_____________________________________________________________________________
1311 Bool_t AliSimulation::RunHitsDigitization(const char* detectors)
1313 // run the digitization and produce digits from hits
1315 AliCodeTimerAuto("",0)
1317 // initialize CDB storage, run number, set CDB lock
1319 if (!SetRunNumberFromData()) if (fStopOnError) return kFALSE;
1322 AliRunLoader* runLoader = LoadRun("READ");
1323 if (!runLoader) return kFALSE;
1325 TString detStr = detectors;
1326 TObjArray* detArray = runLoader->GetAliRun()->Detectors();
1327 for (Int_t iDet = 0; iDet < detArray->GetEntriesFast(); iDet++) {
1328 AliModule* det = (AliModule*) detArray->At(iDet);
1329 if (!det || !det->IsActive()) continue;
1330 if (IsSelected(det->GetName(), detStr)) {
1331 AliInfo(Form("creating digits from hits for %s", det->GetName()));
1336 if ((detStr.CompareTo("ALL") != 0) && !detStr.IsNull()) {
1337 AliError(Form("the following detectors were not found: %s",
1339 if (fStopOnError) return kFALSE;
1345 //_____________________________________________________________________________
1346 Bool_t AliSimulation::WriteRawData(const char* detectors,
1347 const char* fileName,
1348 Bool_t deleteIntermediateFiles,
1351 // convert the digits to raw data
1352 // First DDL raw data files for the given detectors are created.
1353 // If a file name is given, the DDL files are then converted to a DATE file.
1354 // If deleteIntermediateFiles is true, the DDL raw files are deleted
1356 // If the file name has the extension ".root", the DATE file is converted
1358 // If deleteIntermediateFiles is true, the DATE file is deleted afterwards.
1359 // 'selrawdata' flag can be used to enable writing of detectors raw data
1360 // accoring to the trigger cluster.
1362 AliCodeTimerAuto("",0)
1363 AliSysInfo::AddStamp("WriteRawData_Start");
1365 TString detStr = detectors;
1366 if (!WriteRawFiles(detStr.Data())) {
1367 if (fStopOnError) return kFALSE;
1369 AliSysInfo::AddStamp("WriteRawFiles");
1371 // run HLT simulation on simulated DDL raw files
1372 // and produce HLT ddl raw files to be included in date/root file
1373 // bugfix 2009-06-26: the decision whether to write HLT raw data
1374 // is taken in RunHLT. Here HLT always needs to be run in order to
1375 // create HLT digits, unless its switched off. This is due to the
1376 // special placement of the HLT between the generation of DDL files
1377 // and conversion to DATE/Root file.
1378 detStr.ReplaceAll("HLT", "");
1379 if (!fRunHLT.IsNull()) {
1381 if (fStopOnError) return kFALSE;
1384 AliSysInfo::AddStamp("WriteRawData_RunHLT");
1386 TString dateFileName(fileName);
1387 if (!dateFileName.IsNull()) {
1388 Bool_t rootOutput = dateFileName.EndsWith(".root");
1389 if (rootOutput) dateFileName += ".date";
1390 TString selDateFileName;
1392 selDateFileName = "selected.";
1393 selDateFileName+= dateFileName;
1395 if (!ConvertRawFilesToDate(dateFileName,selDateFileName)) {
1396 if (fStopOnError) return kFALSE;
1398 AliSysInfo::AddStamp("ConvertRawFilesToDate");
1399 if (deleteIntermediateFiles) {
1400 AliRunLoader* runLoader = LoadRun("READ");
1401 if (runLoader) for (Int_t iEvent = 0;
1402 iEvent < runLoader->GetNumberOfEvents(); iEvent++) {
1404 snprintf(command, 256, "rm -r raw%d", iEvent);
1405 gSystem->Exec(command);
1411 if (!ConvertDateToRoot(dateFileName, fileName)) {
1412 if (fStopOnError) return kFALSE;
1414 AliSysInfo::AddStamp("ConvertDateToRoot");
1415 if (deleteIntermediateFiles) {
1416 gSystem->Unlink(dateFileName);
1419 TString selFileName = "selected.";
1420 selFileName += fileName;
1421 if (!ConvertDateToRoot(selDateFileName, selFileName)) {
1422 if (fStopOnError) return kFALSE;
1424 if (deleteIntermediateFiles) {
1425 gSystem->Unlink(selDateFileName);
1434 //_____________________________________________________________________________
1435 Bool_t AliSimulation::WriteRawFiles(const char* detectors)
1437 // convert the digits to raw data DDL files
1439 AliCodeTimerAuto("",0)
1441 AliRunLoader* runLoader = LoadRun("READ");
1442 if (!runLoader) return kFALSE;
1444 // write raw data to DDL files
1445 for (Int_t iEvent = 0; iEvent < runLoader->GetNumberOfEvents(); iEvent++) {
1446 AliInfo(Form("processing event %d", iEvent));
1447 runLoader->GetEvent(iEvent);
1448 TString baseDir = gSystem->WorkingDirectory();
1450 snprintf(dirName, 256, "raw%d", iEvent);
1451 gSystem->MakeDirectory(dirName);
1452 if (!gSystem->ChangeDirectory(dirName)) {
1453 AliError(Form("couldn't change to directory %s", dirName));
1454 if (fStopOnError) return kFALSE; else continue;
1457 ofstream runNbFile(Form("run%u",runLoader->GetHeader()->GetRun()));
1460 TString detStr = detectors;
1461 if (IsSelected("HLT", detStr)) {
1462 // Do nothing. "HLT" will be removed from detStr and HLT raw
1463 // data files are generated in RunHLT.
1466 TObjArray* detArray = runLoader->GetAliRun()->Detectors();
1467 for (Int_t iDet = 0; iDet < detArray->GetEntriesFast(); iDet++) {
1468 AliModule* det = (AliModule*) detArray->At(iDet);
1469 if (!det || !det->IsActive()) continue;
1470 if (IsSelected(det->GetName(), detStr)) {
1471 AliInfo(Form("creating raw data from digits for %s", det->GetName()));
1476 if (!WriteTriggerRawData())
1477 if (fStopOnError) return kFALSE;
1479 gSystem->ChangeDirectory(baseDir);
1480 if ((detStr.CompareTo("ALL") != 0) && !detStr.IsNull()) {
1481 AliError(Form("the following detectors were not found: %s",
1483 if (fStopOnError) return kFALSE;
1492 //_____________________________________________________________________________
1493 Bool_t AliSimulation::ConvertRawFilesToDate(const char* dateFileName,
1494 const char* selDateFileName)
1496 // convert raw data DDL files to a DATE file with the program "dateStream"
1497 // The second argument is not empty when the user decides to write
1498 // the detectors raw data according to the trigger cluster.
1500 AliCodeTimerAuto("",0)
1502 char* path = gSystem->Which(gSystem->Getenv("PATH"), "dateStream");
1504 AliError("the program dateStream was not found");
1505 if (fStopOnError) return kFALSE;
1510 AliRunLoader* runLoader = LoadRun("READ");
1511 if (!runLoader) return kFALSE;
1513 AliInfo(Form("converting raw data DDL files to DATE file %s", dateFileName));
1514 Bool_t selrawdata = kFALSE;
1515 if (strcmp(selDateFileName,"") != 0) selrawdata = kTRUE;
1518 // Note the option -s. It is used in order to avoid
1519 // the generation of SOR/EOR events.
1520 snprintf(command, 256, "dateStream -c -s -D -o %s -# %d -C -run %d",
1521 dateFileName, runLoader->GetNumberOfEvents(),runLoader->GetHeader()->GetRun());
1522 FILE* pipe = gSystem->OpenPipe(command, "w");
1525 AliError(Form("Cannot execute command: %s",command));
1529 Int_t selEvents = 0;
1530 for (Int_t iEvent = 0; iEvent < runLoader->GetNumberOfEvents(); iEvent++) {
1532 UInt_t detectorPattern = 0;
1533 runLoader->GetEvent(iEvent);
1534 if (!runLoader->LoadTrigger()) {
1535 AliCentralTrigger *aCTP = runLoader->GetTrigger();
1536 detectorPattern = aCTP->GetClusterMask();
1537 // Check if the event was triggered by CTP
1539 if (aCTP->GetClassMask()) selEvents++;
1543 AliWarning("No trigger can be loaded! Some fields in the event header will be empty !");
1545 AliWarning("No trigger can be loaded! Writing of selected raw data is abandoned !");
1546 selrawdata = kFALSE;
1550 fprintf(pipe, "GDC DetectorPattern %u\n", detectorPattern);
1554 // loop over detectors and DDLs
1555 for (Int_t iDet = 0; iDet < AliDAQ::kNDetectors; iDet++) {
1556 for (Int_t iDDL = 0; iDDL < AliDAQ::NumberOfDdls(iDet); iDDL++) {
1558 Int_t ddlID = AliDAQ::DdlID(iDet,iDDL);
1559 Int_t ldcID = Int_t(ldc + 0.0001);
1560 ldc += AliDAQ::NumberOfLdcs(iDet) / AliDAQ::NumberOfDdls(iDet);
1562 char rawFileName[256];
1563 snprintf(rawFileName, 256, "raw%d/%s",
1564 iEvent, AliDAQ::DdlFileName(iDet,iDDL));
1566 // check existence and size of raw data file
1567 FILE* file = fopen(rawFileName, "rb");
1568 if (!file) continue;
1569 fseek(file, 0, SEEK_END);
1570 unsigned long size = ftell(file);
1572 if (!size) continue;
1574 if (ldcID != prevLDC) {
1575 fprintf(pipe, " LDC Id %d\n", ldcID);
1578 fprintf(pipe, " Equipment Id %d Payload %s\n", ddlID, rawFileName);
1583 Int_t result = gSystem->ClosePipe(pipe);
1585 if (!(selrawdata && selEvents > 0)) {
1587 return (result == 0);
1590 AliInfo(Form("converting selected by trigger cluster raw data DDL files to DATE file %s", selDateFileName));
1592 snprintf(command, 256, "dateStream -c -s -D -o %s -# %d -C -run %d",
1593 selDateFileName,selEvents,runLoader->GetHeader()->GetRun());
1594 FILE* pipe2 = gSystem->OpenPipe(command, "w");
1596 for (Int_t iEvent = 0; iEvent < runLoader->GetNumberOfEvents(); iEvent++) {
1598 // Get the trigger decision and cluster
1599 UInt_t detectorPattern = 0;
1601 runLoader->GetEvent(iEvent);
1602 if (!runLoader->LoadTrigger()) {
1603 AliCentralTrigger *aCTP = runLoader->GetTrigger();
1604 if (aCTP->GetClassMask() == 0) continue;
1605 detectorPattern = aCTP->GetClusterMask();
1606 detClust = AliDAQ::ListOfTriggeredDetectors(detectorPattern);
1607 AliInfo(Form("List of detectors to be read out: %s",detClust.Data()));
1610 fprintf(pipe2, "GDC DetectorPattern %u\n", detectorPattern);
1614 // loop over detectors and DDLs
1615 for (Int_t iDet = 0; iDet < AliDAQ::kNDetectors; iDet++) {
1616 // Write only raw data from detectors that
1617 // are contained in the trigger cluster(s)
1618 if (!IsSelected(AliDAQ::DetectorName(iDet),detClust)) continue;
1620 for (Int_t iDDL = 0; iDDL < AliDAQ::NumberOfDdls(iDet); iDDL++) {
1622 Int_t ddlID = AliDAQ::DdlID(iDet,iDDL);
1623 Int_t ldcID = Int_t(ldc + 0.0001);
1624 ldc += AliDAQ::NumberOfLdcs(iDet) / AliDAQ::NumberOfDdls(iDet);
1626 char rawFileName[256];
1627 snprintf(rawFileName, 256, "raw%d/%s",
1628 iEvent, AliDAQ::DdlFileName(iDet,iDDL));
1630 // check existence and size of raw data file
1631 FILE* file = fopen(rawFileName, "rb");
1632 if (!file) continue;
1633 fseek(file, 0, SEEK_END);
1634 unsigned long size = ftell(file);
1636 if (!size) continue;
1638 if (ldcID != prevLDC) {
1639 fprintf(pipe2, " LDC Id %d\n", ldcID);
1642 fprintf(pipe2, " Equipment Id %d Payload %s\n", ddlID, rawFileName);
1647 Int_t result2 = gSystem->ClosePipe(pipe2);
1650 return ((result == 0) && (result2 == 0));
1653 //_____________________________________________________________________________
1654 Bool_t AliSimulation::ConvertDateToRoot(const char* dateFileName,
1655 const char* rootFileName)
1657 // convert a DATE file to a root file with the program "alimdc"
1660 const Int_t kDBSize = 2000000000;
1661 const Int_t kTagDBSize = 1000000000;
1662 const Bool_t kFilter = kFALSE;
1663 const Int_t kCompression = 1;
1665 char* path = gSystem->Which(gSystem->Getenv("PATH"), "alimdc");
1667 AliError("the program alimdc was not found");
1668 if (fStopOnError) return kFALSE;
1673 AliInfo(Form("converting DATE file %s to root file %s",
1674 dateFileName, rootFileName));
1676 const char* rawDBFS[2] = { "/tmp/mdc1", "/tmp/mdc2" };
1677 const char* tagDBFS = "/tmp/mdc1/tags";
1679 // User defined file system locations
1680 if (gSystem->Getenv("ALIMDC_RAWDB1"))
1681 rawDBFS[0] = gSystem->Getenv("ALIMDC_RAWDB1");
1682 if (gSystem->Getenv("ALIMDC_RAWDB2"))
1683 rawDBFS[1] = gSystem->Getenv("ALIMDC_RAWDB2");
1684 if (gSystem->Getenv("ALIMDC_TAGDB"))
1685 tagDBFS = gSystem->Getenv("ALIMDC_TAGDB");
1687 gSystem->Exec(Form("rm -rf %s",rawDBFS[0]));
1688 gSystem->Exec(Form("rm -rf %s",rawDBFS[1]));
1689 gSystem->Exec(Form("rm -rf %s",tagDBFS));
1691 gSystem->Exec(Form("mkdir %s",rawDBFS[0]));
1692 gSystem->Exec(Form("mkdir %s",rawDBFS[1]));
1693 gSystem->Exec(Form("mkdir %s",tagDBFS));
1695 Int_t result = gSystem->Exec(Form("alimdc %d %d %d %d %s",
1696 kDBSize, kTagDBSize, kFilter, kCompression, dateFileName));
1697 gSystem->Exec(Form("mv %s/*.root %s", rawDBFS[0], rootFileName));
1699 gSystem->Exec(Form("rm -rf %s",rawDBFS[0]));
1700 gSystem->Exec(Form("rm -rf %s",rawDBFS[1]));
1701 gSystem->Exec(Form("rm -rf %s",tagDBFS));
1703 return (result == 0);
1707 //_____________________________________________________________________________
1708 AliRunLoader* AliSimulation::LoadRun(const char* mode) const
1710 // delete existing run loaders, open a new one and load gAlice
1712 delete AliRunLoader::Instance();
1713 AliRunLoader* runLoader =
1714 AliRunLoader::Open(fGAliceFileName.Data(),
1715 AliConfig::GetDefaultEventFolderName(), mode);
1717 AliError(Form("no run loader found in file %s", fGAliceFileName.Data()));
1720 runLoader->LoadgAlice();
1721 runLoader->LoadHeader();
1722 gAlice = runLoader->GetAliRun();
1724 AliError(Form("no gAlice object found in file %s",
1725 fGAliceFileName.Data()));
1731 //_____________________________________________________________________________
1732 Int_t AliSimulation::GetNSignalPerBkgrd(Int_t nEvents) const
1734 // get or calculate the number of signal events per background event
1736 if (!fBkgrdFileNames) return 1;
1737 Int_t nBkgrdFiles = fBkgrdFileNames->GetEntriesFast();
1738 if (nBkgrdFiles == 0) return 1;
1740 // get the number of signal events
1742 AliRunLoader* runLoader =
1743 AliRunLoader::Open(fGAliceFileName.Data(), "SIGNAL");
1744 if (!runLoader) return 1;
1746 nEvents = runLoader->GetNumberOfEvents();
1751 for (Int_t iBkgrdFile = 0; iBkgrdFile < nBkgrdFiles; iBkgrdFile++) {
1752 // get the number of background events
1753 const char* fileName = ((TObjString*)
1754 (fBkgrdFileNames->At(iBkgrdFile)))->GetName();
1755 AliRunLoader* runLoader =
1756 AliRunLoader::Open(fileName, "BKGRD");
1757 if (!runLoader) continue;
1758 Int_t nBkgrdEvents = runLoader->GetNumberOfEvents();
1761 // get or calculate the number of signal per background events
1762 Int_t nSignalPerBkgrd = fBkgrdFileNames->At(iBkgrdFile)->GetUniqueID();
1763 if (nSignalPerBkgrd <= 0) {
1764 nSignalPerBkgrd = (nEvents-1) / nBkgrdEvents + 1;
1765 } else if (result && (result != nSignalPerBkgrd)) {
1766 AliInfo(Form("the number of signal events per background event "
1767 "will be changed from %d to %d for stream %d",
1768 nSignalPerBkgrd, result, iBkgrdFile+1));
1769 nSignalPerBkgrd = result;
1772 if (!result) result = nSignalPerBkgrd;
1773 if (nSignalPerBkgrd * nBkgrdEvents < nEvents) {
1774 AliWarning(Form("not enough background events (%d) for %d signal events "
1775 "using %d signal per background events for stream %d",
1776 nBkgrdEvents, nEvents, nSignalPerBkgrd, iBkgrdFile+1));
1783 //_____________________________________________________________________________
1784 Bool_t AliSimulation::IsSelected(TString detName, TString& detectors) const
1786 // check whether detName is contained in detectors
1787 // if yes, it is removed from detectors
1789 // check if all detectors are selected
1790 if ((detectors.CompareTo("ALL") == 0) ||
1791 detectors.BeginsWith("ALL ") ||
1792 detectors.EndsWith(" ALL") ||
1793 detectors.Contains(" ALL ")) {
1798 // search for the given detector
1799 Bool_t result = kFALSE;
1800 if ((detectors.CompareTo(detName) == 0) ||
1801 detectors.BeginsWith(detName+" ") ||
1802 detectors.EndsWith(" "+detName) ||
1803 detectors.Contains(" "+detName+" ")) {
1804 detectors.ReplaceAll(detName, "");
1808 // clean up the detectors string
1809 while (detectors.Contains(" ")) detectors.ReplaceAll(" ", " ");
1810 while (detectors.BeginsWith(" ")) detectors.Remove(0, 1);
1811 while (detectors.EndsWith(" ")) detectors.Remove(detectors.Length()-1, 1);
1816 //_____________________________________________________________________________
1817 Bool_t AliSimulation::ConvertRaw2SDigits(const char* rawDirectory, const char* esdFileName, Int_t N)
1820 // Steering routine to convert raw data in directory rawDirectory/ to fake SDigits.
1821 // These can be used for embedding of MC tracks into RAW data using the standard
1822 // merging procedure.
1824 // If an ESD file is given the reconstructed vertex is taken from it and stored in the event header.
1827 AliError("no gAlice object. Restart aliroot and try again.");
1830 if (gAlice->Modules()->GetEntries() > 0) {
1831 AliError("gAlice was already run. Restart aliroot and try again.");
1835 AliInfo(Form("initializing gAlice with config file %s",fConfigFileName.Data()));
1839 gROOT->LoadMacro(fConfigFileName.Data());
1840 gInterpreter->ProcessLine(gAlice->GetConfigFunction());
1842 if(AliCDBManager::Instance()->GetRun() >= 0) {
1843 SetRunNumber(AliCDBManager::Instance()->GetRun());
1845 AliWarning("Run number not initialized!!");
1848 AliRunLoader::Instance()->CdGAFile();
1850 AliPDG::AddParticlesToPdgDataBase();
1852 gMC->SetMagField(TGeoGlobalMagField::Instance()->GetField());
1854 gAlice->GetMCApp()->Init();
1856 //Must be here because some MCs (G4) adds detectors here and not in Config.C
1857 gAlice->InitLoaders();
1858 AliRunLoader::Instance()->MakeTree("E");
1859 AliRunLoader::Instance()->LoadKinematics("RECREATE");
1860 AliRunLoader::Instance()->LoadTrackRefs("RECREATE");
1861 AliRunLoader::Instance()->LoadHits("all","RECREATE");
1864 // Save stuff at the beginning of the file to avoid file corruption
1865 AliRunLoader::Instance()->CdGAFile();
1870 //AliCDBManager* man = AliCDBManager::Instance();
1871 //man->SetRun(0); // Should this come from rawdata header ?
1875 // Get the runloader
1876 AliRunLoader* runLoader = AliRunLoader::Instance();
1878 // Open esd file if available
1881 AliESDEvent* esd = 0;
1882 if (esdFileName && (strlen(esdFileName)>0)) {
1883 esdFile = TFile::Open(esdFileName);
1885 esd = new AliESDEvent();
1886 esdFile->GetObject("esdTree", treeESD);
1887 if (treeESD) esd->ReadFromTree(treeESD);
1892 // Create the RawReader
1893 TString fileName(rawDirectory);
1894 AliRawReader* rawReader = 0x0;
1895 if (fileName.EndsWith("/")) {
1896 rawReader = new AliRawReaderFile(fileName);
1897 } else if (fileName.EndsWith(".root")) {
1898 rawReader = new AliRawReaderRoot(fileName);
1899 } else if (!fileName.IsNull()) {
1900 rawReader = new AliRawReaderDate(fileName);
1902 if (!rawReader) return (kFALSE);
1904 // if (!fEquipIdMap.IsNull() && fRawReader)
1905 // fRawReader->LoadEquipmentIdsMap(fEquipIdMap);
1907 // Get list of detectors
1908 TObjArray* detArray = runLoader->GetAliRun()->Detectors();
1911 AliHeader* header = runLoader->GetHeader();
1915 if (!(rawReader->NextEvent())) break;
1916 runLoader->SetEventNumber(nev);
1917 runLoader->GetHeader()->Reset(rawReader->GetRunNumber(),
1919 runLoader->GetEvent(nev);
1920 AliInfo(Form("We are at event %d",nev));
1923 TString detStr = fMakeSDigits;
1924 for (iDet = 0; iDet < detArray->GetEntriesFast(); iDet++) {
1925 AliModule* det = (AliModule*) detArray->At(iDet);
1926 if (!det || !det->IsActive()) continue;
1927 if (IsSelected(det->GetName(), detStr)) {
1928 AliInfo(Form("Calling Raw2SDigits for %s", det->GetName()));
1929 det->Raw2SDigits(rawReader);
1936 // If ESD information available obtain reconstructed vertex and store in header.
1938 treeESD->GetEvent(nev);
1939 const AliESDVertex* esdVertex = esd->GetPrimaryVertex();
1940 Double_t position[3];
1941 esdVertex->GetXYZ(position);
1942 AliGenEventHeader* mcHeader = new AliGenEventHeader("ESD");
1945 for (Int_t i = 0; i < 3; i++) mcV[i] = position[i];
1946 mcHeader->SetPrimaryVertex(mcV);
1947 header->Reset(0,nev);
1948 header->SetGenEventHeader(mcHeader);
1949 AliInfo(Form("***** Saved vertex %f %f %f \n", position[0], position[1], position[2]));
1953 runLoader->TreeE()->Fill();
1954 AliInfo(Form("Finished event %d",nev));
1963 runLoader->CdGAFile();
1964 runLoader->WriteHeader("OVERWRITE");
1965 runLoader->WriteRunLoader();
1970 //_____________________________________________________________________________
1971 void AliSimulation::FinishRun()
1974 // Called at the end of the run.
1979 AliDebug(1, "Finish Lego");
1980 AliRunLoader::Instance()->CdGAFile();
1984 // Clean detector information
1985 TIter next(gAlice->Modules());
1986 AliModule *detector;
1987 while((detector = dynamic_cast<AliModule*>(next()))) {
1988 AliDebug(2, Form("%s->FinishRun()", detector->GetName()));
1989 detector->FinishRun();
1992 AliDebug(1, "AliRunLoader::Instance()->WriteHeader(OVERWRITE)");
1993 AliRunLoader::Instance()->WriteHeader("OVERWRITE");
1995 // Write AliRun info and all detectors parameters
1996 AliRunLoader::Instance()->CdGAFile();
1997 gAlice->Write(0,TObject::kOverwrite);//write AliRun
1998 AliRunLoader::Instance()->Write(0,TObject::kOverwrite);//write RunLoader itself
2000 if(gAlice->GetMCApp()) gAlice->GetMCApp()->FinishRun();
2001 AliRunLoader::Instance()->Synchronize();
2004 //_____________________________________________________________________________
2005 Int_t AliSimulation::GetDetIndex(const char* detector)
2007 // return the detector index corresponding to detector
2009 for (index = 0; index < fgkNDetectors ; index++) {
2010 if ( strcmp(detector, fgkDetectorName[index]) == 0 )
2016 //_____________________________________________________________________________
2017 Bool_t AliSimulation::CreateHLT()
2019 // Init the HLT simulation.
2020 // The function loads the library and creates the instance of AliHLTSimulation.
2021 // the main reason for the decoupled creation is to set the transient OCDB
2022 // objects before the OCDB is locked
2024 // load the library dynamically
2025 gSystem->Load(ALIHLTSIMULATION_LIBRARY);
2027 // check for the library version
2028 AliHLTSimulationGetLibraryVersion_t fctVersion=(AliHLTSimulationGetLibraryVersion_t)(gSystem->DynFindSymbol(ALIHLTSIMULATION_LIBRARY, ALIHLTSIMULATION_GET_LIBRARY_VERSION));
2030 AliError(Form("can not load library %s", ALIHLTSIMULATION_LIBRARY));
2033 if (fctVersion()!= ALIHLTSIMULATION_LIBRARY_VERSION) {
2034 AliWarning(Form("%s version does not match: compiled for version %d, loaded %d", ALIHLTSIMULATION_LIBRARY, ALIHLTSIMULATION_LIBRARY_VERSION, fctVersion()));
2037 // print compile info
2038 typedef void (*CompileInfo)( const char*& date, const char*& time);
2039 CompileInfo fctInfo=(CompileInfo)gSystem->DynFindSymbol(ALIHLTSIMULATION_LIBRARY, "CompileInfo");
2041 const char* date="";
2042 const char* time="";
2043 (*fctInfo)(date, time);
2044 if (!date) date="unknown";
2045 if (!time) time="unknown";
2046 AliInfo(Form("%s build on %s (%s)", ALIHLTSIMULATION_LIBRARY, date, time));
2048 AliInfo(Form("no build info available for %s", ALIHLTSIMULATION_LIBRARY));
2051 // create instance of the HLT simulation
2052 AliHLTSimulationCreateInstance_t fctCreate=(AliHLTSimulationCreateInstance_t)(gSystem->DynFindSymbol(ALIHLTSIMULATION_LIBRARY, ALIHLTSIMULATION_CREATE_INSTANCE));
2053 if (fctCreate==NULL || (fpHLT=(fctCreate()))==NULL) {
2054 AliError(Form("can not create instance of HLT simulation (creator %p)", fctCreate));
2058 TString specObjects;
2059 for (Int_t i = 0; i < fSpecCDBUri.GetEntriesFast(); i++) {
2060 if (specObjects.Length()>0) specObjects+=" ";
2061 specObjects+=fSpecCDBUri[i]->GetName();
2064 AliHLTSimulationSetup_t fctSetup=(AliHLTSimulationSetup_t)(gSystem->DynFindSymbol(ALIHLTSIMULATION_LIBRARY, ALIHLTSIMULATION_SETUP));
2065 if (fctSetup==NULL || fctSetup(fpHLT, this, specObjects.Data())<0) {
2066 AliWarning(Form("failed to setup HLT simulation (function %p)", fctSetup));
2072 //_____________________________________________________________________________
2073 Bool_t AliSimulation::RunHLT()
2075 // Run the HLT simulation
2076 // HLT simulation is implemented in HLT/sim/AliHLTSimulation
2077 // Disabled if fRunHLT is empty, default vaule is "default".
2078 // AliSimulation::SetRunHLT can be used to set the options for HLT simulation
2079 // The default simulation depends on the HLT component libraries and their
2080 // corresponding agents which define components and chains to run. See
2081 // http://web.ift.uib.no/~kjeks/doc/alice-hlt-current/
2082 // http://web.ift.uib.no/~kjeks/doc/alice-hlt-current/classAliHLTModuleAgent.html
2084 // The libraries to be loaded can be specified as an option.
2086 // AliSimulation sim;
2087 // sim.SetRunHLT("libAliHLTSample.so");
2089 // will only load <tt>libAliHLTSample.so</tt>
2091 // Other available options:
2092 // \li loglevel=<i>level</i> <br>
2093 // logging level for this processing
2095 // disable redirection of log messages to AliLog class
2096 // \li config=<i>macro</i>
2097 // configuration macro
2098 // \li chains=<i>configuration</i>
2099 // comma separated list of configurations to be run during simulation
2100 // \li rawfile=<i>file</i>
2101 // source for the RawReader to be created, the default is <i>./</i> if
2102 // raw data is simulated
2106 if (!fpHLT && !CreateHLT()) {
2109 AliHLTSimulation* pHLT=fpHLT;
2111 AliRunLoader* pRunLoader = LoadRun("READ");
2112 if (!pRunLoader) return kFALSE;
2114 // initialize CDB storage, run number, set CDB lock
2115 // thats for the case of running HLT simulation without all the other steps
2116 // multiple calls are handled by the function, so we can just call
2118 if (!SetRunNumberFromData()) if (fStopOnError) return kFALSE;
2121 // init the HLT simulation
2123 if (fRunHLT.CompareTo("default")!=0) options=fRunHLT;
2124 TString detStr = fWriteRawData;
2125 if (!IsSelected("HLT", detStr)) {
2126 options+=" writerawfiles=";
2128 options+=" writerawfiles=HLT";
2131 if (!detStr.IsNull() && !options.Contains("rawfile=")) {
2132 // as a matter of fact, HLT will run reconstruction and needs the RawReader
2133 // in order to get detector data. By default, RawReaderFile is used to read
2134 // the already simulated ddl files. Date and Root files from the raw data
2135 // are generated after the HLT simulation.
2136 options+=" rawfile=./";
2139 AliHLTSimulationInit_t fctInit=(AliHLTSimulationInit_t)(gSystem->DynFindSymbol(ALIHLTSIMULATION_LIBRARY, ALIHLTSIMULATION_INIT));
2140 if (fctInit==NULL || (iResult=(fctInit(pHLT, pRunLoader, options.Data())))<0) {
2141 AliError(Form("can not init HLT simulation: error %d (init %p)", iResult, fctInit));
2143 // run the HLT simulation
2144 AliHLTSimulationRun_t fctRun=(AliHLTSimulationRun_t)(gSystem->DynFindSymbol(ALIHLTSIMULATION_LIBRARY, ALIHLTSIMULATION_RUN));
2145 if (fctRun==NULL || (iResult=(fctRun(pHLT, pRunLoader)))<0) {
2146 AliError(Form("can not run HLT simulation: error %d (run %p)", iResult, fctRun));
2150 // delete the instance
2151 AliHLTSimulationDeleteInstance_t fctDelete=(AliHLTSimulationDeleteInstance_t)(gSystem->DynFindSymbol(ALIHLTSIMULATION_LIBRARY, ALIHLTSIMULATION_DELETE_INSTANCE));
2152 if (fctDelete==NULL || fctDelete(pHLT)<0) {
2153 AliError(Form("can not delete instance of HLT simulation (creator %p)", fctDelete));
2157 return iResult>=0?kTRUE:kFALSE;
2160 //_____________________________________________________________________________
2161 Bool_t AliSimulation::RunQA()
2163 // run the QA on summable hits, digits or digits
2165 //if(!gAlice) return kFALSE;
2166 AliQAManager::QAManager()->SetRunLoader(AliRunLoader::Instance()) ;
2168 TString detectorsw("") ;
2170 AliQAManager::QAManager()->SetEventSpecie(fEventSpecie) ;
2171 detectorsw = AliQAManager::QAManager()->Run(fQADetectors.Data()) ;
2172 if ( detectorsw.IsNull() )
2177 //_____________________________________________________________________________
2178 Bool_t AliSimulation::SetRunQA(TString detAndAction)
2180 // Allows to run QA for a selected set of detectors
2181 // and a selected set of tasks among HITS, SDIGITS and DIGITS
2182 // all selected detectors run the same selected tasks
2184 if (!detAndAction.Contains(":")) {
2185 AliError( Form("%s is a wrong syntax, use \"DetectorList:ActionList\" \n", detAndAction.Data()) ) ;
2189 Int_t colon = detAndAction.Index(":") ;
2190 fQADetectors = detAndAction(0, colon) ;
2191 if (fQADetectors.Contains("ALL") ){
2192 TString tmp = Form("%s %s", fMakeDigits.Data(), fMakeDigitsFromHits.Data()) ;
2193 Int_t minus = fQADetectors.Last('-') ;
2194 TString toKeep = Form("%s %s", fMakeDigits.Data(), fMakeDigitsFromHits.Data()) ;
2195 TString toRemove("") ;
2196 while (minus >= 0) {
2197 toRemove = fQADetectors(minus+1, fQADetectors.Length()) ;
2198 toRemove = toRemove.Strip() ;
2199 toKeep.ReplaceAll(toRemove, "") ;
2200 fQADetectors.ReplaceAll(Form("-%s", toRemove.Data()), "") ;
2201 minus = fQADetectors.Last('-') ;
2203 fQADetectors = toKeep ;
2205 fQATasks = detAndAction(colon+1, detAndAction.Sizeof() ) ;
2206 if (fQATasks.Contains("ALL") ) {
2207 fQATasks = Form("%d %d %d", AliQAv1::kHITS, AliQAv1::kSDIGITS, AliQAv1::kDIGITS) ;
2209 fQATasks.ToUpper() ;
2211 if ( fQATasks.Contains("HIT") )
2212 tempo = Form("%d ", AliQAv1::kHITS) ;
2213 if ( fQATasks.Contains("SDIGIT") )
2214 tempo += Form("%d ", AliQAv1::kSDIGITS) ;
2215 if ( fQATasks.Contains("DIGIT") )
2216 tempo += Form("%d ", AliQAv1::kDIGITS) ;
2218 if (fQATasks.IsNull()) {
2219 AliInfo("No QA requested\n") ;
2224 TString tempo(fQATasks) ;
2225 tempo.ReplaceAll(Form("%d", AliQAv1::kHITS), AliQAv1::GetTaskName(AliQAv1::kHITS)) ;
2226 tempo.ReplaceAll(Form("%d", AliQAv1::kSDIGITS), AliQAv1::GetTaskName(AliQAv1::kSDIGITS)) ;
2227 tempo.ReplaceAll(Form("%d", AliQAv1::kDIGITS), AliQAv1::GetTaskName(AliQAv1::kDIGITS)) ;
2228 AliInfo( Form("QA will be done on \"%s\" for \"%s\"\n", fQADetectors.Data(), tempo.Data()) ) ;
2230 AliQAManager::QAManager()->SetActiveDetectors(fQADetectors) ;
2231 AliQAManager::QAManager()->SetTasks(fQATasks) ;
2232 for (Int_t det = 0 ; det < AliQAv1::kNDET ; det++)
2233 AliQAManager::QAManager()->SetWriteExpert(AliQAv1::DETECTORINDEX_t(det)) ;
2238 //_____________________________________________________________________________
2239 void AliSimulation::ProcessEnvironmentVars()
2241 // Extract run number and random generator seed from env variables
2243 AliInfo("Processing environment variables");
2245 // Random Number seed
2247 // first check that seed is not already set
2249 if (gSystem->Getenv("CONFIG_SEED")) {
2250 fSeed = atoi(gSystem->Getenv("CONFIG_SEED"));
2253 if (gSystem->Getenv("CONFIG_SEED")) {
2254 AliInfo(Form("Seed for random number generation already set (%d)"
2255 ": CONFIG_SEED variable ignored!", fSeed));
2259 AliInfo(Form("Seed for random number generation = %d ", fSeed));
2263 // first check that run number is not already set
2265 if (gSystem->Getenv("DC_RUN")) {
2266 fRun = atoi(gSystem->Getenv("DC_RUN"));
2269 if (gSystem->Getenv("DC_RUN")) {
2270 AliInfo(Form("Run number already set (%d): DC_RUN variable ignored!", fRun));
2274 AliInfo(Form("Run number = %d", fRun));
2277 //---------------------------------------------------------------------
2278 void AliSimulation::WriteGRPEntry()
2280 // Get the necessary information from galice (generator, trigger etc) and
2281 // write a GRP entry corresponding to the settings in the Config.C used
2282 // note that Hall probes and Cavern and Surface Atmos pressures are not simulated.
2285 AliInfo("Writing global run parameters entry into the OCDB");
2287 AliGRPObject* grpObj = new AliGRPObject();
2289 grpObj->SetRunType("PHYSICS");
2290 grpObj->SetTimeStart(fTimeStart);
2291 grpObj->SetTimeEnd(fTimeEnd);
2292 grpObj->SetBeamEnergyIsSqrtSHalfGeV(); // new format of GRP: store sqrt(s)/2 in GeV
2294 const AliGenerator *gen = gAlice->GetMCApp()->Generator();
2300 gen->GetProjectile(projectile,a,z);
2302 gen->GetTarget(target,a,z);
2303 TString beamType = projectile + "-" + target;
2304 beamType.ReplaceAll(" ","");
2305 if (!beamType.CompareTo("-")) {
2306 grpObj->SetBeamType("UNKNOWN");
2307 grpObj->SetBeamEnergy(gen->GetEnergyCMS()/2);
2310 grpObj->SetBeamType(beamType);
2312 grpObj->SetBeamEnergy(gen->GetEnergyCMS()/2 * a / z);
2314 grpObj->SetBeamEnergy(gen->GetEnergyCMS()/2 );
2316 // Heavy ion run, the event specie is set to kHighMult
2317 fEventSpecie = AliRecoParam::kHighMult;
2318 if ((strcmp(beamType,"p-p") == 0) ||
2319 (strcmp(beamType,"p-") == 0) ||
2320 (strcmp(beamType,"-p") == 0) ||
2321 (strcmp(beamType,"P-P") == 0) ||
2322 (strcmp(beamType,"P-") == 0) ||
2323 (strcmp(beamType,"-P") == 0)) {
2324 // Proton run, the event specie is set to kLowMult
2325 fEventSpecie = AliRecoParam::kLowMult;
2329 AliWarning("Unknown beam type and energy! Setting energy to 0");
2330 grpObj->SetBeamEnergy(0);
2331 grpObj->SetBeamType("UNKNOWN");
2334 UInt_t detectorPattern = 0;
2336 TObjArray *detArray = gAlice->Detectors();
2337 for (Int_t iDet = 0; iDet < AliDAQ::kNDetectors-1; iDet++) {
2338 if (detArray->FindObject(AliDAQ::OfflineModuleName(iDet))) {
2339 detectorPattern |= (1 << iDet);
2344 if (!fTriggerConfig.IsNull())
2345 detectorPattern |= (1 << AliDAQ::DetectorID("TRG"));
2348 if (!fRunHLT.IsNull())
2349 detectorPattern |= (1 << AliDAQ::kHLTId);
2351 grpObj->SetNumberOfDetectors((Char_t)nDets);
2352 grpObj->SetDetectorMask((Int_t)detectorPattern);
2353 grpObj->SetLHCPeriod("LHC08c");
2354 grpObj->SetLHCState("STABLE_BEAMS");
2356 AliMagF *field = (AliMagF*)TGeoGlobalMagField::Instance()->GetField();
2357 Float_t solenoidField = field ? TMath::Abs(field->SolenoidField()) : 0;
2359 Float_t factorSol = field ? field->GetFactorSol() : 0;
2360 Float_t currentSol = TMath::Abs(factorSol)>1E-6 ?
2361 TMath::Nint(TMath::Abs(solenoidField/factorSol))/5.*30000.*TMath::Abs(factorSol) : 0;
2363 Float_t factorDip = field ? field->GetFactorDip() : 0;
2364 Float_t currentDip = 6000.*TMath::Abs(factorDip);
2366 grpObj->SetL3Current(currentSol,(AliGRPObject::Stats)0);
2367 grpObj->SetDipoleCurrent(currentDip,(AliGRPObject::Stats)0);
2368 grpObj->SetL3Polarity(factorSol>0 ? 0:1);
2369 grpObj->SetDipolePolarity(factorDip>0 ? 0:1);
2370 if (field) grpObj->SetUniformBMap(field->IsUniform()); // for special MC with k5kGUniform map
2371 grpObj->SetPolarityConventionLHC(); // LHC convention +/+ current -> -/- field main components
2373 grpObj->SetCavernTemperature(0,(AliGRPObject::Stats)0);
2375 //grpMap->Add(new TObjString("fCavernPressure"),new TObjString("0")); ---> not inserted in simulation with the new object, since it is now an AliDCSSensor
2377 // Now store the entry in OCDB
2378 AliCDBManager* man = AliCDBManager::Instance();
2380 man->SetLock(0, fKey);
2382 AliCDBStorage* sto = man->GetStorage(fGRPWriteLocation.Data());
2385 AliCDBId id("GRP/GRP/Data", man->GetRun(), man->GetRun(), 1, 1);
2386 AliCDBMetaData *metadata= new AliCDBMetaData();
2388 metadata->SetResponsible("alice-off@cern.ch");
2389 metadata->SetComment("Automatically produced GRP entry for Monte Carlo");
2391 sto->Put(grpObj,id,metadata);
2392 man->SetLock(1, fKey);
2395 //_____________________________________________________________________________
2396 time_t AliSimulation::GenerateTimeStamp() const
2398 // Generate event time-stamp according to
2399 // SOR/EOR time from GRP
2400 if (fUseTimeStampFromCDB)
2401 return fTimeStart + gRandom->Integer(fTimeEnd-fTimeStart);