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