1 /**************************************************************************
2 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
4 * Author: The ALICE Off-line Project. *
5 * Contributors are mentioned in the code where appropriate. *
7 * Permission to use, copy, modify and distribute this software and its *
8 * documentation strictly for non-commercial purposes is hereby granted *
9 * without fee, provided that the above copyright notice appears in all *
10 * copies and that both the copyright notice and this permission notice *
11 * appear in the supporting documentation. The authors make no claims *
12 * about the suitability of this software for any purpose. It is *
13 * provided "as is" without express or implied warranty. *
14 **************************************************************************/
17 // Author: Andrei Gheata, 31/05/2006
19 //==============================================================================
20 // AliAnalysysManager - Manager analysis class. Allows creation of several
21 // analysis tasks and data containers storing their input/output. Allows
22 // connecting/chaining tasks via shared data containers. Serializes the current
23 // event for all tasks depending only on initial input data.
24 //==============================================================================
26 //==============================================================================
28 #include <Riostream.h>
36 #include <TMethodCall.h>
41 #include <TStopwatch.h>
43 #include "AliAnalysisSelector.h"
44 #include "AliAnalysisGrid.h"
45 #include "AliAnalysisTask.h"
46 #include "AliAnalysisDataContainer.h"
47 #include "AliAnalysisDataSlot.h"
48 #include "AliVEventHandler.h"
49 #include "AliVEventPool.h"
50 #include "AliSysInfo.h"
51 #include "AliAnalysisManager.h"
53 ClassImp(AliAnalysisManager)
55 AliAnalysisManager *AliAnalysisManager::fgAnalysisManager = NULL;
56 TString AliAnalysisManager::fgCommonFileName = "";
58 //______________________________________________________________________________
59 AliAnalysisManager::AliAnalysisManager(const char *name, const char *title)
62 fInputEventHandler(NULL),
63 fOutputEventHandler(NULL),
64 fMCtruthEventHandler(NULL),
68 fMode(kLocalAnalysis),
72 fSpecialOutputLocation(""),
85 fAutoBranchHandling(kTRUE),
88 // Default constructor.
89 fgAnalysisManager = this;
90 fgCommonFileName = "AnalysisResults.root";
91 fTasks = new TObjArray();
92 fTopTasks = new TObjArray();
93 fZombies = new TObjArray();
94 fContainers = new TObjArray();
95 fInputs = new TObjArray();
96 fOutputs = new TObjArray();
97 fParamCont = new TObjArray();
99 TObject::SetObjectStat(kFALSE);
102 //______________________________________________________________________________
103 AliAnalysisManager::AliAnalysisManager(const AliAnalysisManager& other)
106 fInputEventHandler(NULL),
107 fOutputEventHandler(NULL),
108 fMCtruthEventHandler(NULL),
113 fInitOK(other.fInitOK),
114 fIsRemote(other.fIsRemote),
115 fDebug(other.fDebug),
116 fSpecialOutputLocation(""),
129 fAutoBranchHandling(other.fAutoBranchHandling),
133 fTasks = new TObjArray(*other.fTasks);
134 fTopTasks = new TObjArray(*other.fTopTasks);
135 fZombies = new TObjArray(*other.fZombies);
136 fContainers = new TObjArray(*other.fContainers);
137 fInputs = new TObjArray(*other.fInputs);
138 fOutputs = new TObjArray(*other.fOutputs);
139 fParamCont = new TObjArray(*other.fParamCont);
140 fgCommonFileName = "AnalysisResults.root";
141 fgAnalysisManager = this;
142 TObject::SetObjectStat(kFALSE);
145 //______________________________________________________________________________
146 AliAnalysisManager& AliAnalysisManager::operator=(const AliAnalysisManager& other)
149 if (&other != this) {
150 TNamed::operator=(other);
151 fInputEventHandler = other.fInputEventHandler;
152 fOutputEventHandler = other.fOutputEventHandler;
153 fMCtruthEventHandler = other.fMCtruthEventHandler;
154 fEventPool = other.fEventPool;
157 fNSysInfo = other.fNSysInfo;
159 fInitOK = other.fInitOK;
160 fIsRemote = other.fIsRemote;
161 fDebug = other.fDebug;
162 fTasks = new TObjArray(*other.fTasks);
163 fTopTasks = new TObjArray(*other.fTopTasks);
164 fZombies = new TObjArray(*other.fZombies);
165 fContainers = new TObjArray(*other.fContainers);
166 fInputs = new TObjArray(*other.fInputs);
167 fOutputs = new TObjArray(*other.fOutputs);
168 fParamCont = new TObjArray(*other.fParamCont);
170 fCommonOutput = NULL;
173 fExtraFiles = other.fExtraFiles;
174 fgCommonFileName = "AnalysisResults.root";
175 fgAnalysisManager = this;
176 fAutoBranchHandling = other.fAutoBranchHandling;
177 fTable.Clear("nodelete");
182 //______________________________________________________________________________
183 AliAnalysisManager::~AliAnalysisManager()
186 if (fTasks) {fTasks->Delete(); delete fTasks;}
187 if (fTopTasks) delete fTopTasks;
188 if (fZombies) delete fZombies;
189 if (fContainers) {fContainers->Delete(); delete fContainers;}
190 if (fInputs) delete fInputs;
191 if (fOutputs) delete fOutputs;
192 if (fParamCont) delete fParamCont;
193 if (fGridHandler) delete fGridHandler;
194 if (fInputEventHandler) delete fInputEventHandler;
195 if (fOutputEventHandler) delete fOutputEventHandler;
196 if (fMCtruthEventHandler) delete fMCtruthEventHandler;
197 if (fEventPool) delete fEventPool;
198 if (fgAnalysisManager==this) fgAnalysisManager = NULL;
199 TObject::SetObjectStat(kTRUE);
202 //______________________________________________________________________________
203 Int_t AliAnalysisManager::GetEntry(Long64_t entry, Int_t getall)
205 // Read one entry of the tree or a whole branch.
206 fCurrentEntry = entry;
207 if (!fAutoBranchHandling)
209 return fTree ? fTree->GetTree()->GetEntry(entry, getall) : 0;
212 //______________________________________________________________________________
213 Bool_t AliAnalysisManager::Init(TTree *tree)
215 // The Init() function is called when the selector needs to initialize
216 // a new tree or chain. Typically here the branch addresses of the tree
217 // will be set. It is normaly not necessary to make changes to the
218 // generated code, but the routine can be extended by the user if needed.
219 // Init() will be called many times when running with PROOF.
220 Bool_t init = kFALSE;
221 if (!tree) return kFALSE; // Should not happen - protected in selector caller
223 printf("->AliAnalysisManager::Init(%s)\n", tree->GetName());
225 // Call InitTree of EventHandler
226 if (fOutputEventHandler) {
227 if (fMode == kProofAnalysis) {
228 init = fOutputEventHandler->Init(0x0, "proof");
230 init = fOutputEventHandler->Init(0x0, "local");
233 Error("Init", "Output event handler failed to initialize");
238 if (fInputEventHandler) {
239 if (fMode == kProofAnalysis) {
240 init = fInputEventHandler->Init(tree, "proof");
242 init = fInputEventHandler->Init(tree, "local");
245 Error("Init", "Input event handler failed to initialize tree");
249 // If no input event handler we need to get the tree once
251 if(!tree->GetTree()) {
252 Long64_t readEntry = tree->LoadTree(0);
253 if (readEntry == -2) {
254 Error("Init", "Input tree has no entry. Exiting");
260 if (fMCtruthEventHandler) {
261 if (fMode == kProofAnalysis) {
262 init = fMCtruthEventHandler->Init(0x0, "proof");
264 init = fMCtruthEventHandler->Init(0x0, "local");
267 Error("Init", "MC event handler failed to initialize");
272 if (!fInitOK) InitAnalysis();
273 if (!fInitOK) return kFALSE;
276 AliAnalysisDataContainer *top = fCommonInput;
277 if (!top) top = (AliAnalysisDataContainer*)fInputs->At(0);
279 Error("Init","No top input container !");
284 printf("<-AliAnalysisManager::Init(%s)\n", tree->GetName());
289 //______________________________________________________________________________
290 void AliAnalysisManager::SlaveBegin(TTree *tree)
292 // The SlaveBegin() function is called after the Begin() function.
293 // When running with PROOF SlaveBegin() is called on each slave server.
294 // The tree argument is deprecated (on PROOF 0 is passed).
295 if (fDebug > 1) printf("->AliAnalysisManager::SlaveBegin()\n");
296 static Bool_t isCalled = kFALSE;
297 Bool_t init = kFALSE;
298 Bool_t initOK = kTRUE;
300 TDirectory *curdir = gDirectory;
301 // Call SlaveBegin only once in case of mixing
302 if (isCalled && fMode==kMixingAnalysis) return;
304 // Call Init of EventHandler
305 if (fOutputEventHandler) {
306 if (fMode == kProofAnalysis) {
307 // Merging AOD's in PROOF via TProofOutputFile
308 if (fDebug > 1) printf(" Initializing AOD output file %s...\n", fOutputEventHandler->GetOutputFileName());
309 init = fOutputEventHandler->Init("proof");
310 if (!init) msg = "Failed to initialize output handler on worker";
312 init = fOutputEventHandler->Init("local");
313 if (!init) msg = "Failed to initialize output handler";
316 if (!fSelector) Error("SlaveBegin", "Selector not set");
317 else if (!init) {fSelector->Abort(msg); fSelector->SetStatus(-1);}
320 if (fInputEventHandler) {
321 fInputEventHandler->SetInputTree(tree);
322 if (fMode == kProofAnalysis) {
323 init = fInputEventHandler->Init("proof");
324 if (!init) msg = "Failed to initialize input handler on worker";
326 init = fInputEventHandler->Init("local");
327 if (!init) msg = "Failed to initialize input handler";
330 if (!fSelector) Error("SlaveBegin", "Selector not set");
331 else if (!init) {fSelector->Abort(msg); fSelector->SetStatus(-1);}
334 if (fMCtruthEventHandler) {
335 if (fMode == kProofAnalysis) {
336 init = fMCtruthEventHandler->Init("proof");
337 if (!init) msg = "Failed to initialize MC handler on worker";
339 init = fMCtruthEventHandler->Init("local");
340 if (!init) msg = "Failed to initialize MC handler";
343 if (!fSelector) Error("SlaveBegin", "Selector not set");
344 else if (!init) {fSelector->Abort(msg); fSelector->SetStatus(-1);}
346 if (curdir) curdir->cd();
350 AliAnalysisTask *task;
351 // Call CreateOutputObjects for all tasks
352 Bool_t getsysInfo = ((fNSysInfo>0) && (fMode==kLocalAnalysis))?kTRUE:kFALSE;
353 Bool_t dirStatus = TH1::AddDirectoryStatus();
355 while ((task=(AliAnalysisTask*)next())) {
357 // Start with memory as current dir and make sure by default histograms do not get attached to files.
358 TH1::AddDirectory(kFALSE);
359 task->CreateOutputObjects();
360 if (getsysInfo) AliSysInfo::AddStamp(Form("%s_CREATEOUTOBJ",task->ClassName()), 0, itask, 0);
363 TH1::AddDirectory(dirStatus);
364 if (curdir) curdir->cd();
365 if (fDebug > 1) printf("<-AliAnalysisManager::SlaveBegin()\n");
368 //______________________________________________________________________________
369 Bool_t AliAnalysisManager::Notify()
371 // The Notify() function is called when a new file is opened. This
372 // can be either for a new TTree in a TChain or when when a new TTree
373 // is started when using PROOF. It is normaly not necessary to make changes
374 // to the generated code, but the routine can be extended by the
375 // user if needed. The return value is currently not used.
376 if (!fTree) return kFALSE;
378 fTable.Clear("nodelete"); // clearing the hash table may not be needed -> C.L.
379 if (fMode == kProofAnalysis) fIsRemote = kTRUE;
381 TFile *curfile = fTree->GetCurrentFile();
383 Error("Notify","No current file");
387 if (fDebug > 1) printf("->AliAnalysisManager::Notify() file: %s\n", curfile->GetName());
389 AliAnalysisTask *task;
390 // Call Notify for all tasks
391 while ((task=(AliAnalysisTask*)next()))
394 // Call Notify of the event handlers
395 if (fInputEventHandler) {
396 fInputEventHandler->Notify(curfile->GetName());
399 if (fOutputEventHandler) {
400 fOutputEventHandler->Notify(curfile->GetName());
403 if (fMCtruthEventHandler) {
404 fMCtruthEventHandler->Notify(curfile->GetName());
407 if (fDebug > 1) printf("<-AliAnalysisManager::Notify()\n");
411 //______________________________________________________________________________
412 Bool_t AliAnalysisManager::Process(Long64_t entry)
414 // The Process() function is called for each entry in the tree (or possibly
415 // keyed object in the case of PROOF) to be processed. The entry argument
416 // specifies which entry in the currently loaded tree is to be processed.
417 // It can be passed to either TTree::GetEntry() or TBranch::GetEntry()
418 // to read either all or the required parts of the data. When processing
419 // keyed objects with PROOF, the object is already loaded and is available
420 // via the fObject pointer.
422 // This function should contain the "body" of the analysis. It can contain
423 // simple or elaborate selection criteria, run algorithms on the data
424 // of the event and typically fill histograms.
426 // WARNING when a selector is used with a TChain, you must use
427 // the pointer to the current TTree to call GetEntry(entry).
428 // The entry is always the local entry number in the current tree.
429 // Assuming that fChain is the pointer to the TChain being processed,
430 // use fChain->GetTree()->GetEntry(entry).
431 if (fDebug > 1) printf("->AliAnalysisManager::Process(%lld)\n", entry);
433 if (fInputEventHandler) fInputEventHandler ->BeginEvent(entry);
434 if (fOutputEventHandler) fOutputEventHandler ->BeginEvent(entry);
435 if (fMCtruthEventHandler) fMCtruthEventHandler->BeginEvent(entry);
439 if (fDebug > 1) printf("<-AliAnalysisManager::Process()\n");
443 //______________________________________________________________________________
444 void AliAnalysisManager::PackOutput(TList *target)
446 // Pack all output data containers in the output list. Called at SlaveTerminate
447 // stage in PROOF case for each slave.
448 if (fDebug > 1) printf("->AliAnalysisManager::PackOutput()\n");
450 Error("PackOutput", "No target. Exiting.");
453 TDirectory *cdir = gDirectory;
455 if (fInputEventHandler) fInputEventHandler ->Terminate();
456 if (fOutputEventHandler) fOutputEventHandler ->Terminate();
457 if (fMCtruthEventHandler) fMCtruthEventHandler->Terminate();
460 // Call FinishTaskOutput() for each event loop task (not called for
461 // post-event loop tasks - use Terminate() fo those)
462 TIter nexttask(fTasks);
463 AliAnalysisTask *task;
464 while ((task=(AliAnalysisTask*)nexttask())) {
465 if (!task->IsPostEventLoop()) {
466 if (fDebug > 1) printf("->FinishTaskOutput: task %s\n", task->GetName());
467 task->FinishTaskOutput();
469 if (fDebug > 1) printf("<-FinishTaskOutput: task %s\n", task->GetName());
473 if (fMode == kProofAnalysis) {
474 TIter next(fOutputs);
475 AliAnalysisDataContainer *output;
476 Bool_t isManagedByHandler = kFALSE;
477 while ((output=(AliAnalysisDataContainer*)next())) {
478 // Do not consider outputs of post event loop tasks
479 isManagedByHandler = kFALSE;
480 if (output->GetProducer()->IsPostEventLoop()) continue;
481 const char *filename = output->GetFileName();
482 if (!(strcmp(filename, "default")) && fOutputEventHandler) {
483 isManagedByHandler = kTRUE;
484 printf("#### Handler output. Extra: %s\n", fExtraFiles.Data());
485 filename = fOutputEventHandler->GetOutputFileName();
487 // Check if data was posted to this container. If not, issue an error.
488 if (!output->GetData() && !isManagedByHandler) {
489 Error("PackOutput", "No data for output container %s. Forgot to PostData ?", output->GetName());
492 if (!output->IsSpecialOutput()) {
494 if (strlen(filename) && !isManagedByHandler) {
495 // Backup current folder
496 TDirectory *opwd = gDirectory;
497 // File resident outputs.
498 // Check first if the file exists.
499 TString openoption = "RECREATE";
500 if (!gSystem->AccessPathName(output->GetFileName())) openoption = "UPDATE";
501 TFile *file = AliAnalysisManager::OpenFile(output, openoption, kTRUE);
502 // Save data to file, then close.
503 if (output->GetData()->InheritsFrom(TCollection::Class())) {
504 // If data is a collection, we set the name of the collection
505 // as the one of the container and we save as a single key.
506 TCollection *coll = (TCollection*)output->GetData();
507 coll->SetName(output->GetName());
508 coll->Write(output->GetName(), TObject::kSingleKey);
510 if (output->GetData()->InheritsFrom(TTree::Class())) {
511 TTree *tree = (TTree*)output->GetData();
512 // Check if tree is in memory
513 if (tree->GetDirectory()==gROOT) tree->SetDirectory(gDirectory);
516 output->GetData()->Write();
519 if (fDebug > 1) printf("PackOutput %s: memory merge, file resident output\n", output->GetName());
521 printf(" file %s listing content:\n", filename);
524 // Clear file list to release object ownership to user.
527 output->SetFile(NULL);
528 // Restore current directory
529 if (opwd) opwd->cd();
531 // Memory-resident outputs
532 if (fDebug > 1) printf("PackOutput %s: memory merge memory resident output\n", filename);
534 AliAnalysisDataWrapper *wrap = 0;
535 if (isManagedByHandler) {
536 wrap = new AliAnalysisDataWrapper(fOutputEventHandler->GetTree());
537 wrap->SetName(output->GetName());
539 else wrap =output->ExportData();
540 // Output wrappers must NOT delete data after merging - the user owns them
541 wrap->SetDeleteData(kFALSE);
544 // Special outputs. The file must be opened and connected to the container.
545 TDirectory *opwd = gDirectory;
546 TFile *file = output->GetFile();
548 AliAnalysisTask *producer = output->GetProducer();
550 "File %s for special container %s was NOT opened in %s::CreateOutputObjects !!!",
551 output->GetFileName(), output->GetName(), producer->ClassName());
554 TString outFilename = file->GetName();
555 if (fDebug > 1) printf("PackOutput %s: special output\n", output->GetName());
556 if (isManagedByHandler) {
557 // Terminate IO for files managed by the output handler
558 // file->Write() moved to AOD handler (A.G. 11.01.10)
559 // if (file) file->Write();
560 if (file && fDebug > 2) {
561 printf(" handled file %s listing content:\n", file->GetName());
564 fOutputEventHandler->TerminateIO();
567 // Release object ownership to users after writing data to file
568 if (output->GetData()->InheritsFrom(TCollection::Class())) {
569 // If data is a collection, we set the name of the collection
570 // as the one of the container and we save as a single key.
571 TCollection *coll = (TCollection*)output->GetData();
572 coll->SetName(output->GetName());
573 coll->Write(output->GetName(), TObject::kSingleKey);
575 if (output->GetData()->InheritsFrom(TTree::Class())) {
576 TTree *tree = (TTree*)output->GetData();
577 tree->SetDirectory(file);
580 output->GetData()->Write();
584 printf(" file %s listing content:\n", output->GetFileName());
587 // Clear file list to release object ownership to user.
590 output->SetFile(NULL);
592 // Restore current directory
593 if (opwd) opwd->cd();
594 // Check if a special output location was provided or the output files have to be merged
595 if (strlen(fSpecialOutputLocation.Data())) {
596 TString remote = fSpecialOutputLocation;
598 Int_t gid = gROOT->ProcessLine("gProofServ->GetGroupId();");
599 if (remote.BeginsWith("alien://")) {
600 gROOT->ProcessLine("TGrid::Connect(\"alien://pcapiserv01.cern.ch:10000\", gProofServ->GetUser());");
601 remote += outFilename;
602 remote.ReplaceAll(".root", Form("_%d.root", gid));
604 remote += Form("%s_%d_", gSystem->HostName(), gid);
605 remote += outFilename;
608 Info("PackOutput", "Output file for container %s to be copied \n at: %s. No merging.",
609 output->GetName(), remote.Data());
610 TFile::Cp ( outFilename.Data(), remote.Data() );
611 // Copy extra outputs
612 if (fExtraFiles.Length() && isManagedByHandler) {
613 TObjArray *arr = fExtraFiles.Tokenize(" ");
615 TIter nextfilename(arr);
616 while ((os=(TObjString*)nextfilename())) {
617 outFilename = os->GetString();
618 remote = fSpecialOutputLocation;
620 if (remote.BeginsWith("alien://")) {
621 remote += outFilename;
622 remote.ReplaceAll(".root", Form("_%d.root", gid));
624 remote += Form("%s_%d_", gSystem->HostName(), gid);
625 remote += outFilename;
628 Info("PackOutput", "Extra AOD file %s to be copied \n at: %s. No merging.",
629 outFilename.Data(), remote.Data());
630 TFile::Cp ( outFilename.Data(), remote.Data() );
635 // No special location specified-> use TProofOutputFile as merging utility
636 // The file at this output slot must be opened in CreateOutputObjects
637 if (fDebug > 1) printf(" File for container %s to be merged via file merger...\n", output->GetName());
643 if (fDebug > 1) printf("<-AliAnalysisManager::PackOutput: output list contains %d containers\n", target->GetSize());
646 //______________________________________________________________________________
647 void AliAnalysisManager::ImportWrappers(TList *source)
649 // Import data in output containers from wrappers coming in source.
650 if (fDebug > 1) printf("->AliAnalysisManager::ImportWrappers()\n");
651 TIter next(fOutputs);
652 AliAnalysisDataContainer *cont;
653 AliAnalysisDataWrapper *wrap;
655 Bool_t inGrid = (fMode == kGridAnalysis)?kTRUE:kFALSE;
656 TDirectory *cdir = gDirectory;
657 while ((cont=(AliAnalysisDataContainer*)next())) {
659 if (cont->GetProducer() && cont->GetProducer()->IsPostEventLoop() && !inGrid) continue;
660 if (cont->IsRegisterDataset()) continue;
661 const char *filename = cont->GetFileName();
662 Bool_t isManagedByHandler = kFALSE;
663 if (!(strcmp(filename, "default")) && fOutputEventHandler) {
664 isManagedByHandler = kTRUE;
665 filename = fOutputEventHandler->GetOutputFileName();
667 if (cont->IsSpecialOutput() || inGrid) {
668 if (strlen(fSpecialOutputLocation.Data())) continue;
669 // Copy merged file from PROOF scratch space.
670 // In case of grid the files are already in the current directory.
672 if (isManagedByHandler && fExtraFiles.Length()) {
673 // Copy extra registered dAOD files.
674 TObjArray *arr = fExtraFiles.Tokenize(" ");
676 TIter nextfilename(arr);
677 while ((os=(TObjString*)nextfilename())) GetFileFromWrapper(os->GetString(), source);
680 if (!GetFileFromWrapper(filename, source)) continue;
682 // Normally we should connect data from the copied file to the
683 // corresponding output container, but it is not obvious how to do this
684 // automatically if several objects in file...
685 TFile *f = (TFile*)gROOT->GetListOfFiles()->FindObject(filename);
686 if (!f) f = TFile::Open(filename, "READ");
688 Error("ImportWrappers", "Cannot open file %s in read-only mode", filename);
692 // Cd to the directory pointed by the container
693 TString folder = cont->GetFolderName();
694 if (!folder.IsNull()) f->cd(folder);
695 // Try to fetch first an object having the container name.
696 obj = gDirectory->Get(cont->GetName());
698 Warning("ImportWrappers", "Could not import object for container %s in file %s:%s.\n Object will not be available in Terminate()",
699 cont->GetName(), filename, cont->GetFolderName());
702 wrap = new AliAnalysisDataWrapper(obj);
703 wrap->SetDeleteData(kFALSE);
705 if (!wrap) wrap = (AliAnalysisDataWrapper*)source->FindObject(cont->GetName());
707 Error("ImportWrappers","Container %s not found in analysis output !", cont->GetName());
712 printf(" Importing data for container %s\n", cont->GetName());
713 if (strlen(filename)) printf(" -> file %s\n", filename);
716 cont->ImportData(wrap);
718 if (cdir) cdir->cd();
719 if (fDebug > 1) printf("<-AliAnalysisManager::ImportWrappers(): %d containers imported\n", icont);
722 //______________________________________________________________________________
723 void AliAnalysisManager::UnpackOutput(TList *source)
725 // Called by AliAnalysisSelector::Terminate only on the client.
726 if (fDebug > 1) printf("->AliAnalysisManager::UnpackOutput()\n");
728 Error("UnpackOutput", "No target. Exiting.");
731 if (fDebug > 1) printf(" Source list contains %d containers\n", source->GetSize());
733 if (fMode == kProofAnalysis) ImportWrappers(source);
735 TIter next(fOutputs);
736 AliAnalysisDataContainer *output;
737 while ((output=(AliAnalysisDataContainer*)next())) {
738 if (!output->GetData()) continue;
739 // Check if there are client tasks that run post event loop
740 if (output->HasConsumers()) {
741 // Disable event loop semaphore
742 output->SetPostEventLoop(kTRUE);
743 TObjArray *list = output->GetConsumers();
744 Int_t ncons = list->GetEntriesFast();
745 for (Int_t i=0; i<ncons; i++) {
746 AliAnalysisTask *task = (AliAnalysisTask*)list->At(i);
747 task->CheckNotify(kTRUE);
748 // If task is active, execute it
749 if (task->IsPostEventLoop() && task->IsActive()) {
750 if (fDebug > 1) printf("== Executing post event loop task %s\n", task->GetName());
756 if (fDebug > 1) printf("<-AliAnalysisManager::UnpackOutput()\n");
759 //______________________________________________________________________________
760 void AliAnalysisManager::Terminate()
762 // The Terminate() function is the last function to be called during
763 // a query. It always runs on the client, it can be used to present
764 // the results graphically.
765 if (fDebug > 1) printf("->AliAnalysisManager::Terminate()\n");
766 TDirectory *cdir = gDirectory;
768 AliAnalysisTask *task;
769 AliAnalysisDataContainer *output;
772 Bool_t getsysInfo = ((fNSysInfo>0) && (fMode==kLocalAnalysis))?kTRUE:kFALSE;
773 // Call Terminate() for tasks
775 while (!IsSkipTerminate() && (task=(AliAnalysisTask*)next())) {
776 // Save all the canvases produced by the Terminate
777 TString pictname = Form("%s_%s", task->GetName(), task->ClassName());
781 AliSysInfo::AddStamp(Form("%s_TERMINATE",task->ClassName()),0, itask, 2);
783 if (TObject::TestBit(kSaveCanvases)) {
784 if (!gROOT->IsBatch()) {
785 if (fDebug>1) printf("Waiting 5 sec for %s::Terminate() to finish drawing ...\n", task->ClassName());
787 while (timer.CpuTime()<5) {
789 gSystem->ProcessEvents();
792 Int_t iend = gROOT->GetListOfCanvases()->GetEntries();
793 if (iend==0) continue;
795 for (Int_t ipict=0; ipict<iend; ipict++) {
796 canvas = (TCanvas*)gROOT->GetListOfCanvases()->At(ipict);
797 if (!canvas) continue;
798 canvas->SaveAs(Form("%s_%02d.gif", pictname.Data(),ipict));
800 gROOT->GetListOfCanvases()->Delete();
804 if (fInputEventHandler) fInputEventHandler ->TerminateIO();
805 if (fOutputEventHandler) fOutputEventHandler ->TerminateIO();
806 if (fMCtruthEventHandler) fMCtruthEventHandler->TerminateIO();
808 TObjArray *allOutputs = new TObjArray();
810 for (icont=0; icont<fOutputs->GetEntriesFast(); icont++) allOutputs->Add(fOutputs->At(icont));
811 if (!IsSkipTerminate())
812 for (icont=0; icont<fParamCont->GetEntriesFast(); icont++) allOutputs->Add(fParamCont->At(icont));
813 TIter next1(allOutputs);
814 TString handlerFile = "";
815 if (fOutputEventHandler) {
816 handlerFile = fOutputEventHandler->GetOutputFileName();
819 while ((output=(AliAnalysisDataContainer*)next1())) {
820 // Special outputs or grid files have the files already closed and written.
822 if (fMode == kGridAnalysis && icont<=fOutputs->GetEntriesFast()) continue;
823 if (fMode == kProofAnalysis) {
824 if (output->IsSpecialOutput() || output->IsRegisterDataset()) continue;
826 const char *filename = output->GetFileName();
827 TString openoption = "RECREATE";
828 if (!(strcmp(filename, "default"))) continue;
829 if (!strlen(filename)) continue;
830 if (!output->GetData()) continue;
831 TDirectory *opwd = gDirectory;
832 TFile *file = output->GetFile();
833 if (!file) file = (TFile*)gROOT->GetListOfFiles()->FindObject(filename);
835 //if (handlerFile == filename && !gSystem->AccessPathName(filename)) openoption = "UPDATE";
836 if (!gSystem->AccessPathName(filename)) openoption = "UPDATE";
837 if (fDebug>1) printf("Opening file: %s option=%s\n",filename, openoption.Data());
838 file = new TFile(filename, openoption);
840 if (fDebug>1) printf("File <%s> already opened with option: <%s> \n", filename, file->GetOption());
841 openoption = file->GetOption();
842 if (openoption == "READ") {
843 if (fDebug>1) printf("...reopening in UPDATE mode\n");
844 file->ReOpen("UPDATE");
847 if (file->IsZombie()) {
848 Error("Terminate", "Cannot open output file %s", filename);
851 output->SetFile(file);
853 // Check for a folder request
854 TString dir = output->GetFolderName();
856 if (!file->GetDirectory(dir)) file->mkdir(dir);
859 if (fDebug > 1) printf("...writing container %s to file %s:%s\n", output->GetName(), file->GetName(), output->GetFolderName());
860 if (output->GetData()->InheritsFrom(TCollection::Class())) {
861 // If data is a collection, we set the name of the collection
862 // as the one of the container and we save as a single key.
863 TCollection *coll = (TCollection*)output->GetData();
864 coll->SetName(output->GetName());
865 coll->Write(output->GetName(), TObject::kSingleKey);
867 if (output->GetData()->InheritsFrom(TTree::Class())) {
868 TTree *tree = (TTree*)output->GetData();
869 tree->SetDirectory(gDirectory);
872 output->GetData()->Write();
875 if (opwd) opwd->cd();
879 while ((output=(AliAnalysisDataContainer*)next1())) {
880 // Close all files at output
881 TDirectory *opwd = gDirectory;
882 if (output->GetFile()) {
883 // Clear file list to release object ownership to user.
884 // output->GetFile()->Clear();
885 output->GetFile()->Close();
886 output->SetFile(NULL);
887 // Copy merged outputs in alien if requested
888 if (fSpecialOutputLocation.Length() &&
889 fSpecialOutputLocation.BeginsWith("alien://")) {
890 Info("Terminate", "Copy file %s to %s", output->GetFile()->GetName(),fSpecialOutputLocation.Data());
891 TFile::Cp(output->GetFile()->GetName(),
892 Form("%s/%s", fSpecialOutputLocation.Data(), output->GetFile()->GetName()));
895 if (opwd) opwd->cd();
900 TDirectory *crtdir = gDirectory;
901 TFile f("syswatch.root", "RECREATE");
905 TTree *tree = AliSysInfo::MakeTree("syswatch.log");
906 tree->SetName("syswatch");
907 tree->SetMarkerStyle(kCircle);
908 tree->SetMarkerColor(kBlue);
909 tree->SetMarkerSize(0.5);
910 if (!gROOT->IsBatch()) {
911 tree->SetAlias("event", "id0");
912 tree->SetAlias("task", "id1");
913 tree->SetAlias("stage", "id2");
914 // Already defined aliases
915 // tree->SetAlias("deltaT","stampSec-stampOldSec");
916 // tree->SetAlias("T","stampSec-first");
917 // tree->SetAlias("deltaVM","(pI.fMemVirtual-pIOld.fMemVirtual)");
918 // tree->SetAlias("VM","pI.fMemVirtual");
919 TCanvas *canvas = new TCanvas("SysInfo","SysInfo",10,10,1200,800);
920 Int_t npads = 1 /*COO plot for all tasks*/ +
921 fTopTasks->GetEntries() /*Exec plot per task*/ +
922 1 /*Terminate plot for all tasks*/ +
925 Int_t iopt = (Int_t)TMath::Sqrt((Double_t)npads);
926 if (npads<iopt*(iopt+1))
927 canvas->Divide(iopt, iopt+1, 0.01, 0.01);
929 canvas->Divide(iopt+1, iopt+1, 0.01, 0.01);
931 // draw the plot of deltaVM for Exec for each task
932 for (itask=0; itask<fTopTasks->GetEntriesFast(); itask++) {
933 task = (AliAnalysisTask*)fTopTasks->At(itask);
935 cut = Form("task==%d && stage==1", itask);
936 tree->Draw("deltaVM:event",cut,"", 1234567890, 0);
937 hist = (TH1*)gPad->GetListOfPrimitives()->FindObject("htemp");
939 hist->SetTitle(Form("%s: Exec dVM[kB]/event", task->GetName()));
940 hist->GetYaxis()->SetTitle("deltaVM [kB]");
943 // Draw the plot of deltaVM for CreateOutputObjects for all tasks
945 tree->SetMarkerStyle(kFullTriangleUp);
946 tree->SetMarkerColor(kRed);
947 tree->SetMarkerSize(0.8);
948 cut = "task>=0 && task<1000 && stage==0";
949 tree->Draw("deltaVM:sname",cut,"", 1234567890, 0);
950 hist = (TH1*)gPad->GetListOfPrimitives()->FindObject("htemp");
952 hist->SetTitle("Memory in CreateOutputObjects()");
953 hist->GetYaxis()->SetTitle("deltaVM [kB]");
954 hist->GetXaxis()->SetTitle("task");
956 // draw the plot of deltaVM for Terminate for all tasks
958 tree->SetMarkerStyle(kOpenSquare);
959 tree->SetMarkerColor(kMagenta);
960 cut = "task>=0 && task<1000 && stage==2";
961 tree->Draw("deltaVM:sname",cut,"", 1234567890, 0);
962 hist = (TH1*)gPad->GetListOfPrimitives()->FindObject("htemp");
964 hist->SetTitle("Memory in Terminate()");
965 hist->GetYaxis()->SetTitle("deltaVM [kB]");
966 hist->GetXaxis()->SetTitle("task");
970 tree->SetMarkerStyle(kFullCircle);
971 tree->SetMarkerColor(kGreen);
972 cut = Form("task==%d && stage==1",fTopTasks->GetEntriesFast()-1);
973 tree->Draw("VM:event",cut,"", 1234567890, 0);
974 hist = (TH1*)gPad->GetListOfPrimitives()->FindObject("htemp");
976 hist->SetTitle("Virtual memory");
977 hist->GetYaxis()->SetTitle("VM [kB]");
981 tree->SetMarkerStyle(kCircle);
982 tree->SetMarkerColor(kBlue);
983 tree->SetMarkerSize(0.5);
988 if (crtdir) crtdir->cd();
990 // Validate the output files
991 if (ValidateOutputFiles()) {
993 out.open("outputs_valid", ios::out);
997 if (fDebug > 1) printf("<-AliAnalysisManager::Terminate()\n");
999 //______________________________________________________________________________
1000 void AliAnalysisManager::ProfileTask(Int_t itop, const char *option) const
1002 // Profiles the task having the itop index in the list of top (first level) tasks.
1003 AliAnalysisTask *task = (AliAnalysisTask*)fTopTasks->At(itop);
1005 Error("ProfileTask", "There are only %d top tasks in the manager", fTopTasks->GetEntries());
1008 ProfileTask(task->GetName(), option);
1011 //______________________________________________________________________________
1012 void AliAnalysisManager::ProfileTask(const char *name, const char */*option*/) const
1014 // Profile a managed task after the execution of the analysis in case NSysInfo
1016 if (gSystem->AccessPathName("syswatch.root")) {
1017 Error("ProfileTask", "No file syswatch.root found in the current directory");
1020 if (gROOT->IsBatch()) return;
1021 AliAnalysisTask *task = (AliAnalysisTask*)fTopTasks->FindObject(name);
1023 Error("ProfileTask", "No top task named %s known by the manager.", name);
1026 Int_t itop = fTopTasks->IndexOf(task);
1027 Int_t itask = fTasks->IndexOf(task);
1028 // Create canvas with 2 pads: first draw COO + Terminate, second Exec
1029 TDirectory *cdir = gDirectory;
1030 TFile f("syswatch.root");
1031 TTree *tree = (TTree*)f.Get("syswatch");
1033 Error("ProfileTask", "No tree named <syswatch> found in file syswatch.root");
1036 if (fDebug > 1) printf("=== Profiling task %s (class %s)\n", name, task->ClassName());
1037 TCanvas *canvas = new TCanvas(Form("profile_%d",itop),Form("Profile of task %s (class %s)",name,task->ClassName()),10,10,800,600);
1038 canvas->Divide(2, 2, 0.01, 0.01);
1042 // VM profile for COO and Terminate methods
1044 cut = Form("task==%d && (stage==0 || stage==2)",itask);
1045 tree->Draw("deltaVM:sname",cut,"", 1234567890, 0);
1046 hist = (TH1*)gPad->GetListOfPrimitives()->FindObject("htemp");
1048 hist->SetTitle("Alocated VM[kB] for COO and Terminate");
1049 hist->GetYaxis()->SetTitle("deltaVM [kB]");
1050 hist->GetXaxis()->SetTitle("method");
1052 // CPU profile per event
1054 cut = Form("task==%d && stage==1",itop);
1055 tree->Draw("deltaT:event",cut,"", 1234567890, 0);
1056 hist = (TH1*)gPad->GetListOfPrimitives()->FindObject("htemp");
1058 hist->SetTitle("Execution time per event");
1059 hist->GetYaxis()->SetTitle("CPU/event [s]");
1061 // VM profile for Exec
1063 cut = Form("task==%d && stage==1",itop);
1064 tree->Draw("deltaVM:event",cut,"", 1234567890, 0);
1065 hist = (TH1*)gPad->GetListOfPrimitives()->FindObject("htemp");
1067 hist->SetTitle("Alocated VM[kB] per event");
1068 hist->GetYaxis()->SetTitle("deltaVM [kB]");
1073 if (cdir) cdir->cd();
1076 //______________________________________________________________________________
1077 void AliAnalysisManager::AddTask(AliAnalysisTask *task)
1079 // Adds a user task to the global list of tasks.
1080 if (fTasks->FindObject(task)) {
1081 Warning("AddTask", "Task %s: the same object already added to the analysis manager. Not adding.", task->GetName());
1084 task->SetActive(kFALSE);
1088 //______________________________________________________________________________
1089 AliAnalysisTask *AliAnalysisManager::GetTask(const char *name) const
1091 // Retreive task by name.
1092 if (!fTasks) return NULL;
1093 return (AliAnalysisTask*)fTasks->FindObject(name);
1096 //______________________________________________________________________________
1097 AliAnalysisDataContainer *AliAnalysisManager::CreateContainer(const char *name,
1098 TClass *datatype, EAliAnalysisContType type, const char *filename)
1100 // Create a data container of a certain type. Types can be:
1101 // kExchangeContainer = 0, used to exchange data between tasks
1102 // kInputContainer = 1, used to store input data
1103 // kOutputContainer = 2, used for writing result to a file
1104 // filename: composed by file#folder (e.g. results.root#INCLUSIVE) - will write
1105 // the output object to a folder inside the output file
1106 if (fContainers->FindObject(name)) {
1107 Error("CreateContainer","A container named %s already defined !",name);
1110 AliAnalysisDataContainer *cont = new AliAnalysisDataContainer(name, datatype);
1111 fContainers->Add(cont);
1113 case kInputContainer:
1116 case kOutputContainer:
1117 fOutputs->Add(cont);
1118 if (filename && strlen(filename)) {
1119 cont->SetFileName(filename);
1120 cont->SetDataOwned(kFALSE); // data owned by the file
1123 case kParamContainer:
1124 fParamCont->Add(cont);
1125 if (filename && strlen(filename)) {
1126 cont->SetFileName(filename);
1127 cont->SetDataOwned(kFALSE); // data owned by the file
1130 case kExchangeContainer:
1136 //______________________________________________________________________________
1137 Bool_t AliAnalysisManager::ConnectInput(AliAnalysisTask *task, Int_t islot,
1138 AliAnalysisDataContainer *cont)
1140 // Connect input of an existing task to a data container.
1142 Error("ConnectInput", "Task pointer is NULL");
1145 if (!fTasks->FindObject(task)) {
1147 Info("ConnectInput", "Task %s was not registered. Now owned by analysis manager", task->GetName());
1149 Bool_t connected = task->ConnectInput(islot, cont);
1153 //______________________________________________________________________________
1154 Bool_t AliAnalysisManager::ConnectOutput(AliAnalysisTask *task, Int_t islot,
1155 AliAnalysisDataContainer *cont)
1157 // Connect output of an existing task to a data container.
1159 Error("ConnectOutput", "Task pointer is NULL");
1162 if (!fTasks->FindObject(task)) {
1164 Warning("ConnectOutput", "Task %s not registered. Now owned by analysis manager", task->GetName());
1166 Bool_t connected = task->ConnectOutput(islot, cont);
1170 //______________________________________________________________________________
1171 void AliAnalysisManager::CleanContainers()
1173 // Clean data from all containers that have already finished all client tasks.
1174 TIter next(fContainers);
1175 AliAnalysisDataContainer *cont;
1176 while ((cont=(AliAnalysisDataContainer *)next())) {
1177 if (cont->IsOwnedData() &&
1178 cont->IsDataReady() &&
1179 cont->ClientsExecuted()) cont->DeleteData();
1183 //______________________________________________________________________________
1184 Bool_t AliAnalysisManager::InitAnalysis()
1186 // Initialization of analysis chain of tasks. Should be called after all tasks
1187 // and data containers are properly connected
1188 // Reset flag and remove valid_outputs file if exists
1190 if (!gSystem->AccessPathName("outputs_valid"))
1191 gSystem->Unlink("outputs_valid");
1192 // Check for top tasks (depending only on input data containers)
1193 if (!fTasks->First()) {
1194 Error("InitAnalysis", "Analysis has no tasks !");
1198 AliAnalysisTask *task;
1199 AliAnalysisDataContainer *cont;
1202 Bool_t iszombie = kFALSE;
1203 Bool_t istop = kTRUE;
1205 while ((task=(AliAnalysisTask*)next())) {
1208 Int_t ninputs = task->GetNinputs();
1209 for (i=0; i<ninputs; i++) {
1210 cont = task->GetInputSlot(i)->GetContainer();
1214 fZombies->Add(task);
1218 Error("InitAnalysis", "Input slot %d of task %s has no container connected ! Declared zombie...",
1219 i, task->GetName());
1221 if (iszombie) continue;
1222 // Check if cont is an input container
1223 if (istop && !fInputs->FindObject(cont)) istop=kFALSE;
1224 // Connect to parent task
1228 fTopTasks->Add(task);
1232 Error("InitAnalysis", "No top task defined. At least one task should be connected only to input containers");
1235 // Check now if there are orphan tasks
1236 for (i=0; i<ntop; i++) {
1237 task = (AliAnalysisTask*)fTopTasks->At(i);
1242 while ((task=(AliAnalysisTask*)next())) {
1243 if (!task->IsUsed()) {
1245 Warning("InitAnalysis", "Task %s is orphan", task->GetName());
1248 // Check the task hierarchy (no parent task should depend on data provided
1249 // by a daughter task)
1250 for (i=0; i<ntop; i++) {
1251 task = (AliAnalysisTask*)fTopTasks->At(i);
1252 if (task->CheckCircularDeps()) {
1253 Error("InitAnalysis", "Found illegal circular dependencies between following tasks:");
1258 // Check that all containers feeding post-event loop tasks are in the outputs list
1259 TIter nextcont(fContainers); // loop over all containers
1260 while ((cont=(AliAnalysisDataContainer*)nextcont())) {
1261 if (!cont->IsPostEventLoop() && !fOutputs->FindObject(cont)) {
1262 if (cont->HasConsumers()) {
1263 // Check if one of the consumers is post event loop
1264 TIter nextconsumer(cont->GetConsumers());
1265 while ((task=(AliAnalysisTask*)nextconsumer())) {
1266 if (task->IsPostEventLoop()) {
1267 fOutputs->Add(cont);
1274 // Check if all special output containers have a file name provided
1275 TIter nextout(fOutputs);
1276 while ((cont=(AliAnalysisDataContainer*)nextout())) {
1277 if (cont->IsSpecialOutput() && !strlen(cont->GetFileName())) {
1278 Error("InitAnalysis", "Wrong container %s : a file name MUST be provided for special outputs", cont->GetName());
1286 //______________________________________________________________________________
1287 void AliAnalysisManager::PrintStatus(Option_t *option) const
1289 // Print task hierarchy.
1291 Info("PrintStatus", "Analysis manager %s not initialized : call InitAnalysis() first", GetName());
1294 Bool_t getsysInfo = ((fNSysInfo>0) && (fMode==kLocalAnalysis))?kTRUE:kFALSE;
1296 Info("PrintStatus", "System information will be collected each %lld events", fNSysInfo);
1297 TIter next(fTopTasks);
1298 AliAnalysisTask *task;
1299 while ((task=(AliAnalysisTask*)next()))
1300 task->PrintTask(option);
1303 //______________________________________________________________________________
1304 void AliAnalysisManager::ResetAnalysis()
1306 // Reset all execution flags and clean containers.
1310 //______________________________________________________________________________
1311 Long64_t AliAnalysisManager::StartAnalysis(const char *type, TTree * const tree, Long64_t nentries, Long64_t firstentry)
1313 // Start analysis for this manager. Analysis task can be: LOCAL, PROOF, GRID or
1314 // MIX. Process nentries starting from firstentry
1316 // Backup current directory and make sure gDirectory points to gROOT
1317 TDirectory *cdir = gDirectory;
1320 Error("StartAnalysis","Analysis manager was not initialized !");
1324 if (fDebug > 1) printf("StartAnalysis %s\n",GetName());
1326 TString anaType = type;
1328 fMode = kLocalAnalysis;
1329 Bool_t runlocalinit = kTRUE;
1330 if (anaType.Contains("file")) {
1331 runlocalinit = kFALSE;
1334 if (anaType.Contains("proof")) fMode = kProofAnalysis;
1335 else if (anaType.Contains("grid")) fMode = kGridAnalysis;
1336 else if (anaType.Contains("mix")) fMode = kMixingAnalysis;
1338 if (fMode == kGridAnalysis) {
1340 if (!anaType.Contains("terminate")) {
1341 if (!fGridHandler) {
1342 Error("StartAnalysis", "Cannot start grid analysis without a grid handler.");
1343 Info("===", "Add an AliAnalysisAlien object as plugin for this manager and configure it.");
1347 // Write analysis manager in the analysis file
1348 cout << "===== RUNNING GRID ANALYSIS: " << GetName() << endl;
1349 // run local task configuration
1350 TIter nextTask(fTasks);
1351 AliAnalysisTask *task;
1352 while ((task=(AliAnalysisTask*)nextTask())) {
1356 if (!fGridHandler->StartAnalysis(nentries, firstentry)) {
1357 Info("StartAnalysis", "Grid analysis was stopped and cannot be terminated");
1362 // Terminate grid analysis
1363 if (fSelector && fSelector->GetStatus() == -1) {cdir->cd(); return -1;}
1364 if (fGridHandler->GetRunMode() == AliAnalysisGrid::kOffline) {cdir->cd(); return 0;}
1365 cout << "===== MERGING OUTPUTS REGISTERED BY YOUR ANALYSIS JOB: " << GetName() << endl;
1366 if (!fGridHandler->MergeOutputs()) {
1367 // Return if outputs could not be merged or if it alien handler
1368 // was configured for offline mode or local testing.
1373 cout << "===== TERMINATING GRID ANALYSIS JOB: " << GetName() << endl;
1374 ImportWrappers(NULL);
1380 SetEventLoop(kFALSE);
1381 // Enable event loop mode if a tree was provided
1382 if (tree || fMode==kMixingAnalysis) SetEventLoop(kTRUE);
1385 TString ttype = "TTree";
1386 if (tree && tree->IsA() == TChain::Class()) {
1387 chain = (TChain*)tree;
1388 if (!chain || !chain->GetListOfFiles()->First()) {
1389 Error("StartAnalysis", "Cannot process null or empty chain...");
1396 Bool_t getsysInfo = ((fNSysInfo>0) && (fMode==kLocalAnalysis))?kTRUE:kFALSE;
1397 if (getsysInfo) AliSysInfo::AddStamp("Start", 0);
1398 // Initialize locally all tasks (happens for all modes)
1400 AliAnalysisTask *task;
1402 while ((task=(AliAnalysisTask*)next())) {
1406 if (getsysInfo) AliSysInfo::AddStamp("LocalInit_all", 0);
1410 case kLocalAnalysis:
1412 TIter nextT(fTasks);
1413 // Call CreateOutputObjects for all tasks
1415 Bool_t dirStatus = TH1::AddDirectoryStatus();
1416 while ((task=(AliAnalysisTask*)nextT())) {
1417 TH1::AddDirectory(kFALSE);
1418 task->CreateOutputObjects();
1419 if (getsysInfo) AliSysInfo::AddStamp(Form("%s_CREATEOUTOBJ",task->ClassName()), 0, itask, 0);
1423 TH1::AddDirectory(dirStatus);
1424 if (IsExternalLoop()) {
1425 Info("StartAnalysis", "Initialization done. Event loop is controlled externally.\
1426 \nSetData for top container, call ExecAnalysis in a loop and then Terminate manually");
1433 // Run tree-based analysis via AliAnalysisSelector
1434 cout << "===== RUNNING LOCAL ANALYSIS " << GetName() << " ON TREE " << tree->GetName() << endl;
1435 fSelector = new AliAnalysisSelector(this);
1436 retv = tree->Process(fSelector, "", nentries, firstentry);
1438 case kProofAnalysis:
1440 if (!gROOT->GetListOfProofs() || !gROOT->GetListOfProofs()->GetEntries()) {
1441 Error("StartAnalysis", "No PROOF!!! Exiting.");
1445 sprintf(line, "gProof->AddInput((TObject*)0x%lx);", (ULong_t)this);
1446 gROOT->ProcessLine(line);
1449 cout << "===== RUNNING PROOF ANALYSIS " << GetName() << " ON CHAIN " << chain->GetName() << endl;
1450 retv = chain->Process("AliAnalysisSelector", "", nentries, firstentry);
1452 Error("StartAnalysis", "No chain!!! Exiting.");
1458 Warning("StartAnalysis", "GRID analysis mode not implemented. Running local.");
1460 case kMixingAnalysis:
1461 // Run event mixing analysis
1463 Error("StartAnalysis", "Cannot run event mixing without event pool");
1467 cout << "===== RUNNING EVENT MIXING ANALYSIS " << GetName() << endl;
1468 fSelector = new AliAnalysisSelector(this);
1469 while ((chain=fEventPool->GetNextChain())) {
1471 // Call NotifyBinChange for all tasks
1472 while ((task=(AliAnalysisTask*)next()))
1473 if (!task->IsPostEventLoop()) task->NotifyBinChange();
1474 retv = chain->Process(fSelector);
1476 Error("StartAnalysis", "Mixing analysis failed");
1481 PackOutput(fSelector->GetOutputList());
1488 //______________________________________________________________________________
1489 Long64_t AliAnalysisManager::StartAnalysis(const char *type, const char *dataset, Long64_t nentries, Long64_t firstentry)
1491 // Start analysis for this manager on a given dataset. Analysis task can be:
1492 // LOCAL, PROOF or GRID. Process nentries starting from firstentry.
1494 Error("StartAnalysis","Analysis manager was not initialized !");
1498 if (fDebug > 1) printf("StartAnalysis %s\n",GetName());
1499 TString anaType = type;
1501 if (!anaType.Contains("proof")) {
1502 Error("StartAnalysis", "Cannot process datasets in %s mode. Try PROOF.", type);
1505 fMode = kProofAnalysis;
1507 SetEventLoop(kTRUE);
1508 // Set the dataset flag
1509 TObject::SetBit(kUseDataSet);
1512 // Initialize locally all tasks
1514 AliAnalysisTask *task;
1515 while ((task=(AliAnalysisTask*)next())) {
1519 if (!gROOT->GetListOfProofs() || !gROOT->GetListOfProofs()->GetEntries()) {
1520 Error("StartAnalysis", "No PROOF!!! Exiting.");
1523 sprintf(line, "gProof->AddInput((TObject*)0x%lx);", (ULong_t)this);
1524 gROOT->ProcessLine(line);
1525 // sprintf(line, "gProof->GetDataSet(\"%s\");", dataset);
1526 // if (!gROOT->ProcessLine(line)) {
1527 // Error("StartAnalysis", "Dataset %s not found", dataset);
1530 sprintf(line, "gProof->Process(\"%s\", \"AliAnalysisSelector\", \"\", %lld, %lld);",
1531 dataset, nentries, firstentry);
1532 cout << "===== RUNNING PROOF ANALYSIS " << GetName() << " ON DATASET " << dataset << endl;
1533 Long_t retv = (Long_t)gROOT->ProcessLine(line);
1537 //______________________________________________________________________________
1538 TFile *AliAnalysisManager::OpenFile(AliAnalysisDataContainer *cont, const char *option, Bool_t ignoreProof)
1540 // Opens according the option the file specified by cont->GetFileName() and changes
1541 // current directory to cont->GetFolderName(). If the file was already opened, it
1542 // checks if the option UPDATE was preserved. File open via TProofOutputFile can
1543 // be optionally ignored.
1544 AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
1545 TString filename = cont->GetFileName();
1547 if (filename.IsNull()) {
1548 ::Error("AliAnalysisManager::OpenFile", "No file name specified for container %s", cont->GetName());
1551 if (mgr->GetAnalysisType()==AliAnalysisManager::kProofAnalysis && cont->IsSpecialOutput()
1553 f = mgr->OpenProofFile(cont,option);
1555 // Check first if the file is already opened
1556 f = (TFile*)gROOT->GetListOfFiles()->FindObject(filename);
1558 // Check if option "UPDATE" was preserved
1559 TString opt(option);
1561 if ((opt=="UPDATE") && (opt!=f->GetOption()))
1562 ::Info("AliAnalysisManager::OpenFile", "File %s already opened in %s mode!", cont->GetFileName(), f->GetOption());
1564 f = TFile::Open(filename, option);
1567 if (f && !f->IsZombie() && !f->TestBit(TFile::kRecovered)) {
1571 // Check for a folder request
1572 TString dir = cont->GetFolderName();
1573 if (!dir.IsNull()) {
1574 if (!f->GetDirectory(dir)) f->mkdir(dir);
1579 ::Fatal("AliAnalysisManager::OpenFile", "File %s could not be opened", filename.Data());
1580 cont->SetFile(NULL);
1584 //______________________________________________________________________________
1585 TFile *AliAnalysisManager::OpenProofFile(AliAnalysisDataContainer *cont, const char *option)
1587 // Opens a special output file used in PROOF.
1589 TString filename = cont->GetFileName();
1590 if (cont == fCommonOutput) {
1591 if (fOutputEventHandler) filename = fOutputEventHandler->GetOutputFileName();
1592 else Fatal("OpenProofFile","No output container. Exiting.");
1595 if (fMode!=kProofAnalysis || !fSelector) {
1596 Fatal("OpenProofFile","Cannot open PROOF file %s: no PROOF or selector",filename.Data());
1599 if (fSpecialOutputLocation.Length()) {
1600 f = (TFile*)gROOT->GetListOfFiles()->FindObject(filename);
1602 // Check if option "UPDATE" was preserved
1603 TString opt(option);
1605 if ((opt=="UPDATE") && (opt!=f->GetOption()))
1606 ::Info("OpenProofFile", "File %s already opened in %s mode!", cont->GetFileName(), f->GetOption());
1608 f = new TFile(filename, option);
1610 if (f && !f->IsZombie() && !f->TestBit(TFile::kRecovered)) {
1614 // Check for a folder request
1615 TString dir = cont->GetFolderName();
1617 if (!f->GetDirectory(dir)) f->mkdir(dir);
1622 Fatal("OpenProofFile", "File %s could not be opened", cont->GetFileName());
1623 cont->SetFile(NULL);
1626 // Check if there is already a proof output file in the output list
1627 TObject *pof = fSelector->GetOutputList()->FindObject(filename);
1629 // Get the actual file
1630 line = Form("((TProofOutputFile*)0x%lx)->GetFileName();", (ULong_t)pof);
1631 filename = (const char*)gROOT->ProcessLine(line);
1633 printf("File: %s already booked via TProofOutputFile\n", filename.Data());
1635 f = (TFile*)gROOT->GetListOfFiles()->FindObject(filename);
1636 if (!f) Fatal("OpenProofFile", "Proof output file found but no file opened for %s", filename.Data());
1637 // Check if option "UPDATE" was preserved
1638 TString opt(option);
1640 if ((opt=="UPDATE") && (opt!=f->GetOption()))
1641 Fatal("OpenProofFile", "File %s already opened, but not in UPDATE mode!", cont->GetFileName());
1643 if (cont->IsRegisterDataset()) {
1644 TString dsetName = filename;
1645 dsetName.ReplaceAll(".root", cont->GetTitle());
1646 dsetName.ReplaceAll(":","_");
1647 if (fDebug>1) printf("Booking dataset: %s\n", dsetName.Data());
1648 line = Form("TProofOutputFile *pf = new TProofOutputFile(\"%s\", \"DROV\", \"%s\");", filename.Data(), dsetName.Data());
1650 if (fDebug>1) printf("Booking TProofOutputFile: %s to be merged\n", filename.Data());
1651 line = Form("TProofOutputFile *pf = new TProofOutputFile(\"%s\");", filename.Data());
1653 if (fDebug > 1) printf("=== %s\n", line.Data());
1654 gROOT->ProcessLine(line);
1655 line = Form("pf->OpenFile(\"%s\");", option);
1656 gROOT->ProcessLine(line);
1659 gROOT->ProcessLine("pf->Print()");
1660 printf(" == proof file name: %s", f->GetName());
1662 // Add to proof output list
1663 line = Form("((TList*)0x%lx)->Add(pf);",(ULong_t)fSelector->GetOutputList());
1664 if (fDebug > 1) printf("=== %s\n", line.Data());
1665 gROOT->ProcessLine(line);
1667 if (f && !f->IsZombie() && !f->TestBit(TFile::kRecovered)) {
1671 // Check for a folder request
1672 TString dir = cont->GetFolderName();
1673 if (!dir.IsNull()) {
1674 if (!f->GetDirectory(dir)) f->mkdir(dir);
1679 Fatal("OpenProofFile", "File %s could not be opened", cont->GetFileName());
1680 cont->SetFile(NULL);
1684 //______________________________________________________________________________
1685 void AliAnalysisManager::ExecAnalysis(Option_t *option)
1687 // Execute analysis.
1688 static Long64_t ncalls = 0;
1689 static Long64_t nentries = 0;
1690 static TTree *lastTree = 0;
1691 static TStopwatch *timer = new TStopwatch();
1692 if (fDebug > 0) printf("MGR: Processing event #%lld\n", ncalls);
1694 if (fTree && (fTree != lastTree)) {
1695 nentries += fTree->GetEntries();
1698 if (!ncalls) timer->Start();
1699 if (!fIsRemote) ProgressBar("Processing event", ncalls, nentries, timer, kFALSE);
1702 TDirectory *cdir = gDirectory;
1703 Bool_t getsysInfo = ((fNSysInfo>0) && (fMode==kLocalAnalysis))?kTRUE:kFALSE;
1704 if (getsysInfo && ((ncalls%fNSysInfo)==0)) AliSysInfo::AddStamp("Exec_start", (Int_t)ncalls);
1707 Error("ExecAnalysis", "Analysis manager was not initialized !");
1711 AliAnalysisTask *task;
1712 // Check if the top tree is active.
1714 if (getsysInfo && ((ncalls%fNSysInfo)==0))
1715 AliSysInfo::AddStamp("Handlers_BeginEventGroup",(Int_t)ncalls, 1002, 0);
1717 // De-activate all tasks
1718 while ((task=(AliAnalysisTask*)next())) task->SetActive(kFALSE);
1719 AliAnalysisDataContainer *cont = fCommonInput;
1720 if (!cont) cont = (AliAnalysisDataContainer*)fInputs->At(0);
1722 Error("ExecAnalysis","Cannot execute analysis in TSelector mode without at least one top container");
1726 cont->SetData(fTree); // This will notify all consumers
1727 Long64_t entry = fTree->GetTree()->GetReadEntry();
1729 // Call BeginEvent() for optional input/output and MC services
1730 if (fInputEventHandler) fInputEventHandler ->BeginEvent(entry);
1731 if (fOutputEventHandler) fOutputEventHandler ->BeginEvent(entry);
1732 if (fMCtruthEventHandler) fMCtruthEventHandler->BeginEvent(entry);
1734 if (getsysInfo && ((ncalls%fNSysInfo)==0))
1735 AliSysInfo::AddStamp("Handlers_BeginEvent",(Int_t)ncalls, 1000, 0);
1737 // Execute the tasks
1738 // TIter next1(cont->GetConsumers());
1739 TIter next1(fTopTasks);
1741 while ((task=(AliAnalysisTask*)next1())) {
1743 cout << " Executing task " << task->GetName() << endl;
1745 task->ExecuteTask(option);
1747 if (getsysInfo && ((ncalls%fNSysInfo)==0))
1748 AliSysInfo::AddStamp(task->ClassName(),(Int_t)ncalls, itask, 1);
1752 // Call FinishEvent() for optional output and MC services
1753 if (fInputEventHandler) fInputEventHandler ->FinishEvent();
1754 if (fOutputEventHandler) fOutputEventHandler ->FinishEvent();
1755 if (fMCtruthEventHandler) fMCtruthEventHandler->FinishEvent();
1756 // Gather system information if requested
1757 if (getsysInfo && ((ncalls%fNSysInfo)==0))
1758 AliSysInfo::AddStamp("Handlers_FinishEvent",(Int_t)ncalls, 1001, 1);
1762 // The event loop is not controlled by TSelector
1764 // Call BeginEvent() for optional input/output and MC services
1765 if (fInputEventHandler) fInputEventHandler ->BeginEvent(-1);
1766 if (fOutputEventHandler) fOutputEventHandler ->BeginEvent(-1);
1767 if (fMCtruthEventHandler) fMCtruthEventHandler->BeginEvent(-1);
1769 if (getsysInfo && ((ncalls%fNSysInfo)==0))
1770 AliSysInfo::AddStamp("Handlers_BeginEvent",(Int_t)ncalls, 1000, 0);
1771 TIter next2(fTopTasks);
1772 while ((task=(AliAnalysisTask*)next2())) {
1773 task->SetActive(kTRUE);
1775 cout << " Executing task " << task->GetName() << endl;
1777 task->ExecuteTask(option);
1781 // Call FinishEvent() for optional output and MC services
1782 if (fInputEventHandler) fInputEventHandler ->FinishEvent();
1783 if (fOutputEventHandler) fOutputEventHandler ->FinishEvent();
1784 if (fMCtruthEventHandler) fMCtruthEventHandler->FinishEvent();
1785 if (getsysInfo && ((ncalls%fNSysInfo)==0))
1786 AliSysInfo::AddStamp("Handlers_FinishEvent",(Int_t)ncalls, 1000, 1);
1790 //______________________________________________________________________________
1791 void AliAnalysisManager::SetInputEventHandler(AliVEventHandler* const handler)
1793 // Set the input event handler and create a container for it.
1794 fInputEventHandler = handler;
1795 fCommonInput = CreateContainer("cAUTO_INPUT", TChain::Class(), AliAnalysisManager::kInputContainer);
1796 // Warning("SetInputEventHandler", " An automatic input container for the input chain was created.\nPlease use: mgr->GetCommonInputContainer() to access it.");
1799 //______________________________________________________________________________
1800 void AliAnalysisManager::SetOutputEventHandler(AliVEventHandler* const handler)
1802 // Set the input event handler and create a container for it.
1803 fOutputEventHandler = handler;
1804 fCommonOutput = CreateContainer("cAUTO_OUTPUT", TTree::Class(), AliAnalysisManager::kOutputContainer, "default");
1805 fCommonOutput->SetSpecialOutput();
1806 // Warning("SetOutputEventHandler", " An automatic output container for the output tree was created.\nPlease use: mgr->GetCommonOutputContainer() to access it.");
1809 //______________________________________________________________________________
1810 void AliAnalysisManager::RegisterExtraFile(const char *fname)
1812 // This method is used externally to register output files which are not
1813 // connected to any output container, so that the manager can properly register,
1814 // retrieve or merge them when running in distributed mode. The file names are
1815 // separated by blancs. The method has to be called in MyAnalysisTask::LocalInit().
1816 if (fExtraFiles.Contains(fname)) return;
1817 if (fExtraFiles.Length()) fExtraFiles += " ";
1818 fExtraFiles += fname;
1821 //______________________________________________________________________________
1822 Bool_t AliAnalysisManager::GetFileFromWrapper(const char *filename, const TList *source)
1824 // Copy a file from the location specified ina the wrapper with the same name from the source list.
1827 TObject *pof = source->FindObject(filename);
1828 if (!pof || !pof->InheritsFrom("TProofOutputFile")) {
1829 Error("GetFileFromWrapper", "TProofOutputFile object not found in output list for file %s", filename);
1832 gROOT->ProcessLine(Form("sprintf((char*)0x%lx, \"%%s\", ((TProofOutputFile*)0x%lx)->GetOutputFileName();)", (ULong_t)fullPath, (ULong_t)pof));
1833 gROOT->ProcessLine(Form("sprintf((char*)0x%lx, \"%%s\", gProof->GetUrl();)", (ULong_t)chUrl));
1834 TString clientUrl(chUrl);
1835 TString fullPath_str(fullPath);
1836 if (clientUrl.Contains("localhost")){
1837 TObjArray* array = fullPath_str.Tokenize ( "//" );
1838 TObjString *strobj = ( TObjString *)array->At(1);
1839 TObjArray* arrayPort = strobj->GetString().Tokenize ( ":" );
1840 TObjString *strobjPort = ( TObjString *) arrayPort->At(1);
1841 fullPath_str.ReplaceAll(strobj->GetString().Data(),"localhost:PORT");
1842 fullPath_str.ReplaceAll(":PORT",Form(":%s",strobjPort->GetString().Data()));
1843 if (fDebug > 1) Info("GetFileFromWrapper","Using tunnel from %s to %s",fullPath_str.Data(),filename);
1848 Info("GetFileFromWrapper","Copying file %s from PROOF scratch space", fullPath_str.Data());
1849 Bool_t gotit = TFile::Cp(fullPath_str.Data(), filename);
1851 Error("GetFileFromWrapper", "Could not get file %s from proof scratch space", filename);
1855 //______________________________________________________________________________
1856 void AliAnalysisManager::GetAnalysisTypeString(TString &type) const
1858 // Fill analysis type in the provided string.
1860 case kLocalAnalysis:
1863 case kProofAnalysis:
1869 case kMixingAnalysis:
1874 //______________________________________________________________________________
1875 Bool_t AliAnalysisManager::ValidateOutputFiles() const
1877 // Validate all output files.
1878 TIter next(fOutputs);
1879 AliAnalysisDataContainer *output;
1880 TDirectory *cdir = gDirectory;
1881 TString openedFiles;
1882 while ((output=(AliAnalysisDataContainer*)next())) {
1883 if (output->IsRegisterDataset()) continue;
1884 TString filename = output->GetFileName();
1885 if (filename == "default") {
1886 if (!fOutputEventHandler) continue;
1887 filename = fOutputEventHandler->GetOutputFileName();
1888 // Main AOD may not be there
1889 if (gSystem->AccessPathName(filename)) continue;
1891 // Check if the file is closed
1892 if (openedFiles.Contains(filename)) continue;;
1893 TFile *file = (TFile*)gROOT->GetListOfFiles()->FindObject(filename);
1895 Warning("ValidateOutputs", "File %s was not closed. Closing.", filename.Data());
1896 // Clear file list to release object ownership to user.
1900 file = TFile::Open(filename);
1901 if (!file || file->IsZombie() || file->TestBit(TFile::kRecovered)) {
1902 Error("ValidateOutputs", "Output file <%s> was not created or invalid", filename.Data());
1907 openedFiles += filename;
1914 //______________________________________________________________________________
1915 void AliAnalysisManager::ProgressBar(const char *opname, Long64_t current, Long64_t size, TStopwatch * const watch, Bool_t last, Bool_t refresh)
1917 // Implements a nice text mode progress bar.
1918 static Long64_t icount = 0;
1919 static TString oname;
1920 static TString nname;
1921 static Long64_t ocurrent = 0;
1922 static Long64_t osize = 0;
1923 static Int_t oseconds = 0;
1924 static TStopwatch *owatch = 0;
1925 static Bool_t oneoftwo = kFALSE;
1926 static Int_t nrefresh = 0;
1927 static Int_t nchecks = 0;
1928 const char symbol[4] = {'=','\\','|','/'};
1929 char progress[11] = " ";
1930 Int_t ichar = icount%4;
1937 ocurrent = TMath::Abs(current);
1938 osize = TMath::Abs(size);
1939 if (ocurrent > osize) ocurrent=osize;
1949 if (owatch && !last) {
1951 time = owatch->RealTime();
1952 hours = (Int_t)(time/3600.);
1954 minutes = (Int_t)(time/60.);
1956 seconds = (Int_t)time;
1958 if (oseconds==seconds) {
1962 oneoftwo = !oneoftwo;
1966 if (refresh && oneoftwo) {
1968 if (nchecks <= 0) nchecks = nrefresh+1;
1969 Int_t pctdone = (Int_t)(100.*nrefresh/nchecks);
1970 oname = Form(" == %d%% ==", pctdone);
1972 Double_t percent = 100.0*ocurrent/osize;
1973 Int_t nchar = Int_t(percent/10);
1974 if (nchar>10) nchar=10;
1976 for (i=0; i<nchar; i++) progress[i] = '=';
1977 progress[nchar] = symbol[ichar];
1978 for (i=nchar+1; i<10; i++) progress[i] = ' ';
1979 progress[10] = '\0';
1982 if(size<10000) fprintf(stderr, "%s [%10s] %4lld ", oname.Data(), progress, ocurrent);
1983 else if(size<100000) fprintf(stderr, "%s [%10s] %5lld ",oname.Data(), progress, ocurrent);
1984 else fprintf(stderr, "%s [%10s] %7lld ",oname.Data(), progress, ocurrent);
1985 if (time>0.) fprintf(stderr, "[%6.2f %%] TIME %.2d:%.2d:%.2d \r", percent, hours, minutes, seconds);
1986 else fprintf(stderr, "[%6.2f %%]\r", percent);
1987 if (refresh && oneoftwo) oname = nname;
1988 if (owatch) owatch->Continue();
1997 fprintf(stderr, "\n");
2001 //______________________________________________________________________________
2002 void AliAnalysisManager::DoLoadBranch(const char *name)
2004 // Get tree and load branch if needed.
2009 TBranch *br = dynamic_cast<TBranch*>(fTable.FindObject(name));
2011 br = fTree->GetBranch(name);
2013 Error("DoLoadBranch", "Could not find branch %s",name);
2018 if (br->GetReadEntry()==GetCurrentEntry())
2020 br->GetEntry(GetCurrentEntry());