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