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>
34 #include <TMethodCall.h>
39 #include <TStopwatch.h>
41 #include "AliAnalysisSelector.h"
42 #include "AliAnalysisGrid.h"
43 #include "AliAnalysisTask.h"
44 #include "AliAnalysisDataContainer.h"
45 #include "AliAnalysisDataSlot.h"
46 #include "AliVEventHandler.h"
47 #include "AliVEventPool.h"
48 #include "AliSysInfo.h"
49 #include "AliAnalysisManager.h"
51 ClassImp(AliAnalysisManager)
53 AliAnalysisManager *AliAnalysisManager::fgAnalysisManager = NULL;
54 TString AliAnalysisManager::fgCommonFileName = "";
56 //______________________________________________________________________________
57 AliAnalysisManager::AliAnalysisManager(const char *name, const char *title)
60 fInputEventHandler(NULL),
61 fOutputEventHandler(NULL),
62 fMCtruthEventHandler(NULL),
66 fMode(kLocalAnalysis),
69 fSpecialOutputLocation(""),
82 // Default constructor.
83 fgAnalysisManager = this;
84 fgCommonFileName = "AnalysisResults.root";
85 fTasks = new TObjArray();
86 fTopTasks = new TObjArray();
87 fZombies = new TObjArray();
88 fContainers = new TObjArray();
89 fInputs = new TObjArray();
90 fOutputs = new TObjArray();
92 TObject::SetObjectStat(kFALSE);
95 //______________________________________________________________________________
96 AliAnalysisManager::AliAnalysisManager(const AliAnalysisManager& other)
99 fInputEventHandler(NULL),
100 fOutputEventHandler(NULL),
101 fMCtruthEventHandler(NULL),
106 fInitOK(other.fInitOK),
107 fDebug(other.fDebug),
108 fSpecialOutputLocation(""),
122 fTasks = new TObjArray(*other.fTasks);
123 fTopTasks = new TObjArray(*other.fTopTasks);
124 fZombies = new TObjArray(*other.fZombies);
125 fContainers = new TObjArray(*other.fContainers);
126 fInputs = new TObjArray(*other.fInputs);
127 fOutputs = new TObjArray(*other.fOutputs);
128 fgCommonFileName = "AnalysisResults.root";
129 fgAnalysisManager = this;
130 TObject::SetObjectStat(kFALSE);
133 //______________________________________________________________________________
134 AliAnalysisManager& AliAnalysisManager::operator=(const AliAnalysisManager& other)
137 if (&other != this) {
138 TNamed::operator=(other);
139 fInputEventHandler = other.fInputEventHandler;
140 fOutputEventHandler = other.fOutputEventHandler;
141 fMCtruthEventHandler = other.fMCtruthEventHandler;
142 fEventPool = other.fEventPool;
145 fNSysInfo = other.fNSysInfo;
147 fInitOK = other.fInitOK;
148 fDebug = other.fDebug;
149 fTasks = new TObjArray(*other.fTasks);
150 fTopTasks = new TObjArray(*other.fTopTasks);
151 fZombies = new TObjArray(*other.fZombies);
152 fContainers = new TObjArray(*other.fContainers);
153 fInputs = new TObjArray(*other.fInputs);
154 fOutputs = new TObjArray(*other.fOutputs);
156 fCommonOutput = NULL;
159 fExtraFiles = other.fExtraFiles;
160 fgCommonFileName = "AnalysisResults.root";
161 fgAnalysisManager = this;
166 //______________________________________________________________________________
167 AliAnalysisManager::~AliAnalysisManager()
170 if (fTasks) {fTasks->Delete(); delete fTasks;}
171 if (fTopTasks) delete fTopTasks;
172 if (fZombies) delete fZombies;
173 if (fContainers) {fContainers->Delete(); delete fContainers;}
174 if (fInputs) delete fInputs;
175 if (fOutputs) delete fOutputs;
176 if (fGridHandler) delete fGridHandler;
177 if (fgAnalysisManager==this) fgAnalysisManager = NULL;
178 TObject::SetObjectStat(kTRUE);
181 //______________________________________________________________________________
182 Int_t AliAnalysisManager::GetEntry(Long64_t entry, Int_t getall)
184 // Read one entry of the tree or a whole branch.
185 static Int_t itot = 0;
186 if (fDebug > 1) printf("MGR: Processing event #%d (entry %lld)\n", itot, entry);
188 fCurrentEntry = entry;
189 return fTree ? fTree->GetTree()->GetEntry(entry, getall) : 0;
192 //______________________________________________________________________________
193 Bool_t AliAnalysisManager::Init(TTree *tree)
195 // The Init() function is called when the selector needs to initialize
196 // a new tree or chain. Typically here the branch addresses of the tree
197 // will be set. It is normaly not necessary to make changes to the
198 // generated code, but the routine can be extended by the user if needed.
199 // Init() will be called many times when running with PROOF.
200 Bool_t init = kFALSE;
201 if (!tree) return kFALSE; // Should not happen - protected in selector caller
203 printf("->AliAnalysisManager::Init(%s)\n", tree->GetName());
205 // Call InitTree of EventHandler
206 if (fOutputEventHandler) {
207 if (fMode == kProofAnalysis) {
208 init = fOutputEventHandler->Init(0x0, "proof");
210 init = fOutputEventHandler->Init(0x0, "local");
213 Error("Init", "Output event handler failed to initialize");
218 if (fInputEventHandler) {
219 if (fMode == kProofAnalysis) {
220 init = fInputEventHandler->Init(tree, "proof");
222 init = fInputEventHandler->Init(tree, "local");
225 Error("Init", "Input event handler failed to initialize tree");
229 // If no input event handler we need to get the tree once
231 if(!tree->GetTree()) {
232 Long64_t readEntry = tree->LoadTree(0);
233 if (readEntry == -2) {
234 Error("Init", "Input tree has no entry. Aborting");
240 if (fMCtruthEventHandler) {
241 if (fMode == kProofAnalysis) {
242 init = fMCtruthEventHandler->Init(0x0, "proof");
244 init = fMCtruthEventHandler->Init(0x0, "local");
247 Error("Init", "MC event handler failed to initialize");
252 if (!fInitOK) InitAnalysis();
253 if (!fInitOK) return kFALSE;
255 AliAnalysisDataContainer *top = fCommonInput;
256 if (!top) top = (AliAnalysisDataContainer*)fInputs->At(0);
258 Error("Init","No top input container !");
263 printf("<-AliAnalysisManager::Init(%s)\n", tree->GetName());
268 //______________________________________________________________________________
269 void AliAnalysisManager::SlaveBegin(TTree *tree)
271 // The SlaveBegin() function is called after the Begin() function.
272 // When running with PROOF SlaveBegin() is called on each slave server.
273 // The tree argument is deprecated (on PROOF 0 is passed).
274 if (fDebug > 0) printf("->AliAnalysisManager::SlaveBegin()\n");
275 static Bool_t isCalled = kFALSE;
276 Bool_t init = kFALSE;
277 Bool_t initOK = kTRUE;
279 TDirectory *curdir = gDirectory;
280 // Call SlaveBegin only once in case of mixing
281 if (isCalled && fMode==kMixingAnalysis) return;
282 // Call Init of EventHandler
283 if (fOutputEventHandler) {
284 if (fMode == kProofAnalysis) {
285 // Merging AOD's in PROOF via TProofOutputFile
286 if (fDebug > 1) printf(" Initializing AOD output file %s...\n", fOutputEventHandler->GetOutputFileName());
287 init = fOutputEventHandler->Init("proof");
288 if (!init) msg = "Failed to initialize output handler on worker";
290 init = fOutputEventHandler->Init("local");
291 if (!init) msg = "Failed to initialize output handler";
294 if (!fSelector) Error("SlaveBegin", "Selector not set");
295 else if (!init) {fSelector->Abort(msg); fSelector->SetStatus(-1);}
298 if (fInputEventHandler) {
299 fInputEventHandler->SetInputTree(tree);
300 if (fMode == kProofAnalysis) {
301 init = fInputEventHandler->Init("proof");
302 if (!init) msg = "Failed to initialize input handler on worker";
304 init = fInputEventHandler->Init("local");
305 if (!init) msg = "Failed to initialize input handler";
308 if (!fSelector) Error("SlaveBegin", "Selector not set");
309 else if (!init) {fSelector->Abort(msg); fSelector->SetStatus(-1);}
312 if (fMCtruthEventHandler) {
313 if (fMode == kProofAnalysis) {
314 init = fMCtruthEventHandler->Init("proof");
315 if (!init) msg = "Failed to initialize MC handler on worker";
317 init = fMCtruthEventHandler->Init("local");
318 if (!init) msg = "Failed to initialize MC handler";
321 if (!fSelector) Error("SlaveBegin", "Selector not set");
322 else if (!init) {fSelector->Abort(msg); fSelector->SetStatus(-1);}
324 if (curdir) curdir->cd();
328 AliAnalysisTask *task;
329 // Call CreateOutputObjects for all tasks
330 while ((task=(AliAnalysisTask*)next())) {
332 task->CreateOutputObjects();
333 if (curdir) curdir->cd();
335 if (fDebug > 0) printf("<-AliAnalysisManager::SlaveBegin()\n");
338 //______________________________________________________________________________
339 Bool_t AliAnalysisManager::Notify()
341 // The Notify() function is called when a new file is opened. This
342 // can be either for a new TTree in a TChain or when when a new TTree
343 // is started when using PROOF. It is normaly not necessary to make changes
344 // to the generated code, but the routine can be extended by the
345 // user if needed. The return value is currently not used.
346 if (!fTree) return kFALSE;
348 TFile *curfile = fTree->GetCurrentFile();
350 Error("Notify","No current file");
354 if (fDebug > 0) printf("->AliAnalysisManager::Notify() file: %s\n", curfile->GetName());
356 AliAnalysisTask *task;
357 // Call Notify for all tasks
358 while ((task=(AliAnalysisTask*)next()))
361 // Call Notify of the event handlers
362 if (fInputEventHandler) {
363 fInputEventHandler->Notify(curfile->GetName());
366 if (fOutputEventHandler) {
367 fOutputEventHandler->Notify(curfile->GetName());
370 if (fMCtruthEventHandler) {
371 fMCtruthEventHandler->Notify(curfile->GetName());
373 if (fDebug > 0) printf("<-AliAnalysisManager::Notify()\n");
377 //______________________________________________________________________________
378 Bool_t AliAnalysisManager::Process(Long64_t entry)
380 // The Process() function is called for each entry in the tree (or possibly
381 // keyed object in the case of PROOF) to be processed. The entry argument
382 // specifies which entry in the currently loaded tree is to be processed.
383 // It can be passed to either TTree::GetEntry() or TBranch::GetEntry()
384 // to read either all or the required parts of the data. When processing
385 // keyed objects with PROOF, the object is already loaded and is available
386 // via the fObject pointer.
388 // This function should contain the "body" of the analysis. It can contain
389 // simple or elaborate selection criteria, run algorithms on the data
390 // of the event and typically fill histograms.
392 // WARNING when a selector is used with a TChain, you must use
393 // the pointer to the current TTree to call GetEntry(entry).
394 // The entry is always the local entry number in the current tree.
395 // Assuming that fChain is the pointer to the TChain being processed,
396 // use fChain->GetTree()->GetEntry(entry).
397 if (fDebug > 0) printf("->AliAnalysisManager::Process(%lld)\n", entry);
399 if (fInputEventHandler) fInputEventHandler ->BeginEvent(entry);
400 if (fOutputEventHandler) fOutputEventHandler ->BeginEvent(entry);
401 if (fMCtruthEventHandler) fMCtruthEventHandler->BeginEvent(entry);
405 if (fDebug > 0) printf("<-AliAnalysisManager::Process()\n");
409 //______________________________________________________________________________
410 void AliAnalysisManager::PackOutput(TList *target)
412 // Pack all output data containers in the output list. Called at SlaveTerminate
413 // stage in PROOF case for each slave.
414 if (fDebug > 0) printf("->AliAnalysisManager::PackOutput()\n");
416 Error("PackOutput", "No target. Aborting.");
419 if (fInputEventHandler) fInputEventHandler ->Terminate();
420 if (fOutputEventHandler) fOutputEventHandler ->Terminate();
421 if (fMCtruthEventHandler) fMCtruthEventHandler->Terminate();
423 // Call FinishTaskOutput() for each event loop task (not called for
424 // post-event loop tasks - use Terminate() fo those)
425 TIter nexttask(fTasks);
426 AliAnalysisTask *task;
427 while ((task=(AliAnalysisTask*)nexttask())) {
428 if (!task->IsPostEventLoop()) {
429 if (fDebug > 0) printf("->FinishTaskOutput: task %s\n", task->GetName());
430 task->FinishTaskOutput();
431 if (fDebug > 0) printf("<-FinishTaskOutput: task %s\n", task->GetName());
435 if (fMode == kProofAnalysis) {
436 TIter next(fOutputs);
437 AliAnalysisDataContainer *output;
438 Bool_t isManagedByHandler = kFALSE;
439 while ((output=(AliAnalysisDataContainer*)next())) {
440 // Do not consider outputs of post event loop tasks
441 isManagedByHandler = kFALSE;
442 if (output->GetProducer()->IsPostEventLoop()) continue;
443 const char *filename = output->GetFileName();
444 if (!(strcmp(filename, "default")) && fOutputEventHandler) {
445 isManagedByHandler = kTRUE;
446 printf("#### Handler output. Extra: %s\n", fExtraFiles.Data());
447 filename = fOutputEventHandler->GetOutputFileName();
449 // Check if data was posted to this container. If not, issue an error.
450 if (!output->GetData() && !isManagedByHandler) {
451 Error("PackOutput", "No data for output container %s. Forgot to PostData ?", output->GetName());
454 if (!output->IsSpecialOutput()) {
456 if (strlen(filename) && !isManagedByHandler) {
457 // Backup current folder
458 TDirectory *opwd = gDirectory;
459 // File resident outputs.
460 // Check first if the file exists.
461 TString open_option = "RECREATE";
462 if (!gSystem->AccessPathName(output->GetFileName())) open_option = "UPDATE";
463 TFile *file = AliAnalysisManager::OpenFile(output, open_option, kTRUE);
464 // Clear file list to release object ownership to user.
466 // Save data to file, then close.
467 if (output->GetData()->InheritsFrom(TCollection::Class())) {
468 // If data is a collection, we set the name of the collection
469 // as the one of the container and we save as a single key.
470 TCollection *coll = (TCollection*)output->GetData();
471 coll->SetName(output->GetName());
472 coll->Write(output->GetName(), TObject::kSingleKey);
474 if (output->GetData()->InheritsFrom(TTree::Class())) {
475 TTree *tree = (TTree*)output->GetData();
476 // tree->SetDirectory(file);
479 output->GetData()->Write();
482 if (fDebug > 1) printf("PackOutput %s: memory merge, file resident output\n", output->GetName());
484 printf(" file %s listing content:\n", filename);
488 output->SetFile(NULL);
489 // Restore current directory
490 if (opwd) opwd->cd();
492 // Memory-resident outputs
493 if (fDebug > 1) printf("PackOutput %s: memory merge memory resident output\n", filename);
495 AliAnalysisDataWrapper *wrap = 0;
496 if (isManagedByHandler) {
497 wrap = new AliAnalysisDataWrapper(fOutputEventHandler->GetTree());
498 wrap->SetName(output->GetName());
500 else wrap =output->ExportData();
501 // Output wrappers must NOT delete data after merging - the user owns them
502 wrap->SetDeleteData(kFALSE);
505 // Special outputs. The file must be opened and connected to the container.
506 TDirectory *opwd = gDirectory;
507 TFile *file = output->GetFile();
509 AliAnalysisTask *producer = output->GetProducer();
511 "File %s for special container %s was NOT opened in %s::CreateOutputObjects !!!",
512 output->GetFileName(), output->GetName(), producer->ClassName());
515 TString outFilename = file->GetName();
516 if (fDebug > 1) printf("PackOutput %s: special output\n", output->GetName());
517 if (isManagedByHandler) {
518 // Terminate IO for files managed by the output handler
519 // file->Write() moved to AOD handler (A.G. 11.01.10)
520 // if (file) file->Write();
521 if (file && fDebug > 2) {
522 printf(" handled file %s listing content:\n", file->GetName());
525 fOutputEventHandler->TerminateIO();
528 // Release object ownership to users after writing data to file
529 if (output->GetData()->InheritsFrom(TCollection::Class())) {
530 // If data is a collection, we set the name of the collection
531 // as the one of the container and we save as a single key.
532 TCollection *coll = (TCollection*)output->GetData();
533 coll->SetName(output->GetName());
534 coll->Write(output->GetName(), TObject::kSingleKey);
536 if (output->GetData()->InheritsFrom(TTree::Class())) {
537 TTree *tree = (TTree*)output->GetData();
538 tree->SetDirectory(file);
541 output->GetData()->Write();
546 printf(" file %s listing content:\n", output->GetFileName());
550 output->SetFile(NULL);
552 // Restore current directory
553 if (opwd) opwd->cd();
554 // Check if a special output location was provided or the output files have to be merged
555 if (strlen(fSpecialOutputLocation.Data())) {
556 TString remote = fSpecialOutputLocation;
558 Int_t gid = gROOT->ProcessLine("gProofServ->GetGroupId();");
559 if (remote.BeginsWith("alien://")) {
560 gROOT->ProcessLine("TGrid::Connect(\"alien://pcapiserv01.cern.ch:10000\", gProofServ->GetUser());");
561 remote += outFilename;
562 remote.ReplaceAll(".root", Form("_%d.root", gid));
564 remote += Form("%s_%d_", gSystem->HostName(), gid);
565 remote += outFilename;
568 Info("PackOutput", "Output file for container %s to be copied \n at: %s. No merging.",
569 output->GetName(), remote.Data());
570 TFile::Cp ( outFilename.Data(), remote.Data() );
571 // Copy extra outputs
572 if (fExtraFiles.Length() && isManagedByHandler) {
573 TObjArray *arr = fExtraFiles.Tokenize(" ");
575 TIter nextfilename(arr);
576 while ((os=(TObjString*)nextfilename())) {
577 outFilename = os->GetString();
578 remote = fSpecialOutputLocation;
580 if (remote.BeginsWith("alien://")) {
581 remote += outFilename;
582 remote.ReplaceAll(".root", Form("_%d.root", gid));
584 remote += Form("%s_%d_", gSystem->HostName(), gid);
585 remote += outFilename;
588 Info("PackOutput", "Extra AOD file %s to be copied \n at: %s. No merging.",
589 outFilename.Data(), remote.Data());
590 TFile::Cp ( outFilename.Data(), remote.Data() );
595 // No special location specified-> use TProofOutputFile as merging utility
596 // The file at this output slot must be opened in CreateOutputObjects
597 if (fDebug > 1) printf(" File for container %s to be merged via file merger...\n", output->GetName());
602 if (fDebug > 0) printf("<-AliAnalysisManager::PackOutput: output list contains %d containers\n", target->GetSize());
605 //______________________________________________________________________________
606 void AliAnalysisManager::ImportWrappers(TList *source)
608 // Import data in output containers from wrappers coming in source.
609 if (fDebug > 0) printf("->AliAnalysisManager::ImportWrappers()\n");
610 TIter next(fOutputs);
611 AliAnalysisDataContainer *cont;
612 AliAnalysisDataWrapper *wrap;
614 Bool_t inGrid = (fMode == kGridAnalysis)?kTRUE:kFALSE;
615 TDirectory *cdir = gDirectory;
616 while ((cont=(AliAnalysisDataContainer*)next())) {
618 if (cont->GetProducer()->IsPostEventLoop() && !inGrid) continue;
619 if (cont->IsRegisterDataset()) continue;
620 const char *filename = cont->GetFileName();
621 Bool_t isManagedByHandler = kFALSE;
622 if (!(strcmp(filename, "default")) && fOutputEventHandler) {
623 isManagedByHandler = kTRUE;
624 filename = fOutputEventHandler->GetOutputFileName();
626 if (cont->IsSpecialOutput() || inGrid) {
627 if (strlen(fSpecialOutputLocation.Data())) continue;
628 // Copy merged file from PROOF scratch space.
629 // In case of grid the files are already in the current directory.
631 if (isManagedByHandler && fExtraFiles.Length()) {
632 // Copy extra registered dAOD files.
633 TObjArray *arr = fExtraFiles.Tokenize(" ");
635 TIter nextfilename(arr);
636 while ((os=(TObjString*)nextfilename())) GetFileFromWrapper(os->GetString(), source);
639 if (!GetFileFromWrapper(filename, source)) continue;
641 // Normally we should connect data from the copied file to the
642 // corresponding output container, but it is not obvious how to do this
643 // automatically if several objects in file...
644 TFile *f = (TFile*)gROOT->GetListOfFiles()->FindObject(filename);
645 if (!f) f = TFile::Open(filename, "READ");
647 Error("ImportWrappers", "Cannot open file %s in read-only mode", filename);
651 // Cd to the directory pointed by the container
652 TString folder = cont->GetFolderName();
653 if (!folder.IsNull()) f->cd(folder);
654 // Try to fetch first an object having the container name.
655 obj = gDirectory->Get(cont->GetName());
657 Warning("ImportWrappers", "Could not import object for container %s in file %s:%s.\n Object will not be available in Terminate()",
658 cont->GetName(), filename, cont->GetFolderName());
661 wrap = new AliAnalysisDataWrapper(obj);
662 wrap->SetDeleteData(kFALSE);
664 if (!wrap) wrap = (AliAnalysisDataWrapper*)source->FindObject(cont->GetName());
666 Error("ImportWrappers","Container %s not found in analysis output !", cont->GetName());
671 printf(" Importing data for container %s\n", cont->GetName());
672 if (strlen(filename)) printf(" -> file %s\n", filename);
675 cont->ImportData(wrap);
677 if (cdir) cdir->cd();
678 if (fDebug > 0) printf("<-AliAnalysisManager::ImportWrappers(): %d containers imported\n", icont);
681 //______________________________________________________________________________
682 void AliAnalysisManager::UnpackOutput(TList *source)
684 // Called by AliAnalysisSelector::Terminate only on the client.
685 if (fDebug > 0) printf("->AliAnalysisManager::UnpackOutput()\n");
687 Error("UnpackOutput", "No target. Aborting.");
690 if (fDebug > 1) printf(" Source list contains %d containers\n", source->GetSize());
692 if (fMode == kProofAnalysis) ImportWrappers(source);
694 TIter next(fOutputs);
695 AliAnalysisDataContainer *output;
696 while ((output=(AliAnalysisDataContainer*)next())) {
697 if (!output->GetData()) continue;
698 // Check if there are client tasks that run post event loop
699 if (output->HasConsumers()) {
700 // Disable event loop semaphore
701 output->SetPostEventLoop(kTRUE);
702 TObjArray *list = output->GetConsumers();
703 Int_t ncons = list->GetEntriesFast();
704 for (Int_t i=0; i<ncons; i++) {
705 AliAnalysisTask *task = (AliAnalysisTask*)list->At(i);
706 task->CheckNotify(kTRUE);
707 // If task is active, execute it
708 if (task->IsPostEventLoop() && task->IsActive()) {
709 if (fDebug > 0) printf("== Executing post event loop task %s\n", task->GetName());
715 if (fDebug > 0) printf("<-AliAnalysisManager::UnpackOutput()\n");
718 //______________________________________________________________________________
719 void AliAnalysisManager::Terminate()
721 // The Terminate() function is the last function to be called during
722 // a query. It always runs on the client, it can be used to present
723 // the results graphically.
724 if (fDebug > 0) printf("->AliAnalysisManager::Terminate()\n");
725 AliAnalysisTask *task;
726 AliAnalysisDataContainer *output;
729 // Call Terminate() for tasks
730 while (!IsSkipTerminate() && (task=(AliAnalysisTask*)next())) {
731 // Save all the canvases produced by the Terminate
732 TString pictname = Form("%s_%s", task->GetName(), task->ClassName());
734 if (TObject::TestBit(kSaveCanvases)) {
735 if (!gROOT->IsBatch()) {
736 Warning("Terminate", "Waiting 5 sec for %s::Terminate() to finish drawing", task->ClassName());
738 while (timer.CpuTime()<5) {
740 gSystem->ProcessEvents();
743 Int_t iend = gROOT->GetListOfCanvases()->GetEntries();
744 if (iend==0) continue;
746 for (Int_t ipict=0; ipict<iend; ipict++) {
747 canvas = (TCanvas*)gROOT->GetListOfCanvases()->At(ipict);
748 if (!canvas) continue;
749 canvas->SaveAs(Form("%s_%02d.gif", pictname.Data(),ipict));
751 gROOT->GetListOfCanvases()->Delete();
755 if (fInputEventHandler) fInputEventHandler ->TerminateIO();
756 if (fOutputEventHandler) fOutputEventHandler ->TerminateIO();
757 if (fMCtruthEventHandler) fMCtruthEventHandler->TerminateIO();
758 TIter next1(fOutputs);
759 TString handlerFile = "";
760 if (fOutputEventHandler) {
761 handlerFile = fOutputEventHandler->GetOutputFileName();
763 while ((output=(AliAnalysisDataContainer*)next1())) {
764 // Special outputs or grid files have the files already closed and written.
765 if (fMode == kGridAnalysis) continue;
766 if (fMode == kProofAnalysis) {
767 if (output->IsSpecialOutput() || output->IsRegisterDataset()) continue;
769 const char *filename = output->GetFileName();
770 TString open_option = "RECREATE";
771 if (!(strcmp(filename, "default"))) continue;
772 if (!strlen(filename)) continue;
773 if (!output->GetData()) continue;
774 TDirectory *opwd = gDirectory;
775 TFile *file = output->GetFile();
776 if (!file) file = (TFile*)gROOT->GetListOfFiles()->FindObject(filename);
778 printf("Terminate : handlerFile = %s, filename = %s\n",handlerFile.Data(),filename);
779 //if (handlerFile == filename && !gSystem->AccessPathName(filename)) open_option = "UPDATE";
780 if (!gSystem->AccessPathName(filename)) open_option = "UPDATE";
781 file = new TFile(filename, open_option);
783 if (file->IsZombie()) {
784 Error("Terminate", "Cannot open output file %s", filename);
787 output->SetFile(file);
789 // Check for a folder request
790 TString dir = output->GetFolderName();
792 if (!file->GetDirectory(dir)) file->mkdir(dir);
795 if (fDebug > 1) printf(" writing output data %s to file %s:%s\n", output->GetData()->GetName(), file->GetName(), output->GetFolderName());
796 if (output->GetData()->InheritsFrom(TCollection::Class())) {
797 // If data is a collection, we set the name of the collection
798 // as the one of the container and we save as a single key.
799 TCollection *coll = (TCollection*)output->GetData();
800 coll->SetName(output->GetName());
801 coll->Write(output->GetName(), TObject::kSingleKey);
803 if (output->GetData()->InheritsFrom(TTree::Class())) {
804 TTree *tree = (TTree*)output->GetData();
805 tree->SetDirectory(file);
808 output->GetData()->Write();
811 if (opwd) opwd->cd();
814 while ((output=(AliAnalysisDataContainer*)next1())) {
815 // Close all files at output
816 TDirectory *opwd = gDirectory;
817 if (output->GetFile()) {
818 output->GetFile()->Close();
819 output->SetFile(NULL);
820 // Copy merged outputs in alien if requested
821 if (fSpecialOutputLocation.Length() &&
822 fSpecialOutputLocation.BeginsWith("alien://")) {
823 Info("Terminate", "Copy file %s to %s", output->GetFile()->GetName(),fSpecialOutputLocation.Data());
824 TFile::Cp(output->GetFile()->GetName(),
825 Form("%s/%s", fSpecialOutputLocation.Data(), output->GetFile()->GetName()));
828 if (opwd) opwd->cd();
831 Bool_t getsysInfo = ((fNSysInfo>0) && (fMode==kLocalAnalysis))?kTRUE:kFALSE;
833 TDirectory *cdir = gDirectory;
834 TFile f("syswatch.root", "RECREATE");
836 TTree *tree = AliSysInfo::MakeTree("syswatch.log");
837 tree->SetMarkerStyle(kCircle);
838 tree->SetMarkerColor(kBlue);
839 tree->SetMarkerSize(0.5);
840 if (!gROOT->IsBatch()) {
841 tree->SetAlias("event", "id0");
842 tree->SetAlias("memUSED", "mi.fMemUsed");
843 new TCanvas("SysInfo","SysInfo",10,10,800,600);
844 tree->Draw("memUSED:event","","", 1234567890, 0);
850 if (cdir) cdir->cd();
852 // Validate the output files
853 if (ValidateOutputFiles()) {
855 out.open("outputs_valid", ios::out);
858 if (fDebug > 0) printf("<-AliAnalysisManager::Terminate()\n");
861 //______________________________________________________________________________
862 void AliAnalysisManager::AddTask(AliAnalysisTask *task)
864 // Adds a user task to the global list of tasks.
865 if (fTasks->FindObject(task)) {
866 Warning("AddTask", "Task %s: the same object already added to the analysis manager. Not adding.", task->GetName());
869 task->SetActive(kFALSE);
873 //______________________________________________________________________________
874 AliAnalysisTask *AliAnalysisManager::GetTask(const char *name) const
876 // Retreive task by name.
877 if (!fTasks) return NULL;
878 return (AliAnalysisTask*)fTasks->FindObject(name);
881 //______________________________________________________________________________
882 AliAnalysisDataContainer *AliAnalysisManager::CreateContainer(const char *name,
883 TClass *datatype, EAliAnalysisContType type, const char *filename)
885 // Create a data container of a certain type. Types can be:
886 // kExchangeContainer = 0, used to exchange data between tasks
887 // kInputContainer = 1, used to store input data
888 // kOutputContainer = 2, used for writing result to a file
889 // filename: composed by file#folder (e.g. results.root#INCLUSIVE) - will write
890 // the output object to a folder inside the output file
891 if (fContainers->FindObject(name)) {
892 Error("CreateContainer","A container named %s already defined !",name);
895 AliAnalysisDataContainer *cont = new AliAnalysisDataContainer(name, datatype);
896 fContainers->Add(cont);
898 case kInputContainer:
901 case kOutputContainer:
903 if (filename && strlen(filename)) {
904 cont->SetFileName(filename);
905 cont->SetDataOwned(kFALSE); // data owned by the file
908 case kExchangeContainer:
914 //______________________________________________________________________________
915 Bool_t AliAnalysisManager::ConnectInput(AliAnalysisTask *task, Int_t islot,
916 AliAnalysisDataContainer *cont)
918 // Connect input of an existing task to a data container.
920 Error("ConnectInput", "Task pointer is NULL");
923 if (!fTasks->FindObject(task)) {
925 Info("ConnectInput", "Task %s was not registered. Now owned by analysis manager", task->GetName());
927 Bool_t connected = task->ConnectInput(islot, cont);
931 //______________________________________________________________________________
932 Bool_t AliAnalysisManager::ConnectOutput(AliAnalysisTask *task, Int_t islot,
933 AliAnalysisDataContainer *cont)
935 // Connect output of an existing task to a data container.
937 Error("ConnectOutput", "Task pointer is NULL");
940 if (!fTasks->FindObject(task)) {
942 Warning("ConnectOutput", "Task %s not registered. Now owned by analysis manager", task->GetName());
944 Bool_t connected = task->ConnectOutput(islot, cont);
948 //______________________________________________________________________________
949 void AliAnalysisManager::CleanContainers()
951 // Clean data from all containers that have already finished all client tasks.
952 TIter next(fContainers);
953 AliAnalysisDataContainer *cont;
954 while ((cont=(AliAnalysisDataContainer *)next())) {
955 if (cont->IsOwnedData() &&
956 cont->IsDataReady() &&
957 cont->ClientsExecuted()) cont->DeleteData();
961 //______________________________________________________________________________
962 Bool_t AliAnalysisManager::InitAnalysis()
964 // Initialization of analysis chain of tasks. Should be called after all tasks
965 // and data containers are properly connected
966 // Reset flag and remove valid_outputs file if exists
968 if (!gSystem->AccessPathName("outputs_valid"))
969 gSystem->Unlink("outputs_valid");
970 // Check for top tasks (depending only on input data containers)
971 if (!fTasks->First()) {
972 Error("InitAnalysis", "Analysis has no tasks !");
976 AliAnalysisTask *task;
977 AliAnalysisDataContainer *cont;
980 Bool_t iszombie = kFALSE;
981 Bool_t istop = kTRUE;
983 while ((task=(AliAnalysisTask*)next())) {
986 Int_t ninputs = task->GetNinputs();
987 for (i=0; i<ninputs; i++) {
988 cont = task->GetInputSlot(i)->GetContainer();
996 Error("InitAnalysis", "Input slot %d of task %s has no container connected ! Declared zombie...",
999 if (iszombie) continue;
1000 // Check if cont is an input container
1001 if (istop && !fInputs->FindObject(cont)) istop=kFALSE;
1002 // Connect to parent task
1006 fTopTasks->Add(task);
1010 Error("InitAnalysis", "No top task defined. At least one task should be connected only to input containers");
1013 // Check now if there are orphan tasks
1014 for (i=0; i<ntop; i++) {
1015 task = (AliAnalysisTask*)fTopTasks->At(i);
1020 while ((task=(AliAnalysisTask*)next())) {
1021 if (!task->IsUsed()) {
1023 Warning("InitAnalysis", "Task %s is orphan", task->GetName());
1026 // Check the task hierarchy (no parent task should depend on data provided
1027 // by a daughter task)
1028 for (i=0; i<ntop; i++) {
1029 task = (AliAnalysisTask*)fTopTasks->At(i);
1030 if (task->CheckCircularDeps()) {
1031 Error("InitAnalysis", "Found illegal circular dependencies between following tasks:");
1036 // Check that all containers feeding post-event loop tasks are in the outputs list
1037 TIter nextcont(fContainers); // loop over all containers
1038 while ((cont=(AliAnalysisDataContainer*)nextcont())) {
1039 if (!cont->IsPostEventLoop() && !fOutputs->FindObject(cont)) {
1040 if (cont->HasConsumers()) {
1041 // Check if one of the consumers is post event loop
1042 TIter nextconsumer(cont->GetConsumers());
1043 while ((task=(AliAnalysisTask*)nextconsumer())) {
1044 if (task->IsPostEventLoop()) {
1045 fOutputs->Add(cont);
1052 // Check if all special output containers have a file name provided
1053 TIter nextout(fOutputs);
1054 while ((cont=(AliAnalysisDataContainer*)nextout())) {
1055 if (cont->IsSpecialOutput() && !strlen(cont->GetFileName())) {
1056 Error("InitAnalysis", "Wrong container %s : a file name MUST be provided for special outputs", cont->GetName());
1064 //______________________________________________________________________________
1065 void AliAnalysisManager::PrintStatus(Option_t *option) const
1067 // Print task hierarchy.
1069 Info("PrintStatus", "Analysis manager %s not initialized : call InitAnalysis() first", GetName());
1072 Bool_t getsysInfo = ((fNSysInfo>0) && (fMode==kLocalAnalysis))?kTRUE:kFALSE;
1074 Info("PrintStatus", "System information will be collected each %lld events", fNSysInfo);
1075 TIter next(fTopTasks);
1076 AliAnalysisTask *task;
1077 while ((task=(AliAnalysisTask*)next()))
1078 task->PrintTask(option);
1081 //______________________________________________________________________________
1082 void AliAnalysisManager::ResetAnalysis()
1084 // Reset all execution flags and clean containers.
1088 //______________________________________________________________________________
1089 Long64_t AliAnalysisManager::StartAnalysis(const char *type, TTree *tree, Long64_t nentries, Long64_t firstentry)
1091 // Start analysis for this manager. Analysis task can be: LOCAL, PROOF, GRID or
1092 // MIX. Process nentries starting from firstentry
1095 Error("StartAnalysis","Analysis manager was not initialized !");
1098 if (fDebug > 0) printf("StartAnalysis %s\n",GetName());
1099 TString anaType = type;
1101 fMode = kLocalAnalysis;
1102 Bool_t runlocalinit = kTRUE;
1103 if (anaType.Contains("file")) {
1104 runlocalinit = kFALSE;
1106 if (anaType.Contains("proof")) fMode = kProofAnalysis;
1107 else if (anaType.Contains("grid")) fMode = kGridAnalysis;
1108 else if (anaType.Contains("mix")) fMode = kMixingAnalysis;
1110 if (fMode == kGridAnalysis) {
1111 if (!fGridHandler) {
1112 Error("StartAnalysis", "Cannot start grid analysis without a grid handler.");
1113 Info("===", "Add an AliAnalysisAlien object as plugin for this manager and configure it.");
1116 // Write analysis manager in the analysis file
1117 cout << "===== RUNNING GRID ANALYSIS: " << GetName() << endl;
1118 // run local task configuration
1119 TIter nextTask(fTasks);
1120 AliAnalysisTask *task;
1121 while ((task=(AliAnalysisTask*)nextTask())) {
1124 if (!fGridHandler->StartAnalysis(nentries, firstentry)) {
1125 Info("StartAnalysis", "Grid analysis was stopped and cannot be terminated");
1129 // Terminate grid analysis
1130 if (fSelector && fSelector->GetStatus() == -1) return -1;
1131 if (fGridHandler->GetRunMode() == AliAnalysisGrid::kOffline) return 0;
1132 cout << "===== MERGING OUTPUTS REGISTERED BY YOUR ANALYSIS JOB: " << GetName() << endl;
1133 if (!fGridHandler->MergeOutputs()) {
1134 // Return if outputs could not be merged or if it alien handler
1135 // was configured for offline mode or local testing.
1138 ImportWrappers(NULL);
1143 SetEventLoop(kFALSE);
1144 // Enable event loop mode if a tree was provided
1145 if (tree || fMode==kMixingAnalysis) SetEventLoop(kTRUE);
1148 TString ttype = "TTree";
1149 if (tree && tree->IsA() == TChain::Class()) {
1150 chain = (TChain*)tree;
1151 if (!chain || !chain->GetListOfFiles()->First()) {
1152 Error("StartAnalysis", "Cannot process null or empty chain...");
1158 // Initialize locally all tasks (happens for all modes)
1160 AliAnalysisTask *task;
1162 while ((task=(AliAnalysisTask*)next())) {
1168 case kLocalAnalysis:
1170 TIter nextT(fTasks);
1171 // Call CreateOutputObjects for all tasks
1172 while ((task=(AliAnalysisTask*)nextT())) {
1173 TDirectory *curdir = gDirectory;
1174 task->CreateOutputObjects();
1175 if (curdir) curdir->cd();
1177 if (IsExternalLoop()) {
1178 Info("StartAnalysis", "Initialization done. Event loop is controlled externally.\
1179 \nSetData for top container, call ExecAnalysis in a loop and then Terminate manually");
1186 // Run tree-based analysis via AliAnalysisSelector
1187 cout << "===== RUNNING LOCAL ANALYSIS " << GetName() << " ON TREE " << tree->GetName() << endl;
1188 fSelector = new AliAnalysisSelector(this);
1189 retv = tree->Process(fSelector, "", nentries, firstentry);
1191 case kProofAnalysis:
1192 if (!gROOT->GetListOfProofs() || !gROOT->GetListOfProofs()->GetEntries()) {
1193 Error("StartAnalysis", "No PROOF!!! Aborting.");
1196 sprintf(line, "gProof->AddInput((TObject*)0x%lx);", (ULong_t)this);
1197 gROOT->ProcessLine(line);
1200 cout << "===== RUNNING PROOF ANALYSIS " << GetName() << " ON CHAIN " << chain->GetName() << endl;
1201 retv = chain->Process("AliAnalysisSelector", "", nentries, firstentry);
1203 Error("StartAnalysis", "No chain!!! Aborting.");
1208 Warning("StartAnalysis", "GRID analysis mode not implemented. Running local.");
1210 case kMixingAnalysis:
1211 // Run event mixing analysis
1213 Error("StartAnalysis", "Cannot run event mixing without event pool");
1216 cout << "===== RUNNING EVENT MIXING ANALYSIS " << GetName() << endl;
1217 fSelector = new AliAnalysisSelector(this);
1218 while ((chain=fEventPool->GetNextChain())) {
1220 // Call NotifyBinChange for all tasks
1221 while ((task=(AliAnalysisTask*)next()))
1222 if (!task->IsPostEventLoop()) task->NotifyBinChange();
1223 retv = chain->Process(fSelector);
1225 Error("StartAnalysis", "Mixing analysis failed");
1229 PackOutput(fSelector->GetOutputList());
1235 //______________________________________________________________________________
1236 Long64_t AliAnalysisManager::StartAnalysis(const char *type, const char *dataset, Long64_t nentries, Long64_t firstentry)
1238 // Start analysis for this manager on a given dataset. Analysis task can be:
1239 // LOCAL, PROOF or GRID. Process nentries starting from firstentry.
1241 Error("StartAnalysis","Analysis manager was not initialized !");
1244 if (fDebug > 0) printf("StartAnalysis %s\n",GetName());
1245 TString anaType = type;
1247 if (!anaType.Contains("proof")) {
1248 Error("StartAnalysis", "Cannot process datasets in %s mode. Try PROOF.", type);
1251 fMode = kProofAnalysis;
1253 SetEventLoop(kTRUE);
1254 // Set the dataset flag
1255 TObject::SetBit(kUseDataSet);
1258 // Initialize locally all tasks
1260 AliAnalysisTask *task;
1261 while ((task=(AliAnalysisTask*)next())) {
1265 if (!gROOT->GetListOfProofs() || !gROOT->GetListOfProofs()->GetEntries()) {
1266 Error("StartAnalysis", "No PROOF!!! Aborting.");
1269 sprintf(line, "gProof->AddInput((TObject*)0x%lx);", (ULong_t)this);
1270 gROOT->ProcessLine(line);
1271 sprintf(line, "gProof->GetDataSet(\"%s\");", dataset);
1272 if (!gROOT->ProcessLine(line)) {
1273 Error("StartAnalysis", "Dataset %s not found", dataset);
1276 sprintf(line, "gProof->Process(\"%s\", \"AliAnalysisSelector\", \"\", %lld, %lld);",
1277 dataset, nentries, firstentry);
1278 cout << "===== RUNNING PROOF ANALYSIS " << GetName() << " ON DATASET " << dataset << endl;
1279 Long_t retv = (Long_t)gROOT->ProcessLine(line);
1283 //______________________________________________________________________________
1284 TFile *AliAnalysisManager::OpenFile(AliAnalysisDataContainer *cont, const char *option, Bool_t ignoreProof)
1286 // Opens according the option the file specified by cont->GetFileName() and changes
1287 // current directory to cont->GetFolderName(). If the file was already opened, it
1288 // checks if the option UPDATE was preserved. File open via TProofOutputFile can
1289 // be optionally ignored.
1290 AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
1291 TString filename = cont->GetFileName();
1293 if (filename.IsNull()) {
1294 ::Error("AliAnalysisManager::OpenFile", "No file name specified for container %s", cont->GetName());
1297 if (mgr->GetAnalysisType()==AliAnalysisManager::kProofAnalysis && cont->IsSpecialOutput()
1299 f = mgr->OpenProofFile(cont,option);
1301 // Check first if the file is already opened
1302 f = (TFile*)gROOT->GetListOfFiles()->FindObject(filename);
1304 // Check if option "UPDATE" was preserved
1305 TString opt(option);
1307 if ((opt=="UPDATE") && (opt!=f->GetOption()))
1308 ::Info("AliAnalysisManager::OpenFile", "File %s already opened in %s mode!", cont->GetFileName(), f->GetOption());
1310 f = TFile::Open(filename, option);
1313 if (f && !f->IsZombie() && !f->TestBit(TFile::kRecovered)) {
1317 // Check for a folder request
1318 TString dir = cont->GetFolderName();
1319 if (!dir.IsNull()) {
1320 if (!f->GetDirectory(dir)) f->mkdir(dir);
1325 ::Fatal("AliAnalysisManager::OpenFile", "File %s could not be opened", filename.Data());
1326 cont->SetFile(NULL);
1330 //______________________________________________________________________________
1331 TFile *AliAnalysisManager::OpenProofFile(AliAnalysisDataContainer *cont, const char *option)
1333 // Opens a special output file used in PROOF.
1335 TString filename = cont->GetFileName();
1336 if (cont == fCommonOutput) {
1337 if (fOutputEventHandler) filename = fOutputEventHandler->GetOutputFileName();
1338 else Fatal("OpenProofFile","No output container. Aborting.");
1341 if (fMode!=kProofAnalysis || !fSelector) {
1342 Fatal("OpenProofFile","Cannot open PROOF file %s: no PROOF or selector",filename.Data());
1345 if (fSpecialOutputLocation.Length()) {
1346 f = (TFile*)gROOT->GetListOfFiles()->FindObject(filename);
1348 // Check if option "UPDATE" was preserved
1349 TString opt(option);
1351 if ((opt=="UPDATE") && (opt!=f->GetOption()))
1352 ::Info("OpenProofFile", "File %s already opened in %s mode!", cont->GetFileName(), f->GetOption());
1354 f = new TFile(filename, option);
1356 if (f && !f->IsZombie() && !f->TestBit(TFile::kRecovered)) {
1360 // Check for a folder request
1361 TString dir = cont->GetFolderName();
1363 if (!f->GetDirectory(dir)) f->mkdir(dir);
1368 Fatal("OpenProofFile", "File %s could not be opened", cont->GetFileName());
1369 cont->SetFile(NULL);
1372 // Check if there is already a proof output file in the output list
1373 TObject *pof = fSelector->GetOutputList()->FindObject(filename);
1375 // Get the actual file
1376 line = Form("((TProofOutputFile*)0x%lx)->GetFileName();", (ULong_t)pof);
1377 filename = (const char*)gROOT->ProcessLine(line);
1379 printf("File: %s already booked via TProofOutputFile\n", filename.Data());
1381 f = (TFile*)gROOT->GetListOfFiles()->FindObject(filename);
1382 if (!f) Fatal("OpenProofFile", "Proof output file found but no file opened for %s", filename.Data());
1383 // Check if option "UPDATE" was preserved
1384 TString opt(option);
1386 if ((opt=="UPDATE") && (opt!=f->GetOption()))
1387 Fatal("OpenProofFile", "File %s already opened, but not in UPDATE mode!", cont->GetFileName());
1389 if (cont->IsRegisterDataset()) {
1390 TString dset_name = filename;
1391 dset_name.ReplaceAll(".root", cont->GetTitle());
1392 dset_name.ReplaceAll(":","_");
1393 if (fDebug>1) printf("Booking dataset: %s\n", dset_name.Data());
1394 line = Form("TProofOutputFile *pf = new TProofOutputFile(\"%s\", \"DROV\", \"%s\");", filename.Data(), dset_name.Data());
1396 if (fDebug>1) printf("Booking TProofOutputFile: %s to be merged\n", filename.Data());
1397 line = Form("TProofOutputFile *pf = new TProofOutputFile(\"%s\");", filename.Data());
1399 if (fDebug > 1) printf("=== %s\n", line.Data());
1400 gROOT->ProcessLine(line);
1401 line = Form("pf->OpenFile(\"%s\");", option);
1402 gROOT->ProcessLine(line);
1405 gROOT->ProcessLine("pf->Print()");
1406 printf(" == proof file name: %s", f->GetName());
1408 // Add to proof output list
1409 line = Form("((TList*)0x%lx)->Add(pf);",(ULong_t)fSelector->GetOutputList());
1410 if (fDebug > 1) printf("=== %s\n", line.Data());
1411 gROOT->ProcessLine(line);
1413 if (f && !f->IsZombie() && !f->TestBit(TFile::kRecovered)) {
1417 // Check for a folder request
1418 TString dir = cont->GetFolderName();
1419 if (!dir.IsNull()) {
1420 if (!f->GetDirectory(dir)) f->mkdir(dir);
1425 Fatal("OpenProofFile", "File %s could not be opened", cont->GetFileName());
1426 cont->SetFile(NULL);
1430 //______________________________________________________________________________
1431 void AliAnalysisManager::ExecAnalysis(Option_t *option)
1433 // Execute analysis.
1434 static Long64_t ncalls = 0;
1435 Bool_t getsysInfo = ((fNSysInfo>0) && (fMode==kLocalAnalysis))?kTRUE:kFALSE;
1436 if (getsysInfo && ncalls==0) AliSysInfo::AddStamp("Start", (Int_t)ncalls);
1439 Error("ExecAnalysis", "Analysis manager was not initialized !");
1442 AliAnalysisTask *task;
1443 // Check if the top tree is active.
1446 // De-activate all tasks
1447 while ((task=(AliAnalysisTask*)next())) task->SetActive(kFALSE);
1448 AliAnalysisDataContainer *cont = fCommonInput;
1449 if (!cont) cont = (AliAnalysisDataContainer*)fInputs->At(0);
1451 Error("ExecAnalysis","Cannot execute analysis in TSelector mode without at least one top container");
1454 cont->SetData(fTree); // This will notify all consumers
1455 Long64_t entry = fTree->GetTree()->GetReadEntry();
1458 // Call BeginEvent() for optional input/output and MC services
1459 if (fInputEventHandler) fInputEventHandler ->BeginEvent(entry);
1460 if (fOutputEventHandler) fOutputEventHandler ->BeginEvent(entry);
1461 if (fMCtruthEventHandler) fMCtruthEventHandler->BeginEvent(entry);
1463 // Execute the tasks
1464 // TIter next1(cont->GetConsumers());
1465 TIter next1(fTopTasks);
1466 while ((task=(AliAnalysisTask*)next1())) {
1468 cout << " Executing task " << task->GetName() << endl;
1471 task->ExecuteTask(option);
1474 // Call FinishEvent() for optional output and MC services
1475 if (fInputEventHandler) fInputEventHandler ->FinishEvent();
1476 if (fOutputEventHandler) fOutputEventHandler ->FinishEvent();
1477 if (fMCtruthEventHandler) fMCtruthEventHandler->FinishEvent();
1478 // Gather system information if requested
1479 if (getsysInfo && ((ncalls%fNSysInfo)==0))
1480 AliSysInfo::AddStamp(Form("Event#%lld",ncalls),(Int_t)ncalls);
1483 // The event loop is not controlled by TSelector
1485 // Call BeginEvent() for optional input/output and MC services
1486 if (fInputEventHandler) fInputEventHandler ->BeginEvent(-1);
1487 if (fOutputEventHandler) fOutputEventHandler ->BeginEvent(-1);
1488 if (fMCtruthEventHandler) fMCtruthEventHandler->BeginEvent(-1);
1489 TIter next2(fTopTasks);
1490 while ((task=(AliAnalysisTask*)next2())) {
1491 task->SetActive(kTRUE);
1493 cout << " Executing task " << task->GetName() << endl;
1495 task->ExecuteTask(option);
1498 // Call FinishEvent() for optional output and MC services
1499 if (fInputEventHandler) fInputEventHandler ->FinishEvent();
1500 if (fOutputEventHandler) fOutputEventHandler ->FinishEvent();
1501 if (fMCtruthEventHandler) fMCtruthEventHandler->FinishEvent();
1504 //______________________________________________________________________________
1505 void AliAnalysisManager::FinishAnalysis()
1510 //______________________________________________________________________________
1511 void AliAnalysisManager::SetInputEventHandler(AliVEventHandler* handler)
1513 // Set the input event handler and create a container for it.
1514 fInputEventHandler = handler;
1515 fCommonInput = CreateContainer("cAUTO_INPUT", TChain::Class(), AliAnalysisManager::kInputContainer);
1516 // Warning("SetInputEventHandler", " An automatic input container for the input chain was created.\nPlease use: mgr->GetCommonInputContainer() to access it.");
1519 //______________________________________________________________________________
1520 void AliAnalysisManager::SetOutputEventHandler(AliVEventHandler* handler)
1522 // Set the input event handler and create a container for it.
1523 fOutputEventHandler = handler;
1524 fCommonOutput = CreateContainer("cAUTO_OUTPUT", TTree::Class(), AliAnalysisManager::kOutputContainer, "default");
1525 fCommonOutput->SetSpecialOutput();
1526 // Warning("SetOutputEventHandler", " An automatic output container for the output tree was created.\nPlease use: mgr->GetCommonOutputContainer() to access it.");
1529 //______________________________________________________________________________
1530 void AliAnalysisManager::RegisterExtraFile(const char *fname)
1532 // This method is used externally to register output files which are not
1533 // connected to any output container, so that the manager can properly register,
1534 // retrieve or merge them when running in distributed mode. The file names are
1535 // separated by blancs. The method has to be called in MyAnalysisTask::LocalInit().
1536 if (fExtraFiles.Length()) fExtraFiles += " ";
1537 fExtraFiles += fname;
1540 //______________________________________________________________________________
1541 Bool_t AliAnalysisManager::GetFileFromWrapper(const char *filename, TList *source)
1543 // Copy a file from the location specified ina the wrapper with the same name from the source list.
1544 char full_path[512];
1546 TObject *pof = source->FindObject(filename);
1547 if (!pof || !pof->InheritsFrom("TProofOutputFile")) {
1548 Error("GetFileFromWrapper", "TProofOutputFile object not found in output list for file %s", filename);
1551 gROOT->ProcessLine(Form("sprintf((char*)0x%lx, \"%%s\", ((TProofOutputFile*)0x%lx)->GetOutputFileName();)", full_path, pof));
1552 gROOT->ProcessLine(Form("sprintf((char*)0x%lx, \"%%s\", gProof->GetUrl();)", ch_url));
1553 TString clientUrl(ch_url);
1554 TString full_path_str(full_path);
1555 if (clientUrl.Contains("localhost")){
1556 TObjArray* array = full_path_str.Tokenize ( "//" );
1557 TObjString *strobj = ( TObjString *)array->At(1);
1558 TObjArray* arrayPort = strobj->GetString().Tokenize ( ":" );
1559 TObjString *strobjPort = ( TObjString *) arrayPort->At(1);
1560 full_path_str.ReplaceAll(strobj->GetString().Data(),"localhost:PORT");
1561 full_path_str.ReplaceAll(":PORT",Form(":%s",strobjPort->GetString().Data()));
1562 if (fDebug > 1) Info("GetFileFromWrapper","Using tunnel from %s to %s",full_path_str.Data(),filename);
1567 Info("GetFileFromWrapper","Copying file %s from PROOF scratch space", full_path_str.Data());
1568 Bool_t gotit = TFile::Cp(full_path_str.Data(), filename);
1570 Error("GetFileFromWrapper", "Could not get file %s from proof scratch space", filename);
1574 //______________________________________________________________________________
1575 void AliAnalysisManager::GetAnalysisTypeString(TString &type) const
1577 // Fill analysis type in the provided string.
1579 case kLocalAnalysis:
1582 case kProofAnalysis:
1588 case kMixingAnalysis:
1593 //______________________________________________________________________________
1594 Bool_t AliAnalysisManager::ValidateOutputFiles() const
1596 // Validate all output files.
1597 TIter next(fOutputs);
1598 AliAnalysisDataContainer *output;
1599 TDirectory *cdir = gDirectory;
1600 TString openedFiles;
1601 while ((output=(AliAnalysisDataContainer*)next())) {
1602 if (output->IsRegisterDataset()) continue;
1603 TString filename = output->GetFileName();
1604 if (filename == "default") {
1605 if (!fOutputEventHandler) continue;
1606 filename = fOutputEventHandler->GetOutputFileName();
1607 // Main AOD may not be there
1608 if (gSystem->AccessPathName(filename)) continue;
1610 // Check if the file is closed
1611 if (openedFiles.Contains(filename)) continue;;
1612 TFile *file = (TFile*)gROOT->GetListOfFiles()->FindObject(filename);
1614 Warning("ValidateOutputs", "File %s was not closed. Closing.", filename.Data());
1617 file = TFile::Open(filename);
1618 if (!file || file->IsZombie() || file->TestBit(TFile::kRecovered)) {
1619 Error("ValidateOutputs", "Output file <%s> was not created or invalid", filename.Data());
1624 openedFiles += filename;
1631 //______________________________________________________________________________
1632 void AliAnalysisManager::ProgressBar(const char *opname, Long64_t current, Long64_t size, TStopwatch *watch, Bool_t last, Bool_t refresh)
1634 // Implements a nice text mode progress bar.
1635 static Long64_t icount = 0;
1636 static TString oname;
1637 static TString nname;
1638 static Long64_t ocurrent = 0;
1639 static Long64_t osize = 0;
1640 static Int_t oseconds = 0;
1641 static TStopwatch *owatch = 0;
1642 static Bool_t oneoftwo = kFALSE;
1643 static Int_t nrefresh = 0;
1644 static Int_t nchecks = 0;
1645 const char symbol[4] = {'=','\\','|','/'};
1646 char progress[11] = " ";
1647 Int_t ichar = icount%4;
1654 ocurrent = TMath::Abs(current);
1655 osize = TMath::Abs(size);
1656 if (ocurrent > osize) ocurrent=osize;
1666 if (owatch && !last) {
1668 time = owatch->RealTime();
1669 hours = (Int_t)(time/3600.);
1671 minutes = (Int_t)(time/60.);
1673 seconds = (Int_t)time;
1675 if (oseconds==seconds) {
1679 oneoftwo = !oneoftwo;
1683 if (refresh && oneoftwo) {
1685 if (nchecks <= 0) nchecks = nrefresh+1;
1686 Int_t pctdone = (Int_t)(100.*nrefresh/nchecks);
1687 oname = Form(" == %d%% ==", pctdone);
1689 Double_t percent = 100.0*ocurrent/osize;
1690 Int_t nchar = Int_t(percent/10);
1691 if (nchar>10) nchar=10;
1693 for (i=0; i<nchar; i++) progress[i] = '=';
1694 progress[nchar] = symbol[ichar];
1695 for (i=nchar+1; i<10; i++) progress[i] = ' ';
1696 progress[10] = '\0';
1699 if(size<10000) fprintf(stderr, "%s [%10s] %4lld ", oname.Data(), progress, ocurrent);
1700 else if(size<100000) fprintf(stderr, "%s [%10s] %5lld ",oname.Data(), progress, ocurrent);
1701 else fprintf(stderr, "%s [%10s] %7lld ",oname.Data(), progress, ocurrent);
1702 if (time>0.) fprintf(stderr, "[%6.2f %%] TIME %.2d:%.2d:%.2d \r", percent, hours, minutes, seconds);
1703 else fprintf(stderr, "[%6.2f %%]\r", percent);
1704 if (refresh && oneoftwo) oname = nname;
1705 if (owatch) owatch->Continue();
1714 fprintf(stderr, "\n");