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 ///////////////////////////////////////////////////////////////////////////////
108 #include <TGeoManager.h>
109 #include <TObjString.h>
110 #include <TStopwatch.h>
114 #include "AliCDBStorage.h"
115 #include "AliCDBEntry.h"
116 #include "AliCDBManager.h"
117 #include "AliAlignObj.h"
118 #include "AliCentralTrigger.h"
120 #include "AliDigitizer.h"
121 #include "AliGenerator.h"
123 #include "AliModule.h"
125 #include "AliRunDigitizer.h"
126 #include "AliRunLoader.h"
127 #include "AliSimulation.h"
128 #include "AliVertexGenFile.h"
129 #include "AliCentralTrigger.h"
130 #include "AliCTPRawData.h"
131 #include "AliRawReaderFile.h"
133 #include "AliHeader.h"
134 #include "AliGenEventHeader.h"
136 ClassImp(AliSimulation)
139 //_____________________________________________________________________________
140 AliSimulation::AliSimulation(const char* configFileName, const char* cdbUri,
141 const char* name, const char* title) :
144 fRunGeneration(kTRUE),
145 fRunSimulation(kTRUE),
146 fLoadAlignFromCDB(kTRUE),
147 fLoadAlignData("ALL"),
151 fMakeDigitsFromHits(""),
153 fRawDataFileName(""),
154 fDeleteIntermediateFiles(kFALSE),
155 fStopOnError(kFALSE),
158 fConfigFileName(configFileName),
159 fGAliceFileName("galice.root"),
161 fBkgrdFileNames(NULL),
162 fAlignObjArray(NULL),
163 fUseBkgrdVertex(kTRUE),
164 fRegionOfInterest(kFALSE),
167 fEmbeddingFlag(kFALSE)
169 // create simulation object with default parameters
171 SetGAliceFile("galice.root");
174 //_____________________________________________________________________________
175 AliSimulation::AliSimulation(const AliSimulation& sim) :
178 fRunGeneration(sim.fRunGeneration),
179 fRunSimulation(sim.fRunSimulation),
180 fLoadAlignFromCDB(sim.fLoadAlignFromCDB),
181 fLoadAlignData(sim.fLoadAlignData),
182 fMakeSDigits(sim.fMakeSDigits),
183 fMakeDigits(sim.fMakeDigits),
184 fMakeTrigger(sim.fMakeTrigger),
185 fMakeDigitsFromHits(sim.fMakeDigitsFromHits),
186 fWriteRawData(sim.fWriteRawData),
187 fRawDataFileName(""),
188 fDeleteIntermediateFiles(kFALSE),
189 fStopOnError(sim.fStopOnError),
191 fNEvents(sim.fNEvents),
192 fConfigFileName(sim.fConfigFileName),
193 fGAliceFileName(sim.fGAliceFileName),
195 fBkgrdFileNames(NULL),
196 fAlignObjArray(NULL),
197 fUseBkgrdVertex(sim.fUseBkgrdVertex),
198 fRegionOfInterest(sim.fRegionOfInterest),
199 fCDBUri(sim.fCDBUri),
201 fEmbeddingFlag(sim.fEmbeddingFlag)
205 for (Int_t i = 0; i < sim.fEventsPerFile.GetEntriesFast(); i++) {
206 if (!sim.fEventsPerFile[i]) continue;
207 fEventsPerFile.Add(sim.fEventsPerFile[i]->Clone());
210 fBkgrdFileNames = new TObjArray;
211 for (Int_t i = 0; i < sim.fBkgrdFileNames->GetEntriesFast(); i++) {
212 if (!sim.fBkgrdFileNames->At(i)) continue;
213 fBkgrdFileNames->Add(sim.fBkgrdFileNames->At(i)->Clone());
216 for (Int_t i = 0; i < sim.fSpecCDBUri.GetEntriesFast(); i++) {
217 if (sim.fSpecCDBUri[i]) fSpecCDBUri.Add(sim.fSpecCDBUri[i]->Clone());
222 //_____________________________________________________________________________
223 AliSimulation& AliSimulation::operator = (const AliSimulation& sim)
225 // assignment operator
227 this->~AliSimulation();
228 new(this) AliSimulation(sim);
232 //_____________________________________________________________________________
233 AliSimulation::~AliSimulation()
237 fEventsPerFile.Delete();
238 // if(fAlignObjArray) fAlignObjArray->Delete(); // fAlignObjArray->RemoveAll() ???
239 // delete fAlignObjArray; fAlignObjArray=0;
241 if (fBkgrdFileNames) {
242 fBkgrdFileNames->Delete();
243 delete fBkgrdFileNames;
246 fSpecCDBUri.Delete();
250 //_____________________________________________________________________________
251 void AliSimulation::SetNumberOfEvents(Int_t nEvents)
253 // set the number of events for one run
258 //_____________________________________________________________________________
259 void AliSimulation::InitCDBStorage()
261 // activate a default CDB storage
262 // First check if we have any CDB storage set, because it is used
263 // to retrieve the calibration and alignment constants
265 AliCDBManager* man = AliCDBManager::Instance();
266 if (man->IsDefaultStorageSet())
268 AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
269 AliWarning("Default CDB storage has been already set !");
270 AliWarning(Form("Ignoring the default storage declared in AliReconstruction: %s",fCDBUri.Data()));
271 AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
275 AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
276 AliWarning(Form("Default CDB storage is set to: %s",fCDBUri.Data()));
277 AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
278 man->SetDefaultStorage(fCDBUri);
281 // Now activate the detector specific CDB storage locations
282 for (Int_t i = 0; i < fSpecCDBUri.GetEntriesFast(); i++) {
283 TObject* obj = fSpecCDBUri[i];
285 AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
286 AliWarning(Form("Specific CDB storage for %s is set to: %s",obj->GetName(),obj->GetTitle()));
287 AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
288 man->SetSpecificStorage(obj->GetName(),obj->GetTitle());
293 //_____________________________________________________________________________
294 void AliSimulation::SetDefaultStorage(const char* uri) {
295 // Store the desired default CDB storage location
296 // Activate it later within the Run() method
302 //_____________________________________________________________________________
303 void AliSimulation::SetSpecificStorage(const char* detName, const char* uri) {
304 // Store a detector-specific CDB storage location
305 // Activate it later within the Run() method
307 TObject* obj = fSpecCDBUri.FindObject(detName);
308 if (obj) fSpecCDBUri.Remove(obj);
309 fSpecCDBUri.Add(new TNamed(detName, uri));
313 //_____________________________________________________________________________
314 void AliSimulation::SetConfigFile(const char* fileName)
316 // set the name of the config file
318 fConfigFileName = fileName;
321 //_____________________________________________________________________________
322 void AliSimulation::SetGAliceFile(const char* fileName)
324 // set the name of the galice file
325 // the path is converted to an absolute one if it is relative
327 fGAliceFileName = fileName;
328 if (!gSystem->IsAbsoluteFileName(fGAliceFileName)) {
329 char* absFileName = gSystem->ConcatFileName(gSystem->WorkingDirectory(),
331 fGAliceFileName = absFileName;
332 delete[] absFileName;
335 AliDebug(2, Form("galice file name set to %s", fileName));
338 //_____________________________________________________________________________
339 void AliSimulation::SetEventsPerFile(const char* detector, const char* type,
342 // set the number of events per file for the given detector and data type
343 // ("Hits", "Summable Digits", "Digits", "Reconstructed Points" or "Tracks")
345 TNamed* obj = new TNamed(detector, type);
346 obj->SetUniqueID(nEvents);
347 fEventsPerFile.Add(obj);
350 //_____________________________________________________________________________
351 Bool_t AliSimulation::ApplyAlignObjsToGeom(TObjArray* alObjArray)
353 // Read collection of alignment objects (AliAlignObj derived) saved
354 // in the TClonesArray ClArrayName and apply them to the geometry
355 // manager singleton.
358 Int_t nvols = alObjArray->GetEntriesFast();
362 for(Int_t j=0; j<nvols; j++)
364 AliAlignObj* alobj = (AliAlignObj*) alObjArray->UncheckedAt(j);
365 if (alobj->ApplyToGeometry() == kFALSE) flag = kFALSE;
368 if (AliDebugLevelClass() >= 1) {
369 gGeoManager->GetTopNode()->CheckOverlaps(20);
370 TObjArray* ovexlist = gGeoManager->GetListOfOverlaps();
371 if(ovexlist->GetEntriesFast()){
372 AliError("The application of alignment objects to the geometry caused huge overlaps/extrusions!");
380 //_____________________________________________________________________________
381 Bool_t AliSimulation::ApplyAlignObjsToGeom(const char* fileName, const char* clArrayName)
383 // read collection of alignment objects (AliAlignObj derived) saved
384 // in the TClonesArray ClArrayName in the file fileName and apply
385 // them to the TGeo geometry passed as argument
388 TFile* inFile = TFile::Open(fileName,"READ");
389 if (!inFile || !inFile->IsOpen()) {
390 AliErrorClass(Form("Could not open file %s !",fileName));
394 TClonesArray* alObjArray = ((TClonesArray*) inFile->Get(clArrayName));
397 AliErrorClass(Form("Could not get array (%s) from file (%s) !",clArrayName,fileName));
401 return ApplyAlignObjsToGeom(alObjArray);
405 //_____________________________________________________________________________
406 Bool_t AliSimulation::ApplyAlignObjsToGeom(AliCDBParam* param, AliCDBId& Id)
408 // read collection of alignment objects (AliAlignObj derived) saved
409 // in the TClonesArray ClArrayName in the AliCDBEntry identified by
410 // param (to get the AliCDBStorage) and Id; apply the alignment objects
411 // to the TGeo geometry passed as argument
414 AliCDBStorage* storage = AliCDBManager::Instance()->GetStorage(param);
415 AliCDBEntry* entry = storage->Get(Id);
416 TClonesArray* AlObjArray = ((TClonesArray*) entry->GetObject());
418 return ApplyAlignObjsToGeom(AlObjArray);
422 //_____________________________________________________________________________
423 Bool_t AliSimulation::ApplyAlignObjsToGeom(const char* uri, const char* path, Int_t runnum, Int_t version, Int_t sversion)
425 // read collection of alignment objects (AliAlignObj derived) saved
426 // in the TClonesArray ClArrayName in the AliCDBEntry identified by
427 // param (to get the AliCDBStorage) and Id; apply the alignment objects
428 // to the TGeo geometry passed as argument
431 AliCDBParam* param = AliCDBManager::Instance()->CreateParameter(uri);
432 AliCDBId id(path, runnum, runnum, version, sversion);
434 return ApplyAlignObjsToGeom(param, id);
438 //_____________________________________________________________________________
439 Bool_t AliSimulation::ApplyAlignObjsToGeom(const char* detName, Int_t runnum, Int_t version, Int_t sversion)
441 // read collection of alignment objects (AliAlignObj derived) saved
442 // in the TClonesArray ClArrayName in the AliCDBEntry identified by
443 // param (to get the AliCDBStorage) and Id; apply the alignment objects
444 // to the TGeo geometry passed as argument
447 AliCDBPath path(detName,"Align","Data");
448 AliCDBEntry* entry = AliCDBManager::Instance()->Get(path.GetPath(),runnum,version,sversion);
450 if(!entry) return kFALSE;
451 TClonesArray* AlObjArray = ((TClonesArray*) entry->GetObject());
453 return ApplyAlignObjsToGeom(AlObjArray);
456 //_____________________________________________________________________________
457 Bool_t AliSimulation::SetAlignObjArraySingleDet(const char* detName)
459 // Fills array of single detector's alignable objects from CDB
461 AliDebug(2, Form("Loading alignment data for detector: %s",detName));
465 AliCDBPath path(detName,"Align","Data");
467 entry=AliCDBManager::Instance()->Get(path.GetPath());
469 AliDebug(2,Form("Couldn't load alignment data for detector %s",detName));
473 TClonesArray *alignArray = (TClonesArray*) entry->GetObject();
474 alignArray->SetOwner(0);
475 AliDebug(2,Form("Found %d alignment objects for %s",
476 alignArray->GetEntries(),detName));
478 AliAlignObj *alignObj=0;
479 TIter iter(alignArray);
481 // loop over align objects in detector
482 while( ( alignObj=(AliAlignObj *) iter.Next() ) ){
483 fAlignObjArray->Add(alignObj);
485 // delete entry --- Don't delete, it is cached!
487 AliDebug(2, Form("fAlignObjArray entries: %d",fAlignObjArray->GetEntries() ));
492 //_____________________________________________________________________________
493 Bool_t AliSimulation::MisalignGeometry(AliRunLoader *runLoader)
495 // Read the alignment objects from CDB.
496 // Each detector is supposed to have the
497 // alignment objects in DET/Align/Data CDB path.
498 // All the detector objects are then collected,
499 // sorted by geometry level (starting from ALIC) and
500 // then applied to the TGeo geometry.
501 // Finally an overlaps check is performed.
503 Bool_t delRunLoader = kFALSE;
505 runLoader = LoadRun("READ");
506 if (!runLoader) return kFALSE;
507 delRunLoader = kTRUE;
510 // Load alignment data from CDB and fill fAlignObjArray
511 if(fLoadAlignFromCDB){
512 if(!fAlignObjArray) fAlignObjArray = new TObjArray();
514 //fAlignObjArray->RemoveAll();
515 fAlignObjArray->Clear();
516 fAlignObjArray->SetOwner(0);
518 TString detStr = fLoadAlignData;
519 TString dataNotLoaded="";
520 TString dataLoaded="";
522 TObjArray* detArray = runLoader->GetAliRun()->Detectors();
523 for (Int_t iDet = 0; iDet < detArray->GetEntriesFast(); iDet++) {
524 AliModule* det = (AliModule*) detArray->At(iDet);
525 if (!det || !det->IsActive()) continue;
526 if (IsSelected(det->GetName(), detStr)) {
527 if(!SetAlignObjArraySingleDet(det->GetName())){
528 dataNotLoaded += det->GetName();
529 dataNotLoaded += " ";
531 dataLoaded += det->GetName();
535 } // end loop over detectors
537 if ((detStr.CompareTo("ALL") == 0)) detStr = "";
538 dataNotLoaded += detStr;
539 AliInfo(Form("Alignment data loaded for: %s",
541 AliInfo(Form("Didn't/couldn't load alignment data for: %s",
542 dataNotLoaded.Data()));
543 } // fLoadAlignFromCDB flag
545 // Check if the array with alignment objects was
546 // provided by the user. If yes, apply the objects
547 // to the present TGeo geometry
548 if (fAlignObjArray) {
549 if (gGeoManager && gGeoManager->IsClosed()) {
550 if (ApplyAlignObjsToGeom(fAlignObjArray) == kFALSE) {
551 AliError("The misalignment of one or more volumes failed!"
552 "Compare the list of simulated detectors and the list of detector alignment data!");
553 if (delRunLoader) delete runLoader;
558 AliError("Can't apply the misalignment! gGeoManager doesn't exist or it is still opened!");
559 if (delRunLoader) delete runLoader;
564 if (delRunLoader) delete runLoader;
570 //_____________________________________________________________________________
571 Bool_t AliSimulation::SetRunNumber()
573 // Set the CDB manager run number
574 // The run number is retrieved from gAlice
576 if(AliCDBManager::Instance()->GetRun() < 0) {
577 AliRunLoader* runLoader = LoadRun("READ");
578 if (!runLoader) return kFALSE;
580 AliCDBManager::Instance()->SetRun(runLoader->GetAliRun()->GetRunNumber());
581 AliInfo(Form("Run number: %d",AliCDBManager::Instance()->GetRun()));
588 //_____________________________________________________________________________
589 void AliSimulation::MergeWith(const char* fileName, Int_t nSignalPerBkgrd)
591 // add a file with background events for merging
593 TObjString* fileNameStr = new TObjString(fileName);
594 fileNameStr->SetUniqueID(nSignalPerBkgrd);
595 if (!fBkgrdFileNames) fBkgrdFileNames = new TObjArray;
596 fBkgrdFileNames->Add(fileNameStr);
599 void AliSimulation::EmbedInto(const char* fileName, Int_t nSignalPerBkgrd)
601 // add a file with background events for embeddin
602 MergeWith(fileName, nSignalPerBkgrd);
603 fEmbeddingFlag = kTRUE;
606 //_____________________________________________________________________________
607 Bool_t AliSimulation::Run(Int_t nEvents)
609 // run the generation, simulation and digitization
613 if (nEvents > 0) fNEvents = nEvents;
615 // generation and simulation -> hits
616 if (fRunGeneration) {
617 if (!RunSimulation()) if (fStopOnError) return kFALSE;
620 // Set run number in CDBManager (if it is not already set in RunSimulation)
621 if (!SetRunNumber()) if (fStopOnError) return kFALSE;
623 // Load and misalign the geometry
625 TGeoManager::Import("geometry.root");
626 if (!gGeoManager) if (fStopOnError) return kFALSE;
627 if (!MisalignGeometry()) if (fStopOnError) return kFALSE;
630 // hits -> summable digits
631 if (!fMakeSDigits.IsNull()) {
632 if (!RunSDigitization(fMakeSDigits)) if (fStopOnError) return kFALSE;
635 // summable digits -> digits
636 if (!fMakeDigits.IsNull()) {
637 if (!RunDigitization(fMakeDigits, fMakeDigitsFromHits)) {
638 if (fStopOnError) return kFALSE;
643 if (!fMakeDigitsFromHits.IsNull()) {
644 if (fBkgrdFileNames && (fBkgrdFileNames->GetEntriesFast() > 0)) {
645 AliWarning(Form("Merging and direct creation of digits from hits "
646 "was selected for some detectors. "
647 "No merging will be done for the following detectors: %s",
648 fMakeDigitsFromHits.Data()));
650 if (!RunHitsDigitization(fMakeDigitsFromHits)) {
651 if (fStopOnError) return kFALSE;
656 if (!RunTrigger(fMakeTrigger)) {
657 if (fStopOnError) return kFALSE;
660 // digits -> raw data
661 if (!fWriteRawData.IsNull()) {
662 if (!WriteRawData(fWriteRawData, fRawDataFileName,
663 fDeleteIntermediateFiles)) {
664 if (fStopOnError) return kFALSE;
671 //_____________________________________________________________________________
672 Bool_t AliSimulation::RunTrigger(const char* descriptors)
676 TStopwatch stopwatch;
679 AliRunLoader* runLoader = LoadRun("READ");
680 if (!runLoader) return kFALSE;
681 TString des = descriptors;
684 if (gAlice->GetTriggerDescriptor() != "") {
685 des = gAlice->GetTriggerDescriptor();
688 AliWarning("No trigger descriptor is specified. Skipping the trigger simulation...");
693 runLoader->MakeTree( "CT" );
694 AliCentralTrigger* aCTP = runLoader->GetTrigger();
696 aCTP->LoadDescriptor( des );
699 if( !aCTP->RunTrigger( runLoader ) ) {
706 AliInfo(Form("Execution time: R:%.2fs C:%.2fs",
707 stopwatch.RealTime(),stopwatch.CpuTime()));
714 //_____________________________________________________________________________
715 Bool_t AliSimulation::WriteTriggerRawData()
717 // Writes the CTP (trigger) DDL raw data
718 // Details of the format are given in the
719 // trigger TDR - pages 134 and 135.
720 AliCTPRawData writer;
726 //_____________________________________________________________________________
727 Bool_t AliSimulation::RunSimulation(Int_t nEvents)
729 // run the generation and simulation
731 TStopwatch stopwatch;
735 AliError("no gAlice object. Restart aliroot and try again.");
738 if (gAlice->Modules()->GetEntries() > 0) {
739 AliError("gAlice was already run. Restart aliroot and try again.");
743 AliInfo(Form("initializing gAlice with config file %s",
744 fConfigFileName.Data()));
745 StdoutToAliInfo(StderrToAliError(
746 gAlice->Init(fConfigFileName.Data());
749 // Get the trigger descriptor string
750 // Either from AliSimulation or from
752 if (fMakeTrigger.IsNull()) {
753 if (gAlice->GetTriggerDescriptor() != "")
754 fMakeTrigger = gAlice->GetTriggerDescriptor();
757 gAlice->SetTriggerDescriptor(fMakeTrigger.Data());
759 // Set run number in CDBManager
760 AliCDBManager::Instance()->SetRun(gAlice->GetRunNumber());
761 AliInfo(Form("Run number: %d",AliCDBManager::Instance()->GetRun()));
763 AliRunLoader* runLoader = gAlice->GetRunLoader();
765 AliError(Form("gAlice has no run loader object. "
766 "Check your config file: %s", fConfigFileName.Data()));
769 SetGAliceFile(runLoader->GetFileName());
771 // Export ideal geometry
772 if (gGeoManager) gGeoManager->Export("geometry.root");
775 // if (!MisalignGeometry(runLoader)) {
779 MisalignGeometry(runLoader);
781 // Export (mis)aligned geometry
782 if (gGeoManager) gGeoManager->Export("misaligned_geometry.root");
784 // AliRunLoader* runLoader = gAlice->GetRunLoader();
786 // AliError(Form("gAlice has no run loader object. "
787 // "Check your config file: %s", fConfigFileName.Data()));
790 // SetGAliceFile(runLoader->GetFileName());
792 if (!gAlice->Generator()) {
793 AliError(Form("gAlice has no generator object. "
794 "Check your config file: %s", fConfigFileName.Data()));
797 if (nEvents <= 0) nEvents = fNEvents;
799 // get vertex from background file in case of merging
800 if (fUseBkgrdVertex &&
801 fBkgrdFileNames && (fBkgrdFileNames->GetEntriesFast() > 0)) {
802 Int_t signalPerBkgrd = GetNSignalPerBkgrd(nEvents);
803 const char* fileName = ((TObjString*)
804 (fBkgrdFileNames->At(0)))->GetName();
805 AliInfo(Form("The vertex will be taken from the background "
806 "file %s with nSignalPerBackground = %d",
807 fileName, signalPerBkgrd));
808 AliVertexGenFile* vtxGen = new AliVertexGenFile(fileName, signalPerBkgrd);
809 gAlice->Generator()->SetVertexGenerator(vtxGen);
812 if (!fRunSimulation) {
813 gAlice->Generator()->SetTrackingFlag(0);
816 // set the number of events per file for given detectors and data types
817 for (Int_t i = 0; i < fEventsPerFile.GetEntriesFast(); i++) {
818 if (!fEventsPerFile[i]) continue;
819 const char* detName = fEventsPerFile[i]->GetName();
820 const char* typeName = fEventsPerFile[i]->GetTitle();
821 TString loaderName(detName);
822 loaderName += "Loader";
823 AliLoader* loader = runLoader->GetLoader(loaderName);
825 AliError(Form("RunSimulation", "no loader for %s found\n"
826 "Number of events per file not set for %s %s",
827 detName, typeName, detName));
830 AliDataLoader* dataLoader =
831 loader->GetDataLoader(typeName);
833 AliError(Form("no data loader for %s found\n"
834 "Number of events per file not set for %s %s",
835 typeName, detName, typeName));
838 dataLoader->SetNumberOfEventsPerFile(fEventsPerFile[i]->GetUniqueID());
839 AliDebug(1, Form("number of events per file set to %d for %s %s",
840 fEventsPerFile[i]->GetUniqueID(), detName, typeName));
843 AliInfo("running gAlice");
844 StdoutToAliInfo(StderrToAliError(
845 gAlice->Run(nEvents);
850 AliInfo(Form("Execution time: R:%.2fs C:%.2fs",
851 stopwatch.RealTime(),stopwatch.CpuTime()));
856 //_____________________________________________________________________________
857 Bool_t AliSimulation::RunSDigitization(const char* detectors)
859 // run the digitization and produce summable digits
861 TStopwatch stopwatch;
864 AliRunLoader* runLoader = LoadRun();
865 if (!runLoader) return kFALSE;
867 TString detStr = detectors;
868 TObjArray* detArray = runLoader->GetAliRun()->Detectors();
869 for (Int_t iDet = 0; iDet < detArray->GetEntriesFast(); iDet++) {
870 AliModule* det = (AliModule*) detArray->At(iDet);
871 if (!det || !det->IsActive()) continue;
872 if (IsSelected(det->GetName(), detStr)) {
873 AliInfo(Form("creating summable digits for %s", det->GetName()));
874 TStopwatch stopwatchDet;
875 stopwatchDet.Start();
877 AliInfo(Form("Execution time for %s: R:%.2fs C:%.2fs",
878 det->GetName(),stopwatchDet.RealTime(),stopwatchDet.CpuTime()));
882 if ((detStr.CompareTo("ALL") != 0) && !detStr.IsNull()) {
883 AliError(Form("the following detectors were not found: %s",
885 if (fStopOnError) return kFALSE;
890 AliInfo(Form("Execution time: R:%.2fs C:%.2fs",
891 stopwatch.RealTime(),stopwatch.CpuTime()));
897 //_____________________________________________________________________________
898 Bool_t AliSimulation::RunDigitization(const char* detectors,
899 const char* excludeDetectors)
901 // run the digitization and produce digits from sdigits
903 TStopwatch stopwatch;
906 while (AliRunLoader::GetRunLoader()) delete AliRunLoader::GetRunLoader();
907 if (gAlice) delete gAlice;
911 if (fBkgrdFileNames) nStreams = fBkgrdFileNames->GetEntriesFast() + 1;
912 Int_t signalPerBkgrd = GetNSignalPerBkgrd();
913 AliRunDigitizer* manager = new AliRunDigitizer(nStreams, signalPerBkgrd);
914 // manager->SetEmbeddingFlag(fEmbeddingFlag);
915 manager->SetInputStream(0, fGAliceFileName.Data());
916 for (Int_t iStream = 1; iStream < nStreams; iStream++) {
917 const char* fileName = ((TObjString*)
918 (fBkgrdFileNames->At(iStream-1)))->GetName();
919 manager->SetInputStream(iStream, fileName);
922 TString detStr = detectors;
923 TString detExcl = excludeDetectors;
924 manager->GetInputStream(0)->ImportgAlice();
925 AliRunLoader* runLoader =
926 AliRunLoader::GetRunLoader(manager->GetInputStream(0)->GetFolderName());
927 TObjArray* detArray = runLoader->GetAliRun()->Detectors();
928 for (Int_t iDet = 0; iDet < detArray->GetEntriesFast(); iDet++) {
929 AliModule* det = (AliModule*) detArray->At(iDet);
930 if (!det || !det->IsActive()) continue;
931 if (IsSelected(det->GetName(), detStr) &&
932 !IsSelected(det->GetName(), detExcl)) {
933 AliDigitizer* digitizer = det->CreateDigitizer(manager);
936 AliError(Form("no digitizer for %s", det->GetName()));
937 if (fStopOnError) return kFALSE;
939 digitizer->SetRegionOfInterest(fRegionOfInterest);
944 if ((detStr.CompareTo("ALL") != 0) && !detStr.IsNull()) {
945 AliError(Form("the following detectors were not found: %s",
947 if (fStopOnError) return kFALSE;
950 if (!manager->GetListOfTasks()->IsEmpty()) {
951 AliInfo("executing digitization");
957 AliInfo(Form("Execution time: R:%.2fs C:%.2fs",
958 stopwatch.RealTime(),stopwatch.CpuTime()));
963 //_____________________________________________________________________________
964 Bool_t AliSimulation::RunHitsDigitization(const char* detectors)
966 // run the digitization and produce digits from hits
968 TStopwatch stopwatch;
971 AliRunLoader* runLoader = LoadRun("READ");
972 if (!runLoader) return kFALSE;
974 TString detStr = detectors;
975 TObjArray* detArray = runLoader->GetAliRun()->Detectors();
976 for (Int_t iDet = 0; iDet < detArray->GetEntriesFast(); iDet++) {
977 AliModule* det = (AliModule*) detArray->At(iDet);
978 if (!det || !det->IsActive()) continue;
979 if (IsSelected(det->GetName(), detStr)) {
980 AliInfo(Form("creating digits from hits for %s", det->GetName()));
985 if ((detStr.CompareTo("ALL") != 0) && !detStr.IsNull()) {
986 AliError(Form("the following detectors were not found: %s",
988 if (fStopOnError) return kFALSE;
992 //PH Temporary fix to avoid interference with the PHOS loder/getter
993 //PH The problem has to be solved in more general way 09/06/05
995 AliInfo(Form("Execution time: R:%.2fs C:%.2fs",
996 stopwatch.RealTime(),stopwatch.CpuTime()));
1001 //_____________________________________________________________________________
1002 Bool_t AliSimulation::WriteRawData(const char* detectors,
1003 const char* fileName,
1004 Bool_t deleteIntermediateFiles)
1006 // convert the digits to raw data
1007 // First DDL raw data files for the given detectors are created.
1008 // If a file name is given, the DDL files are then converted to a DATE file.
1009 // If deleteIntermediateFiles is true, the DDL raw files are deleted
1011 // If the file name has the extension ".root", the DATE file is converted
1013 // If deleteIntermediateFiles is true, the DATE file is deleted afterwards.
1015 TStopwatch stopwatch;
1018 if (!WriteRawFiles(detectors)) {
1019 if (fStopOnError) return kFALSE;
1022 TString dateFileName(fileName);
1023 if (!dateFileName.IsNull()) {
1024 Bool_t rootOutput = dateFileName.EndsWith(".root");
1025 if (rootOutput) dateFileName += ".date";
1026 if (!ConvertRawFilesToDate(dateFileName)) {
1027 if (fStopOnError) return kFALSE;
1029 if (deleteIntermediateFiles) {
1030 AliRunLoader* runLoader = LoadRun("READ");
1031 if (runLoader) for (Int_t iEvent = 0;
1032 iEvent < runLoader->GetNumberOfEvents(); iEvent++) {
1034 sprintf(command, "rm -r raw%d", iEvent);
1035 gSystem->Exec(command);
1040 if (!ConvertDateToRoot(dateFileName, fileName)) {
1041 if (fStopOnError) return kFALSE;
1043 if (deleteIntermediateFiles) {
1044 gSystem->Unlink(dateFileName);
1049 AliInfo(Form("Execution time: R:%.2fs C:%.2fs",
1050 stopwatch.RealTime(),stopwatch.CpuTime()));
1055 //_____________________________________________________________________________
1056 Bool_t AliSimulation::WriteRawFiles(const char* detectors)
1058 // convert the digits to raw data DDL files
1060 AliRunLoader* runLoader = LoadRun("READ");
1061 if (!runLoader) return kFALSE;
1063 // write raw data to DDL files
1064 for (Int_t iEvent = 0; iEvent < runLoader->GetNumberOfEvents(); iEvent++) {
1065 AliInfo(Form("processing event %d", iEvent));
1066 runLoader->GetEvent(iEvent);
1067 TString baseDir = gSystem->WorkingDirectory();
1069 sprintf(dirName, "raw%d", iEvent);
1070 gSystem->MakeDirectory(dirName);
1071 if (!gSystem->ChangeDirectory(dirName)) {
1072 AliError(Form("couldn't change to directory %s", dirName));
1073 if (fStopOnError) return kFALSE; else continue;
1076 TString detStr = detectors;
1077 TObjArray* detArray = runLoader->GetAliRun()->Detectors();
1078 for (Int_t iDet = 0; iDet < detArray->GetEntriesFast(); iDet++) {
1079 AliModule* det = (AliModule*) detArray->At(iDet);
1080 if (!det || !det->IsActive()) continue;
1081 if (IsSelected(det->GetName(), detStr)) {
1082 AliInfo(Form("creating raw data from digits for %s", det->GetName()));
1087 if (!WriteTriggerRawData())
1088 if (fStopOnError) return kFALSE;
1090 gSystem->ChangeDirectory(baseDir);
1091 if ((detStr.CompareTo("ALL") != 0) && !detStr.IsNull()) {
1092 AliError(Form("the following detectors were not found: %s",
1094 if (fStopOnError) return kFALSE;
1102 //_____________________________________________________________________________
1103 Bool_t AliSimulation::ConvertRawFilesToDate(const char* dateFileName)
1105 // convert raw data DDL files to a DATE file with the program "dateStream"
1107 char* path = gSystem->Which(gSystem->Getenv("PATH"), "dateStream");
1109 AliError("the program dateStream was not found");
1110 if (fStopOnError) return kFALSE;
1115 AliRunLoader* runLoader = LoadRun("READ");
1116 if (!runLoader) return kFALSE;
1118 AliInfo(Form("converting raw data DDL files to DATE file %s", dateFileName));
1120 sprintf(command, "dateStream -D -o %s -# %d -C",
1121 dateFileName, runLoader->GetNumberOfEvents());
1122 FILE* pipe = gSystem->OpenPipe(command, "w");
1124 for (Int_t iEvent = 0; iEvent < runLoader->GetNumberOfEvents(); iEvent++) {
1125 fprintf(pipe, "GDC\n");
1129 // loop over detectors and DDLs
1130 for (Int_t iDet = 0; iDet < AliDAQ::kNDetectors; iDet++) {
1131 for (Int_t iDDL = 0; iDDL < AliDAQ::NumberOfDdls(iDet); iDDL++) {
1133 Int_t ddlID = AliDAQ::DdlID(iDet,iDDL);
1134 Int_t ldcID = Int_t(ldc + 0.0001);
1135 ldc += AliDAQ::NumberOfLdcs(iDet) / AliDAQ::NumberOfDdls(iDet);
1137 char rawFileName[256];
1138 sprintf(rawFileName, "raw%d/%s",
1139 iEvent, AliDAQ::DdlFileName(iDet,iDDL));
1141 // check existence and size of raw data file
1142 FILE* file = fopen(rawFileName, "rb");
1143 if (!file) continue;
1144 fseek(file, 0, SEEK_END);
1145 unsigned long size = ftell(file);
1147 if (!size) continue;
1149 if (ldcID != prevLDC) {
1150 fprintf(pipe, " LDC Id %d\n", ldcID);
1153 fprintf(pipe, " Equipment Id %d Payload %s\n", ddlID, rawFileName);
1158 Int_t result = gSystem->ClosePipe(pipe);
1161 return (result == 0);
1164 //_____________________________________________________________________________
1165 Bool_t AliSimulation::ConvertDateToRoot(const char* dateFileName,
1166 const char* rootFileName)
1168 // convert a DATE file to a root file with the program "alimdc"
1171 const Int_t kDBSize = 1000000000;
1172 const Int_t kTagDBSize = 1000000000;
1173 const Bool_t kFilter = kFALSE;
1174 const Int_t kCompression = 1;
1176 char* path = gSystem->Which(gSystem->Getenv("PATH"), "alimdc");
1178 AliError("the program alimdc was not found");
1179 if (fStopOnError) return kFALSE;
1184 AliInfo(Form("converting DATE file %s to root file %s",
1185 dateFileName, rootFileName));
1187 const char* rawDBFS[2] = { "/tmp/mdc1", "/tmp/mdc2" };
1188 const char* tagDBFS = "/tmp/mdc1/tags";
1189 const char* runDBFS = "/tmp/mdc1/meta";
1191 // User defined file system locations
1192 if (gSystem->Getenv("ALIMDC_RAWDB1"))
1193 rawDBFS[0] = gSystem->Getenv("ALIMDC_RAWDB1");
1194 if (gSystem->Getenv("ALIMDC_RAWDB2"))
1195 rawDBFS[1] = gSystem->Getenv("ALIMDC_RAWDB2");
1196 if (gSystem->Getenv("ALIMDC_TAGDB"))
1197 tagDBFS = gSystem->Getenv("ALIMDC_TAGDB");
1198 if (gSystem->Getenv("ALIMDC_RUNDB"))
1199 runDBFS = gSystem->Getenv("ALIMDC_RUNDB");
1201 gSystem->Exec(Form("rm -rf %s",rawDBFS[0]));
1202 gSystem->Exec(Form("rm -rf %s",rawDBFS[1]));
1203 gSystem->Exec(Form("rm -rf %s",tagDBFS));
1204 gSystem->Exec(Form("rm -rf %s",runDBFS));
1206 gSystem->Exec(Form("mkdir %s",rawDBFS[0]));
1207 gSystem->Exec(Form("mkdir %s",rawDBFS[1]));
1208 gSystem->Exec(Form("mkdir %s",tagDBFS));
1209 gSystem->Exec(Form("mkdir %s",runDBFS));
1211 Int_t result = gSystem->Exec(Form("alimdc %d %d %d %d %s",
1212 kDBSize, kTagDBSize, kFilter, kCompression, dateFileName));
1213 gSystem->Exec(Form("mv %s/*.root %s", rawDBFS[0], rootFileName));
1215 gSystem->Exec(Form("rm -rf %s",rawDBFS[0]));
1216 gSystem->Exec(Form("rm -rf %s",rawDBFS[1]));
1217 gSystem->Exec(Form("rm -rf %s",tagDBFS));
1218 gSystem->Exec(Form("rm -rf %s",runDBFS));
1220 return (result == 0);
1224 //_____________________________________________________________________________
1225 AliRunLoader* AliSimulation::LoadRun(const char* mode) const
1227 // delete existing run loaders, open a new one and load gAlice
1229 while (AliRunLoader::GetRunLoader()) delete AliRunLoader::GetRunLoader();
1230 AliRunLoader* runLoader =
1231 AliRunLoader::Open(fGAliceFileName.Data(),
1232 AliConfig::GetDefaultEventFolderName(), mode);
1234 AliError(Form("no run loader found in file %s", fGAliceFileName.Data()));
1237 runLoader->LoadgAlice();
1238 gAlice = runLoader->GetAliRun();
1240 AliError(Form("no gAlice object found in file %s",
1241 fGAliceFileName.Data()));
1247 //_____________________________________________________________________________
1248 Int_t AliSimulation::GetNSignalPerBkgrd(Int_t nEvents) const
1250 // get or calculate the number of signal events per background event
1252 if (!fBkgrdFileNames) return 1;
1253 Int_t nBkgrdFiles = fBkgrdFileNames->GetEntriesFast();
1254 if (nBkgrdFiles == 0) return 1;
1256 // get the number of signal events
1258 AliRunLoader* runLoader =
1259 AliRunLoader::Open(fGAliceFileName.Data(), "SIGNAL");
1260 if (!runLoader) return 1;
1262 nEvents = runLoader->GetNumberOfEvents();
1267 for (Int_t iBkgrdFile = 0; iBkgrdFile < nBkgrdFiles; iBkgrdFile++) {
1268 // get the number of background events
1269 const char* fileName = ((TObjString*)
1270 (fBkgrdFileNames->At(iBkgrdFile)))->GetName();
1271 AliRunLoader* runLoader =
1272 AliRunLoader::Open(fileName, "BKGRD");
1273 if (!runLoader) continue;
1274 Int_t nBkgrdEvents = runLoader->GetNumberOfEvents();
1277 // get or calculate the number of signal per background events
1278 Int_t nSignalPerBkgrd = fBkgrdFileNames->At(iBkgrdFile)->GetUniqueID();
1279 if (nSignalPerBkgrd <= 0) {
1280 nSignalPerBkgrd = (nEvents-1) / nBkgrdEvents + 1;
1281 } else if (result && (result != nSignalPerBkgrd)) {
1282 AliInfo(Form("the number of signal events per background event "
1283 "will be changed from %d to %d for stream %d",
1284 nSignalPerBkgrd, result, iBkgrdFile+1));
1285 nSignalPerBkgrd = result;
1288 if (!result) result = nSignalPerBkgrd;
1289 if (nSignalPerBkgrd * nBkgrdEvents < nEvents) {
1290 AliWarning(Form("not enough background events (%d) for %d signal events "
1291 "using %d signal per background events for stream %d",
1292 nBkgrdEvents, nEvents, nSignalPerBkgrd, iBkgrdFile+1));
1299 //_____________________________________________________________________________
1300 Bool_t AliSimulation::IsSelected(TString detName, TString& detectors) const
1302 // check whether detName is contained in detectors
1303 // if yes, it is removed from detectors
1305 // check if all detectors are selected
1306 if ((detectors.CompareTo("ALL") == 0) ||
1307 detectors.BeginsWith("ALL ") ||
1308 detectors.EndsWith(" ALL") ||
1309 detectors.Contains(" ALL ")) {
1314 // search for the given detector
1315 Bool_t result = kFALSE;
1316 if ((detectors.CompareTo(detName) == 0) ||
1317 detectors.BeginsWith(detName+" ") ||
1318 detectors.EndsWith(" "+detName) ||
1319 detectors.Contains(" "+detName+" ")) {
1320 detectors.ReplaceAll(detName, "");
1324 // clean up the detectors string
1325 while (detectors.Contains(" ")) detectors.ReplaceAll(" ", " ");
1326 while (detectors.BeginsWith(" ")) detectors.Remove(0, 1);
1327 while (detectors.EndsWith(" ")) detectors.Remove(detectors.Length()-1, 1);
1332 Bool_t AliSimulation::ConvertRaw2SDigits(const char* rawDirectory, const char* esdFileName)
1335 // Steering routine to convert raw data in directory rawDirectory/ to fake SDigits.
1336 // These can be used for embedding of MC tracks into RAW data using the standard
1337 // merging procedure.
1339 // If an ESD file is given the reconstructed vertex is taken from it and stored in the event header.
1342 AliError("no gAlice object. Restart aliroot and try again.");
1345 if (gAlice->Modules()->GetEntries() > 0) {
1346 AliError("gAlice was already run. Restart aliroot and try again.");
1350 AliInfo(Form("initializing gAlice with config file %s",fConfigFileName.Data()));
1351 StdoutToAliInfo(StderrToAliError(gAlice->Init(fConfigFileName.Data());););
1355 AliCDBManager* man = AliCDBManager::Instance();
1356 man->SetRun(0); // Should this come from rawdata header ?
1360 // Get the runloader
1361 AliRunLoader* runLoader = gAlice->GetRunLoader();
1363 // Open esd file if available
1364 TFile* esdFile = TFile::Open(esdFileName);
1365 Bool_t esdOK = (esdFile != 0);
1366 AliESD* esd = new AliESD;
1369 treeESD = (TTree*) esdFile->Get("esdTree");
1371 AliWarning("No ESD tree found");
1374 treeESD->SetBranchAddress("ESD", &esd);
1378 // Create the RawReader
1379 AliRawReaderFile* rawReader = new AliRawReaderFile(rawDirectory);
1381 // Get list of detectors
1382 TObjArray* detArray = runLoader->GetAliRun()->Detectors();
1385 AliHeader* header = runLoader->GetHeader();
1390 if (!(rawReader->NextEvent())) break;
1393 for (iDet = 0; iDet < detArray->GetEntriesFast(); iDet++) {
1394 AliModule* det = (AliModule*) detArray->At(iDet);
1395 AliInfo(Form("Calling Raw2SDigits for %s\n", det->GetName()));
1396 det->Raw2SDigits(rawReader);
1401 // If ESD information available obtain reconstructed vertex and store in header.
1403 treeESD->GetEvent(nev);
1404 const AliESDVertex* esdVertex = esd->GetPrimaryVertex();
1405 Double_t position[3];
1406 esdVertex->GetXYZ(position);
1407 AliGenEventHeader* mcHeader = new AliGenEventHeader("ESD");
1410 for (Int_t i = 0; i < 3; i++) mcV[i] = position[i];
1411 mcHeader->SetPrimaryVertex(mcV);
1412 header->Reset(0,nev);
1413 header->SetGenEventHeader(mcHeader);
1414 printf("***** Saved vertex %f %f %f \n", position[0], position[1], position[2]);
1419 runLoader->TreeE()->Fill();
1420 runLoader->SetNextEvent();
1426 runLoader->CdGAFile();
1427 runLoader->WriteHeader("OVERWRITE");
1428 runLoader->WriteRunLoader();