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