]> git.uio.no Git - u/mrichter/AliRoot.git/blob - EVE/EveBase/AliEveEventManager.cxx
AliEveEventManager
[u/mrichter/AliRoot.git] / EVE / EveBase / AliEveEventManager.cxx
1 // $Id$
2 // Main authors: Matevz Tadel & Alja Mrak-Tadel: 2006, 2007
3
4 /**************************************************************************
5  * Copyright(c) 1998-2008, ALICE Experiment at CERN, all rights reserved. *
6  * See http://aliceinfo.cern.ch/Offline/AliRoot/License.html for          *
7  * full copyright notice.                                                 *
8  **************************************************************************/
9
10 #include "AliEveEventManager.h"
11 #include <TEveManager.h>
12
13 #include <AliRunLoader.h>
14 #include <AliRun.h>
15 #include <AliESDEvent.h>
16 #include <AliESDfriend.h>
17 #include <AliDAQ.h>
18 #include <AliRawEventHeaderBase.h>
19 #include <AliRawReaderRoot.h>
20 #include <AliRawReaderFile.h>
21 #include <AliRawReaderDate.h>
22 #include <AliMagFMaps.h>
23 #include <AliCDBManager.h>
24 #include <AliHeader.h>
25 #include <AliGeomManager.h>
26
27 #include <TFile.h>
28 #include <TTree.h>
29 #include <TGeoManager.h>
30 #include <TSystem.h>
31
32 //==============================================================================
33 //==============================================================================
34 // AliEveEventManager
35 //==============================================================================
36
37 //______________________________________________________________________________
38 //
39 // Provide interface for loading and navigating standard AliRoot data
40 // (AliRunLoader) and ESDs.
41 //
42 // Missing support for raw-data. For now this is handled individually
43 // by each sub-detector.
44 //
45 // Also provides interface to magnetic-field and geometry. Mostly
46 // intended as wrappers over standard AliRoot functionality for
47 // convenient use from visualizateion macros.
48
49 ClassImp(AliEveEventManager)
50
51 AliEveEventManager* gAliEveEvent = 0;
52
53 Bool_t AliEveEventManager::fgAssertRunLoader = kFALSE;
54 Bool_t AliEveEventManager::fgAssertESD       = kFALSE;
55 Bool_t AliEveEventManager::fgAssertRaw       = kFALSE;
56
57 TString  AliEveEventManager::fgESDFileName("AliESDs.root");
58 TString  AliEveEventManager::fgRawFileName("raw.root");
59 TString  AliEveEventManager::fgCdbUri("local://$ALICE_ROOT");
60
61 AliMagF* AliEveEventManager::fgMagField = 0;
62
63
64 AliEveEventManager::AliEveEventManager() :
65   TEveEventManager(),
66
67   fPath      ( ), fEventId (-1),
68   fRunLoader (0),
69   fESDFile   (0), fESDTree (0), fESD (0),
70   fESDfriend (0), fESDfriendExists(kFALSE),
71   fRawReader (0),
72   fAutoLoad(kFALSE),
73   fAutoLoadTime(5.),
74   fAutoLoadTimer(0),
75   fIsOnline(kFALSE)
76 {
77   // Default constructor.
78 }
79
80 AliEveEventManager::AliEveEventManager(TString path, Int_t ev) :
81   TEveEventManager("AliEVE AliEveEventManager"),
82
83   fPath   (path), fEventId(-1),
84   fRunLoader (0),
85   fESDFile   (0), fESDTree (0), fESD (0),
86   fESDfriend (0), fESDfriendExists(kFALSE),
87   fRawReader (0),
88   fAutoLoad(kFALSE),
89   fAutoLoadTime(5.),
90   fAutoLoadTimer(0),
91   fIsOnline(kFALSE)
92 {
93   // Constructor with event-directory URL and event-id.
94
95   Open();
96   if (ev >= 0) GotoEvent(ev);
97 }
98
99 AliEveEventManager::~AliEveEventManager()
100 {
101   // Destructor.
102
103   if (fAutoLoadTimer) delete fAutoLoadTimer;
104   // Somewhat unclear what to do here.
105   // In principle should close all data sources and deregister from
106   // TEveManager.
107 }
108
109 /******************************************************************************/
110
111 void AliEveEventManager::SetESDFileName(const Text_t* esd)
112 {
113   // Set file-name for opening ESD, default "AliESDs.root".
114
115   if (esd) fgESDFileName = esd;
116 }
117
118 void AliEveEventManager::SetRawFileName(const Text_t* raw)
119 {
120   // Set file-name for opening of raw-data, default "raw.root"
121   if (raw) fgRawFileName = raw;
122 }
123
124 void AliEveEventManager::SetCdbUri(const Text_t* cdb)
125 {
126   // Set path to CDB, default "local://$ALICE_ROOT".
127
128   if (cdb) fgCdbUri = cdb;
129 }
130
131 void AliEveEventManager::SetAssertElements(Bool_t assertRunloader,
132                                            Bool_t assertEsd,
133                                            Bool_t assertRaw)
134 {
135   // Set global flags that detrmine which parts of the event-data must
136   // be present when the event is opened.
137
138   fgAssertRunLoader = assertRunloader;
139   fgAssertESD = assertEsd;
140   fgAssertRaw = assertRaw;
141 }
142
143 /******************************************************************************/
144
145 void AliEveEventManager::Open()
146 {
147   // Open event-data from URL specified in fPath.
148   // Attempts to create AliRunLoader() and to open ESD with ESDfriends.
149   // Warning is reported if run-loader or ESD is not found.
150   // Global data-members fgAssertRunLoader and fgAssertESD can be set
151   // to throw exceptions instead.
152
153   static const TEveException kEH("AliEveEventManager::Open ");
154
155   gSystem->ExpandPathName(fPath);
156   // The following magick is required for ESDriends to be loaded properly
157   // from non-current directory.
158   if (fPath.IsNull() || fPath == ".")
159   {
160     fPath = gSystem->WorkingDirectory();
161   }
162   else if ( ! fPath.BeginsWith("file:/"))
163   {
164     TUrl    url(fPath, kTRUE);
165     TString protocol(url.GetProtocol());
166     if (protocol == "file" && fPath[0] != '/')
167       fPath = Form("%s/%s", gSystem->WorkingDirectory(), fPath.Data());
168   }
169
170   Int_t runNo = -1;
171
172   TString gaPath(Form("%s/galice.root", fPath.Data()));
173   // If i use open directly, we get fatal.
174   // Is this (AccessPathName check) ok for xrootd / alien?
175   if (gSystem->AccessPathName(gaPath, kReadPermission) == kFALSE)
176   {
177     fRunLoader = AliRunLoader::Open(gaPath);
178     if (fRunLoader)
179     {
180       TString alicePath = fPath + "/";
181       fRunLoader->SetDirName(alicePath);
182
183       if (fRunLoader->LoadgAlice() != 0)
184         Warning(kEH, "failed loading gAlice via run-loader.");
185
186       if (fRunLoader->LoadHeader() == 0)
187       {
188         runNo = fRunLoader->GetHeader()->GetRun();
189       }
190       else
191       {
192         Warning(kEH, "failed loading run-loader's header.");
193         delete fRunLoader;
194         fRunLoader = 0;
195       }
196     }
197     else // run-loader open failed
198     {
199       Warning(kEH, "failed opening ALICE run-loader from '%s'.", gaPath.Data());
200     }
201   }
202   else // galice not readable
203   {
204     Warning(kEH, "can not read '%s'.", gaPath.Data());
205   }
206   if (fRunLoader == 0)
207   {
208     if (fgAssertRunLoader)
209       throw (kEH + "Bootstraping of run-loader failed. Its precence was requested.");
210     else
211       Warning(kEH, "Bootstraping of run-loader failed.");
212   }
213
214
215   TString esdPath(Form("%s/%s", fPath.Data(), fgESDFileName.Data()));
216   if ((fESDFile = TFile::Open(esdPath)))
217   {
218     fESD = new AliESDEvent();
219     fESDTree = (TTree*) fESDFile->Get("esdTree");
220     if (fESDTree != 0)
221     {
222       fESD->ReadFromTree(fESDTree);
223       fESDTree->GetEntry(0);
224       runNo = fESD->GetESDRun()->GetRunNumber();
225
226       // Check if ESDfriends exists and attach the branch
227       TString p(Form("%s/AliESDfriends.root", fPath.Data()));
228       if (gSystem->AccessPathName(p, kReadPermission) == kFALSE)
229       {
230         fESDfriendExists = kTRUE;
231         fESDTree->SetBranchStatus ("ESDfriend*", 1);
232         fESDTree->SetBranchAddress("ESDfriend.", &fESDfriend);
233       }
234     }
235     else // esdtree == 0
236     {
237       delete fESDFile; fESDFile = 0;
238       Warning(kEH, "failed getting the esdTree.");
239     }
240   }
241   else // esd not readable
242   {
243     Warning(kEH, "can not read ESD file '%s'.", esdPath.Data());
244   }
245   if (fESDTree == 0)
246   {
247     if (fgAssertESD)
248     {
249       throw (kEH + "ESD not initialized. Its precence was requested.");
250     } else {
251       Warning(kEH, "ESD not initialized.");
252     }
253   }
254
255   TString rawPath(Form("%s/%s", fPath.Data(), fgRawFileName.Data()));
256   // If i use open directly, raw-reader reports an error but i have
257   // no way to detect it.
258   // Is this (AccessPathName check) ok for xrootd / alien?
259   if (gSystem->AccessPathName(rawPath, kReadPermission) == kFALSE)
260   {
261     if (fgRawFileName.EndsWith("/"))
262     {
263       fRawReader = new AliRawReaderFile(rawPath);
264     }
265     else if (fgRawFileName.EndsWith(".root"))
266     {
267       fRawReader = new AliRawReaderRoot(rawPath);
268     }
269     else if (!fgRawFileName.IsNull())
270     {
271       fRawReader = new AliRawReaderDate(rawPath);
272     } 
273   }
274
275   if (fRawReader == 0)
276   {
277     if (fgAssertRaw)
278     {
279       throw (kEH + "raw-data not initialized. Its precence was requested.");
280     } else {
281       Warning(kEH, "raw-data not initialized.");
282     }
283   }
284
285   if (runNo < 0)
286   {
287     if (fRawReader)
288     {
289       fRawReader->NextEvent();
290       runNo = fRawReader->GetRunNumber();
291       printf("Determining run-no from raw ... run=%d\n", runNo);
292       fRawReader->RewindEvents();
293     } else {
294       throw (kEH + "unknown run number.");
295     }
296   }
297
298   {
299     AliCDBManager* cdb = AliCDBManager::Instance();
300     cdb->SetDefaultStorage(fgCdbUri);
301     if (cdb->IsDefaultStorageSet() == kFALSE)
302       throw (kEH + "CDB initialization failed.");
303     cdb->SetRun(runNo);
304   }
305
306   SetName(Form("Event %d", fEventId));
307   SetTitle(fPath);
308 }
309
310 void AliEveEventManager::SetEvent(AliRunLoader *runLoader, AliRawReader *rawReader, AliESDEvent *esd)
311 {
312   // Set an event from an external source
313   // The method is used in the online visualisation
314   fRunLoader = runLoader;
315   fRawReader = rawReader;
316   fESD = esd;
317   fIsOnline = kTRUE;
318   SetTitle("Online event in memory");
319   SetName("Online Event");
320
321   ElementChanged();
322   AfterNewEventLoaded();
323 }
324
325 Int_t AliEveEventManager::GetMaxEventId(Bool_t refreshESD) const
326 {
327   // Returns maximum available event id.
328   // If raw-data is the only data-source this can not be known
329   // and 10,000,000 is returned.
330   // If neither data-source is initialised an exception is thrown.
331   // If refresh_esd is true and ESD is the primary event-data source
332   // its header is re-read from disk.
333
334   static const TEveException kEH("AliEveEventManager::GetMaxEventId ");
335
336   if (fRunLoader)
337   {
338     return fRunLoader->GetNumberOfEvents() - 1;
339   }
340   else if (fESDTree)
341   {
342     if (refreshESD)
343       fESDTree->Refresh();
344     return fESDTree->GetEntries() - 1;
345   }
346   else if (fRawReader)
347   {
348     return 10000000;
349   }
350   else
351   {
352     throw (kEH + "neither RunLoader, ESD nor Raw loaded.");
353   }
354 }
355
356 void AliEveEventManager::GotoEvent(Int_t event)
357 {
358   // Load data for specified event.
359   // If event is out of range an exception is thrown and old state
360   // is preserved.
361   // After successful loading of event, the virtual function
362   // AfterNewEventLoaded() is called. This executes commands that
363   // were registered via TEveEventManager::AddNewEventCommand().
364   //
365   // If event is negative, it is subtracted from the number of
366   // available events, thus passing -1 will load the last event.
367   // This is not supported when raw-data is the only data-source
368   // as the number of events is not known.
369
370   static const TEveException kEH("AliEveEventManager::GotoEvent ");
371
372   Int_t maxEvent = 0;
373   if (fRunLoader)
374   {
375     maxEvent = fRunLoader->GetNumberOfEvents() - 1;
376     if (event < 0)
377       event = fRunLoader->GetNumberOfEvents() + event;
378   }
379   else if (fESDTree)
380   {
381     fESDTree->Refresh();
382     maxEvent = fESDTree->GetEntries() - 1;
383     if (event < 0)
384       event = fESDTree->GetEntries() + event;
385   }
386   else if (fRawReader)
387   {
388     maxEvent = 10000000;
389     if (event < 0) {
390       Error(kEH, "negative event id passed for raw-data as source. Operation not supported.");
391       return;
392     }
393     Info(kEH, "number of events unknown for raw-data, setting max-event id to 10M.");
394   }
395   else
396   {
397     throw (kEH + "neither RunLoader, ESD nor Raw loaded.");
398   }
399   if (event < 0 || event > maxEvent)
400   {
401     throw (kEH + Form("event %d not present, available range [%d, %d].",
402                       event, 0, maxEvent));
403   }
404
405   TEveManager::TRedrawDisabler rd(gEve);
406   gEve->Redraw3D(kFALSE, kTRUE); // Enforce drop of all logicals.
407
408   // !!! MT this is somewhat brutal; at least optionally, one could be
409   // a bit gentler, checking for objs owning their external refs and having
410   // additinal parents.
411   DestroyElements();
412
413   if (fRunLoader) {
414     if (fRunLoader->GetEvent(event) != 0)
415       throw (kEH + "failed getting required event.");
416   }
417
418   if (fESDTree) {
419     if (fESDTree->GetEntry(event) <= 0)
420       throw (kEH + "failed getting required event from ESD.");
421
422     if (fESDfriendExists)
423       fESD->SetESDfriend(fESDfriend);
424   }
425
426   if (fRawReader)
427   {
428     Int_t rawEv = fEventId;
429     if (event < rawEv)
430     {
431       fRawReader->RewindEvents();
432       rawEv = -1;
433     }
434
435     while (rawEv < event)
436     {
437       if ( ! fRawReader->NextEvent())
438       {
439         fRawReader->RewindEvents();
440         fEventId = -1;
441         throw (kEH + Form("Error going to next raw-event from event %d.", rawEv));
442       }
443       ++rawEv;
444     }
445
446     printf ("Loaded raw-event %d.\n", rawEv);
447   }
448
449   fEventId = event;
450   SetName(Form("Event %d", fEventId));
451   ElementChanged();
452
453   AfterNewEventLoaded();
454 }
455
456 void AliEveEventManager::NextEvent()
457 {
458   // Loads next event
459   // either in automatic (online) or
460   // manual mode
461   
462   if (fIsOnline) {
463     if (fAutoLoadTimer) fAutoLoadTimer->Stop();
464
465     DestroyElements();
466
467     gSystem->ExitLoop();
468   }
469   else {
470     if (fEventId < GetMaxEventId(kTRUE))
471       GotoEvent(fEventId + 1);
472     else
473       GotoEvent(0);
474     StartStopAutoLoadTimer();
475   }
476 }
477
478 void AliEveEventManager::PrevEvent()
479 {
480   // Loads previous event
481   // only in case of manual mode
482   if (!fIsOnline) {
483     GotoEvent(fEventId - 1);
484     StartStopAutoLoadTimer();
485   }
486 }
487
488 void AliEveEventManager::Close()
489 {
490   // Close the event files.
491   // For the moment only ESD is closed. Needs to be investigated for
492   // AliRunLoader and Raw.
493
494   if (fESDTree) {
495     delete fESD;       fESD       = 0;
496     delete fESDfriend; fESDfriend = 0;
497
498     delete fESDTree; fESDTree = 0;
499     delete fESDFile; fESDFile = 0;
500   }
501 }
502
503
504 /******************************************************************************/
505 // Static convenience functions, mainly used from macros.
506 /******************************************************************************/
507
508 AliRunLoader* AliEveEventManager::AssertRunLoader()
509 {
510   // Make sure AliRunLoader is initialized and return it.
511   // Throws exception in case run-loader is not available.
512   // Static utility for macros.
513
514   static const TEveException kEH("AliEveEventManager::AssertRunLoader ");
515
516   if (gAliEveEvent == 0)
517     throw (kEH + "ALICE event not ready.");
518   if (gAliEveEvent->fRunLoader == 0)
519     throw (kEH + "AliRunLoader not initialised.");
520   return gAliEveEvent->fRunLoader;
521 }
522
523 AliESDEvent* AliEveEventManager::AssertESD()
524 {
525   // Make sure AliESDEvent is initialized and return it.
526   // Throws exception in case ESD is not available.
527   // Static utility for macros.
528
529   static const TEveException kEH("AliEveEventManager::AssertESD ");
530
531   if (gAliEveEvent == 0)
532     throw (kEH + "ALICE event not ready.");
533   if (gAliEveEvent->fESD == 0)
534     throw (kEH + "AliESD not initialised.");
535   return gAliEveEvent->fESD;
536 }
537
538 AliESDfriend* AliEveEventManager::AssertESDfriend()
539 {
540   // Make sure AliESDfriend is initialized and return it.
541   // Throws exception in case ESDfriend-loader is not available.
542   // Static utility for macros.
543
544   static const TEveException kEH("AliEveEventManager::AssertESDfriend ");
545
546   if (gAliEveEvent == 0)
547     throw (kEH + "ALICE event not ready.");
548   if (gAliEveEvent->fESDfriend == 0)
549     throw (kEH + "AliESDfriend not initialised.");
550   return gAliEveEvent->fESDfriend;
551 }
552
553 AliRawReader* AliEveEventManager::AssertRawReader()
554 {
555   // Make sure raw-reader is initialized and return it.
556
557   static const TEveException kEH("AliEveEventManager::AssertRawReader ");
558
559   if (gAliEveEvent == 0)
560     throw (kEH + "ALICE event not ready.");
561   if (gAliEveEvent->fRawReader == 0)
562     throw (kEH + "RawReader not ready.");
563
564   return gAliEveEvent->fRawReader;
565 }
566
567 AliMagF* AliEveEventManager::AssertMagField()
568 {
569   // Make sure AliMagF is initialized and return it.
570   // Throws exception in case magnetic field is not available.
571   // Static utility for macros.
572
573   if (fgMagField == 0)
574   {
575     if (gAliEveEvent && gAliEveEvent->fRunLoader && gAliEveEvent->fRunLoader->GetAliRun())
576       fgMagField = gAliEveEvent->fRunLoader->GetAliRun()->Field();
577     else
578       fgMagField = new AliMagFMaps("Maps","Maps", 1, 1., 10., AliMagFMaps::k5kG);
579   }
580   return fgMagField;
581 }
582
583 TGeoManager* AliEveEventManager::AssertGeometry()
584 {
585   // Make sure AliGeomManager is initialized and returns the
586   // corresponding TGeoManger.
587   // gGeoManager is set to the return value.
588   // Throws exception if geometry can not be loaded or if it is not
589   // available and the TGeoManager is locked.
590   // Static utility for macros.
591
592   static const TEveException kEH("AliEveEventManager::AssertGeometry ");
593
594   if (AliGeomManager::GetGeometry() == 0)
595   {
596     if (TGeoManager::IsLocked())
597       throw (kEH + "geometry is not loaded but TGeoManager is locked.");
598
599     gGeoManager = 0;
600     AliGeomManager::LoadGeometry();
601     if ( ! AliGeomManager::GetGeometry())
602     {
603       throw (kEH + "can not load geometry.");
604     }
605     if ( ! AliGeomManager::ApplyAlignObjsFromCDB("ITS TPC TRD TOF PHOS HMPID EMCAL MUON FMD ZDC PMD T0 VZERO ACORDE"))
606     {
607       ::Warning(kEH, "mismatch of alignable volumes. Proceeding.");
608       // throw (kEH + "could not apply align objs.");
609     }
610     AliGeomManager::GetGeometry()->DefaultColors();
611   }
612
613   gGeoManager = AliGeomManager::GetGeometry();
614   return gGeoManager;
615 }
616
617 void AliEveEventManager::SetAutoLoad(Bool_t autoLoad)
618 {
619   // Set the automatic event loading mode
620   fAutoLoad = autoLoad;
621   StartStopAutoLoadTimer();
622 }
623
624 void AliEveEventManager::SetAutoLoadTime(Double_t time)
625 {
626   // Set the auto-load time in seconds
627   fAutoLoadTime = time;
628   StartStopAutoLoadTimer();
629 }
630
631 void AliEveEventManager::StartStopAutoLoadTimer()
632 {
633   // Create if needed and start
634   // the automatic event loading timer
635   if (fAutoLoad) {
636     if (!fAutoLoadTimer) {
637       fAutoLoadTimer = new TTimer;
638       fAutoLoadTimer->Connect("Timeout()","AliEveEventManager",this,"NextEvent()");
639     }
640     fAutoLoadTimer->Start((Long_t)fAutoLoadTime*1000,kTRUE);
641   }
642   else {
643     if (fAutoLoadTimer) fAutoLoadTimer->Stop();
644   }
645 }
646
647 const char* AliEveEventManager::GetEventInfo() const
648 {
649   // Dumps the event-header contents
650
651   static TString eventInfo;
652
653   if (!fRawReader) {
654     eventInfo.Form("No raw-data event info is available!\n");
655   }
656   else {
657     const UInt_t* attr = fRawReader->GetAttributes();
658     eventInfo.Form("Raw-data event info:\nRun#: %d\nEvent type: %d (%s)\nPeriod: %x\nOrbit: %x   BC: %x\nTrigger: %llx\nDetectors: %x (%s)\nAttributes:%x-%x-%x\nTimestamp: %x\n",
659                    fRawReader->GetRunNumber(),fRawReader->GetType(),AliRawEventHeaderBase::GetTypeName(fRawReader->GetType()),
660                    fRawReader->GetPeriod(),fRawReader->GetOrbitID(),fRawReader->GetBCID(),
661                    fRawReader->GetClassMask(),
662                    *fRawReader->GetDetectorPattern(),AliDAQ::ListOfTriggeredDetectors(*fRawReader->GetDetectorPattern()),
663                    attr[0],attr[1],attr[2],
664                    fRawReader->GetTimestamp());
665   }
666   if (!fESD) {
667     eventInfo.Append(Form("\nNo ESD event info is available!\n"));
668   }
669   else {
670     TString acttrclasses = fESD->GetESDRun()->GetActiveTriggerClasses();
671     TString firedtrclasses = fESD->GetFiredTriggerClasses();
672     eventInfo.Append(Form("\nESD event info:\nRun#: %d\nActive trigger classes: %s\nEvent type: %d (%s)\nPeriod: %x\nOrbit: %x   BC: %x\nTrigger: %llx (%s)\nEvent# in file:%d\nTimestamp: %x\n",
673                           fESD->GetRunNumber(),
674                           acttrclasses.Data(),
675                           fESD->GetEventType(),AliRawEventHeaderBase::GetTypeName(fESD->GetEventType()),
676                           fESD->GetPeriodNumber(),fESD->GetOrbitNumber(),fESD->GetBunchCrossNumber(),
677                           fESD->GetTriggerMask(),firedtrclasses.Data(),
678                           fESD->GetEventNumberInFile(),
679                           fESD->GetTimeStamp()));
680   }
681
682   return eventInfo.Data();
683 }
684