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>
33 #include <TMethodCall.h>
39 #include "AliAnalysisSelector.h"
40 #include "AliAnalysisGrid.h"
41 #include "AliAnalysisTask.h"
42 #include "AliAnalysisDataContainer.h"
43 #include "AliAnalysisDataSlot.h"
44 #include "AliVEventHandler.h"
45 #include "AliVEventPool.h"
46 #include "AliSysInfo.h"
47 #include "AliAnalysisManager.h"
49 ClassImp(AliAnalysisManager)
51 AliAnalysisManager *AliAnalysisManager::fgAnalysisManager = NULL;
53 //______________________________________________________________________________
54 AliAnalysisManager::AliAnalysisManager(const char *name, const char *title)
57 fInputEventHandler(NULL),
58 fOutputEventHandler(NULL),
59 fMCtruthEventHandler(NULL),
63 fMode(kLocalAnalysis),
66 fSpecialOutputLocation(""),
78 // Default constructor.
79 fgAnalysisManager = this;
80 fTasks = new TObjArray();
81 fTopTasks = new TObjArray();
82 fZombies = new TObjArray();
83 fContainers = new TObjArray();
84 fInputs = new TObjArray();
85 fOutputs = new TObjArray();
89 //______________________________________________________________________________
90 AliAnalysisManager::AliAnalysisManager(const AliAnalysisManager& other)
93 fInputEventHandler(NULL),
94 fOutputEventHandler(NULL),
95 fMCtruthEventHandler(NULL),
100 fInitOK(other.fInitOK),
101 fDebug(other.fDebug),
102 fSpecialOutputLocation(""),
115 fTasks = new TObjArray(*other.fTasks);
116 fTopTasks = new TObjArray(*other.fTopTasks);
117 fZombies = new TObjArray(*other.fZombies);
118 fContainers = new TObjArray(*other.fContainers);
119 fInputs = new TObjArray(*other.fInputs);
120 fOutputs = new TObjArray(*other.fOutputs);
121 fgAnalysisManager = this;
124 //______________________________________________________________________________
125 AliAnalysisManager& AliAnalysisManager::operator=(const AliAnalysisManager& other)
128 if (&other != this) {
129 TNamed::operator=(other);
130 fInputEventHandler = other.fInputEventHandler;
131 fOutputEventHandler = other.fOutputEventHandler;
132 fMCtruthEventHandler = other.fMCtruthEventHandler;
133 fEventPool = other.fEventPool;
136 fNSysInfo = other.fNSysInfo;
138 fInitOK = other.fInitOK;
139 fDebug = other.fDebug;
140 fTasks = new TObjArray(*other.fTasks);
141 fTopTasks = new TObjArray(*other.fTopTasks);
142 fZombies = new TObjArray(*other.fZombies);
143 fContainers = new TObjArray(*other.fContainers);
144 fInputs = new TObjArray(*other.fInputs);
145 fOutputs = new TObjArray(*other.fOutputs);
147 fCommonOutput = NULL;
150 fgAnalysisManager = this;
155 //______________________________________________________________________________
156 AliAnalysisManager::~AliAnalysisManager()
159 if (fTasks) {fTasks->Delete(); delete fTasks;}
160 if (fTopTasks) delete fTopTasks;
161 if (fZombies) delete fZombies;
162 if (fContainers) {fContainers->Delete(); delete fContainers;}
163 if (fInputs) delete fInputs;
164 if (fOutputs) delete fOutputs;
165 if (fGridHandler) delete fGridHandler;
166 if (fgAnalysisManager==this) fgAnalysisManager = NULL;
169 //______________________________________________________________________________
170 Int_t AliAnalysisManager::GetEntry(Long64_t entry, Int_t getall)
172 // Read one entry of the tree or a whole branch.
173 if (fDebug > 0) printf("== AliAnalysisManager::GetEntry(%lld)\n", entry);
174 fCurrentEntry = entry;
175 return fTree ? fTree->GetTree()->GetEntry(entry, getall) : 0;
178 //______________________________________________________________________________
179 Bool_t AliAnalysisManager::Init(TTree *tree)
181 // The Init() function is called when the selector needs to initialize
182 // a new tree or chain. Typically here the branch addresses of the tree
183 // will be set. It is normaly not necessary to make changes to the
184 // generated code, but the routine can be extended by the user if needed.
185 // Init() will be called many times when running with PROOF.
186 Bool_t init = kFALSE;
187 if (!tree) return kFALSE; // Should not happen - protected in selector caller
189 printf("->AliAnalysisManager::Init(%s)\n", tree->GetName());
191 // Call InitTree of EventHandler
192 if (fOutputEventHandler) {
193 if (fMode == kProofAnalysis) {
194 init = fOutputEventHandler->Init(0x0, "proof");
196 init = fOutputEventHandler->Init(0x0, "local");
199 Error("Init", "Output event handler failed to initialize");
204 if (fInputEventHandler) {
205 if (fMode == kProofAnalysis) {
206 init = fInputEventHandler->Init(tree, "proof");
208 init = fInputEventHandler->Init(tree, "local");
211 Error("Init", "Input event handler failed to initialize tree");
215 // If no input event handler we need to get the tree once
217 if(!tree->GetTree()) {
218 Long64_t readEntry = tree->LoadTree(0);
219 if (readEntry == -2) {
220 Error("Init", "Input tree has no entry. Aborting");
226 if (fMCtruthEventHandler) {
227 if (fMode == kProofAnalysis) {
228 init = fMCtruthEventHandler->Init(0x0, "proof");
230 init = fMCtruthEventHandler->Init(0x0, "local");
233 Error("Init", "MC event handler failed to initialize");
238 if (!fInitOK) InitAnalysis();
239 if (!fInitOK) return kFALSE;
241 AliAnalysisDataContainer *top = fCommonInput;
242 if (!top) top = (AliAnalysisDataContainer*)fInputs->At(0);
244 Error("Init","No top input container !");
249 printf("<-AliAnalysisManager::Init(%s)\n", tree->GetName());
254 //______________________________________________________________________________
255 void AliAnalysisManager::SlaveBegin(TTree *tree)
257 // The SlaveBegin() function is called after the Begin() function.
258 // When running with PROOF SlaveBegin() is called on each slave server.
259 // The tree argument is deprecated (on PROOF 0 is passed).
260 if (fDebug > 0) printf("->AliAnalysisManager::SlaveBegin()\n");
261 static Bool_t isCalled = kFALSE;
262 Bool_t init = kFALSE;
263 Bool_t initOK = kTRUE;
265 TDirectory *curdir = gDirectory;
266 // Call SlaveBegin only once in case of mixing
267 if (isCalled && fMode==kMixingAnalysis) return;
268 // Call Init of EventHandler
269 if (fOutputEventHandler) {
270 if (fMode == kProofAnalysis) {
271 TIter nextout(fOutputs);
272 AliAnalysisDataContainer *c_aod;
273 while ((c_aod=(AliAnalysisDataContainer*)nextout())) if (!strcmp(c_aod->GetFileName(),"default")) break;
274 if (c_aod && c_aod->IsSpecialOutput()) {
276 if (fDebug > 1) printf(" Initializing special output file %s...\n", fOutputEventHandler->GetOutputFileName());
277 OpenProofFile(fOutputEventHandler->GetOutputFileName(), "RECREATE");
278 c_aod->SetFile(gFile);
279 init = fOutputEventHandler->Init("proofspecial");
280 if (!init) msg = "Failed to initialize output handler on worker using special proof output";
283 init = fOutputEventHandler->Init("proof");
284 if (!init) msg = "Failed to initialize output handler on worker";
287 init = fOutputEventHandler->Init("local");
288 if (!init) msg = "Failed to initialize output handler on worker";
291 if (!fSelector) Error("SlaveBegin", "Selector not set");
292 else if (!init) {fSelector->Abort(msg); fSelector->SetStatus(-1);}
295 if (fInputEventHandler) {
296 fInputEventHandler->SetInputTree(tree);
297 if (fMode == kProofAnalysis) {
298 init = fInputEventHandler->Init("proof");
299 if (!init) msg = "Failed to initialize input handler on worker";
301 init = fInputEventHandler->Init("local");
302 if (!init) msg = "Failed to initialize input handler";
305 if (!fSelector) Error("SlaveBegin", "Selector not set");
306 else if (!init) {fSelector->Abort(msg); fSelector->SetStatus(-1);}
309 if (fMCtruthEventHandler) {
310 if (fMode == kProofAnalysis) {
311 init = fMCtruthEventHandler->Init("proof");
312 if (!init) msg = "Failed to initialize MC handler on worker";
314 init = fMCtruthEventHandler->Init("local");
315 if (!init) msg = "Failed to initialize MC handler";
318 if (!fSelector) Error("SlaveBegin", "Selector not set");
319 else if (!init) {fSelector->Abort(msg); fSelector->SetStatus(-1);}
321 if (curdir) curdir->cd();
325 AliAnalysisTask *task;
326 // Call CreateOutputObjects for all tasks
327 while ((task=(AliAnalysisTask*)next())) {
329 task->CreateOutputObjects();
330 if (curdir) curdir->cd();
332 if (fDebug > 0) printf("<-AliAnalysisManager::SlaveBegin()\n");
335 //______________________________________________________________________________
336 Bool_t AliAnalysisManager::Notify()
338 // The Notify() function is called when a new file is opened. This
339 // can be either for a new TTree in a TChain or when when a new TTree
340 // is started when using PROOF. It is normaly not necessary to make changes
341 // to the generated code, but the routine can be extended by the
342 // user if needed. The return value is currently not used.
343 if (!fTree) return kFALSE;
345 TFile *curfile = fTree->GetCurrentFile();
347 Error("Notify","No current file");
351 if (fDebug > 0) printf("->AliAnalysisManager::Notify() file: %s\n", curfile->GetName());
353 AliAnalysisTask *task;
354 // Call Notify for all tasks
355 while ((task=(AliAnalysisTask*)next()))
358 // Call Notify of the event handlers
359 if (fInputEventHandler) {
360 fInputEventHandler->Notify(curfile->GetName());
363 if (fOutputEventHandler) {
364 fOutputEventHandler->Notify(curfile->GetName());
367 if (fMCtruthEventHandler) {
368 fMCtruthEventHandler->Notify(curfile->GetName());
370 if (fDebug > 0) printf("<-AliAnalysisManager::Notify()\n");
374 //______________________________________________________________________________
375 Bool_t AliAnalysisManager::Process(Long64_t entry)
377 // The Process() function is called for each entry in the tree (or possibly
378 // keyed object in the case of PROOF) to be processed. The entry argument
379 // specifies which entry in the currently loaded tree is to be processed.
380 // It can be passed to either TTree::GetEntry() or TBranch::GetEntry()
381 // to read either all or the required parts of the data. When processing
382 // keyed objects with PROOF, the object is already loaded and is available
383 // via the fObject pointer.
385 // This function should contain the "body" of the analysis. It can contain
386 // simple or elaborate selection criteria, run algorithms on the data
387 // of the event and typically fill histograms.
389 // WARNING when a selector is used with a TChain, you must use
390 // the pointer to the current TTree to call GetEntry(entry).
391 // The entry is always the local entry number in the current tree.
392 // Assuming that fChain is the pointer to the TChain being processed,
393 // use fChain->GetTree()->GetEntry(entry).
394 if (fDebug > 0) printf("->AliAnalysisManager::Process(%lld)\n", entry);
396 if (fInputEventHandler) fInputEventHandler ->BeginEvent(entry);
397 if (fOutputEventHandler) fOutputEventHandler ->BeginEvent(entry);
398 if (fMCtruthEventHandler) fMCtruthEventHandler->BeginEvent(entry);
402 if (fDebug > 0) printf("<-AliAnalysisManager::Process()\n");
406 //______________________________________________________________________________
407 void AliAnalysisManager::PackOutput(TList *target)
409 // Pack all output data containers in the output list. Called at SlaveTerminate
410 // stage in PROOF case for each slave.
411 if (fDebug > 0) printf("->AliAnalysisManager::PackOutput()\n");
413 Error("PackOutput", "No target. Aborting.");
416 if (fInputEventHandler) fInputEventHandler ->Terminate();
417 if (fOutputEventHandler) fOutputEventHandler ->Terminate();
418 if (fMCtruthEventHandler) fMCtruthEventHandler->Terminate();
420 // Call FinishTaskOutput() for each event loop task (not called for
421 // post-event loop tasks - use Terminate() fo those)
422 TIter nexttask(fTasks);
423 AliAnalysisTask *task;
424 while ((task=(AliAnalysisTask*)nexttask())) {
425 if (!task->IsPostEventLoop()) {
426 if (fDebug > 0) printf("->FinishTaskOutput: task %s\n", task->GetName());
427 task->FinishTaskOutput();
428 if (fDebug > 0) printf("<-FinishTaskOutput: task %s\n", task->GetName());
432 if (fMode == kProofAnalysis) {
433 TIter next(fOutputs);
434 AliAnalysisDataContainer *output;
435 Bool_t isManagedByHandler = kFALSE;
436 while ((output=(AliAnalysisDataContainer*)next())) {
437 // Do not consider outputs of post event loop tasks
438 isManagedByHandler = kFALSE;
439 if (output->GetProducer()->IsPostEventLoop()) continue;
440 const char *filename = output->GetFileName();
441 if (!(strcmp(filename, "default")) && fOutputEventHandler) {
442 isManagedByHandler = kTRUE;
443 filename = fOutputEventHandler->GetOutputFileName();
445 // Check if data was posted to this container. If not, issue an error.
446 if (!output->GetData() && !isManagedByHandler) {
447 Error("PackOutput", "No data for output container %s. Forgot to PostData ?\n", output->GetName());
450 if (!output->IsSpecialOutput()) {
452 if (strlen(filename) && !isManagedByHandler) {
453 // File resident outputs
454 TFile *file = output->GetFile();
455 // Backup current folder
456 TDirectory *opwd = gDirectory;
457 // Create file if not existing and register to container.
458 if (file) file->cd();
459 else file = new TFile(filename, "RECREATE");
460 if (file->IsZombie()) {
461 Fatal("PackOutput", "Could not recreate file %s\n", filename);
464 output->SetFile(file);
465 // Clear file list to release object ownership to user.
467 // Save data to file, then close.
468 if (output->GetData()->InheritsFrom(TCollection::Class())) {
469 // If data is a collection, we set the name of the collection
470 // as the one of the container and we save as a single key.
471 TCollection *coll = (TCollection*)output->GetData();
472 coll->SetName(output->GetName());
473 coll->Write(output->GetName(), TObject::kSingleKey);
475 if (output->GetData()->InheritsFrom(TTree::Class())) {
476 TTree *tree = (TTree*)output->GetData();
477 tree->SetDirectory(file);
480 output->GetData()->Write();
483 if (fDebug > 1) printf("PackOutput %s: memory merge, file resident output\n", output->GetName());
485 printf(" file %s listing content:\n", filename);
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);
506 TDirectory *opwd = gDirectory;
507 TFile *file = output->GetFile();
508 if (fDebug > 1 && file) printf("PackOutput %s: file merge, special output\n", output->GetName());
509 if (isManagedByHandler) {
510 // Terminate IO for files managed by the output handler
511 if (file) file->Write();
512 if (file && fDebug > 2) {
513 printf(" handled file %s listing content:\n", file->GetName());
516 fOutputEventHandler->TerminateIO();
521 AliAnalysisTask *producer = output->GetProducer();
523 "File %s for special container %s was NOT opened in %s::CreateOutputObjects !!!",
524 output->GetFileName(), output->GetName(), producer->ClassName());
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());
549 TString outFilename = file->GetName();
551 // Restore current directory
552 if (opwd) opwd->cd();
553 // Check if a special output location was provided or the output files have to be merged
554 if (strlen(fSpecialOutputLocation.Data())) {
555 TString remote = fSpecialOutputLocation;
557 Int_t gid = gROOT->ProcessLine("gProofServ->GetGroupId();");
558 remote += Form("%s_%d_", gSystem->HostName(), gid);
559 remote += output->GetFileName();
560 TFile::Cp ( outFilename.Data(), remote.Data() );
562 // No special location specified-> use TProofOutputFile as merging utility
563 // The file at this output slot must be opened in CreateOutputObjects
564 if (fDebug > 1) printf(" File %s to be merged...\n", output->GetFileName());
569 if (fDebug > 0) printf("<-AliAnalysisManager::PackOutput: output list contains %d containers\n", target->GetSize());
572 //______________________________________________________________________________
573 void AliAnalysisManager::ImportWrappers(TList *source)
575 // Import data in output containers from wrappers coming in source.
576 if (fDebug > 0) printf("->AliAnalysisManager::ImportWrappers()\n");
577 TIter next(fOutputs);
578 AliAnalysisDataContainer *cont;
579 AliAnalysisDataWrapper *wrap;
581 Bool_t inGrid = (fMode == kGridAnalysis)?kTRUE:kFALSE;
582 while ((cont=(AliAnalysisDataContainer*)next())) {
584 if (cont->GetProducer()->IsPostEventLoop() && !inGrid) continue;
585 const char *filename = cont->GetFileName();
586 Bool_t isManagedByHandler = kFALSE;
587 if (!(strcmp(filename, "default")) && fOutputEventHandler) {
588 isManagedByHandler = kTRUE;
589 filename = fOutputEventHandler->GetOutputFileName();
591 if (cont->IsSpecialOutput() || inGrid) {
592 if (strlen(fSpecialOutputLocation.Data()) && !isManagedByHandler) continue;
593 // Copy merged file from PROOF scratch space.
594 // In case of grid the files are already in the current directory.
598 TObject *pof = source->FindObject(filename);
599 if (!pof || !pof->InheritsFrom("TProofOutputFile")) {
600 Error("ImportWrappers", "TProofOutputFile object not found in output list for container %s", cont->GetName());
603 gROOT->ProcessLine(Form("sprintf((char*)0x%lx, \"%%s\", ((TProofOutputFile*)0x%lx)->GetOutputFileName();)", full_path, pof));
604 gROOT->ProcessLine(Form("sprintf((char*)0x%lx, \"%%s\", gProof->GetUrl();)", ch_url));
605 TString clientUrl(ch_url);
606 TString full_path_str(full_path);
607 if (clientUrl.Contains("localhost")){
608 TObjArray* array = full_path_str.Tokenize ( "//" );
609 TObjString *strobj = ( TObjString *)array->At(1);
610 TObjArray* arrayPort = strobj->GetString().Tokenize ( ":" );
611 TObjString *strobjPort = ( TObjString *) arrayPort->At(1);
612 full_path_str.ReplaceAll(strobj->GetString().Data(),"localhost:PORT");
613 full_path_str.ReplaceAll(":PORT",Form(":%s",strobjPort->GetString().Data()));
614 if (fDebug > 1) Info("ImportWrappers","Using tunnel from %s to %s",full_path_str.Data(),filename);
617 printf(" Copying file %s from PROOF scratch space\n", full_path_str.Data());
618 Bool_t gotit = TFile::Cp(full_path_str.Data(), filename);
620 Error("ImportWrappers", "Could not get file %s from proof scratch space", cont->GetFileName());
624 // Normally we should connect data from the copied file to the
625 // corresponding output container, but it is not obvious how to do this
626 // automatically if several objects in file...
627 TFile *f = TFile::Open(filename, "READ");
629 Error("ImportWrappers", "Cannot open file %s in read-only mode", filename);
633 // Try to fetch first a list object having the container name.
634 obj = f->Get(cont->GetName());
636 // Fetch first object from file having the container type.
637 TIter nextkey(f->GetListOfKeys());
639 while ((key=(TKey*)nextkey())) {
640 obj = f->Get(key->GetName());
641 if (obj && obj->IsA()->InheritsFrom(cont->GetType())) break;
645 Error("ImportWrappers", "Could not find object for container %s in file %s", cont->GetName(), filename);
648 wrap = new AliAnalysisDataWrapper(obj);
649 wrap->SetDeleteData(kFALSE);
651 if (!wrap) wrap = (AliAnalysisDataWrapper*)source->FindObject(cont->GetName());
653 Error("ImportWrappers","Container %s not found in analysis output !", cont->GetName());
658 printf(" Importing data for container %s", cont->GetName());
659 if (strlen(filename)) printf(" -> file %s\n", filename);
662 cont->ImportData(wrap);
664 if (fDebug > 0) printf("<-AliAnalysisManager::ImportWrappers(): %d containers imported\n", icont);
667 //______________________________________________________________________________
668 void AliAnalysisManager::UnpackOutput(TList *source)
670 // Called by AliAnalysisSelector::Terminate only on the client.
671 if (fDebug > 0) printf("->AliAnalysisManager::UnpackOutput()\n");
673 Error("UnpackOutput", "No target. Aborting.");
676 if (fDebug > 1) printf(" Source list contains %d containers\n", source->GetSize());
678 if (fMode == kProofAnalysis) ImportWrappers(source);
680 TIter next(fOutputs);
681 AliAnalysisDataContainer *output;
682 while ((output=(AliAnalysisDataContainer*)next())) {
683 if (!output->GetData()) continue;
684 // Check if there are client tasks that run post event loop
685 if (output->HasConsumers()) {
686 // Disable event loop semaphore
687 output->SetPostEventLoop(kTRUE);
688 TObjArray *list = output->GetConsumers();
689 Int_t ncons = list->GetEntriesFast();
690 for (Int_t i=0; i<ncons; i++) {
691 AliAnalysisTask *task = (AliAnalysisTask*)list->At(i);
692 task->CheckNotify(kTRUE);
693 // If task is active, execute it
694 if (task->IsPostEventLoop() && task->IsActive()) {
695 if (fDebug > 0) printf("== Executing post event loop task %s\n", task->GetName());
701 if (fDebug > 0) printf("<-AliAnalysisManager::UnpackOutput()\n");
704 //______________________________________________________________________________
705 void AliAnalysisManager::Terminate()
707 // The Terminate() function is the last function to be called during
708 // a query. It always runs on the client, it can be used to present
709 // the results graphically.
710 if (fDebug > 0) printf("->AliAnalysisManager::Terminate()\n");
711 AliAnalysisTask *task;
713 // Call Terminate() for tasks
714 while ((task=(AliAnalysisTask*)next())) task->Terminate();
716 TIter next1(fOutputs);
717 AliAnalysisDataContainer *output;
718 while ((output=(AliAnalysisDataContainer*)next1())) {
719 // Special outputs or grid files have the files already closed and written.
720 if (fMode == kGridAnalysis) continue;
721 if (output->IsSpecialOutput()&&(fMode == kProofAnalysis)) continue;
722 const char *filename = output->GetFileName();
723 if (!(strcmp(filename, "default"))) {
724 if (fOutputEventHandler) filename = fOutputEventHandler->GetOutputFileName();
725 TFile *aodfile = (TFile*)gROOT->GetListOfFiles()->FindObject(filename);
727 if (fDebug > 1) printf("Writing output handler file: %s\n", filename);
732 if (!strlen(filename)) continue;
733 if (!output->GetData()) continue;
734 TFile *file = output->GetFile();
735 TDirectory *opwd = gDirectory;
736 file = (TFile*)gROOT->GetListOfFiles()->FindObject(filename);
737 if (!file) file = new TFile(filename, "RECREATE");
738 if (file->IsZombie()) continue;
739 output->SetFile(file);
741 if (fDebug > 1) printf(" writing output data %s to file %s\n", output->GetData()->GetName(), file->GetName());
742 if (output->GetData()->InheritsFrom(TCollection::Class())) {
743 // If data is a collection, we set the name of the collection
744 // as the one of the container and we save as a single key.
745 TCollection *coll = (TCollection*)output->GetData();
746 coll->SetName(output->GetName());
747 coll->Write(output->GetName(), TObject::kSingleKey);
749 if (output->GetData()->InheritsFrom(TTree::Class())) {
750 TTree *tree = (TTree*)output->GetData();
751 tree->SetDirectory(file);
754 output->GetData()->Write();
757 if (opwd) opwd->cd();
760 while ((output=(AliAnalysisDataContainer*)next1())) {
761 // Close all files at output
762 TDirectory *opwd = gDirectory;
763 if (output->GetFile()) output->GetFile()->Close();
764 if (opwd) opwd->cd();
767 if (fInputEventHandler) fInputEventHandler ->TerminateIO();
768 if (fOutputEventHandler) fOutputEventHandler ->TerminateIO();
769 if (fMCtruthEventHandler) fMCtruthEventHandler->TerminateIO();
771 Bool_t getsysInfo = ((fNSysInfo>0) && (fMode==kLocalAnalysis))?kTRUE:kFALSE;
773 TDirectory *cdir = gDirectory;
774 TFile f("syswatch.root", "RECREATE");
776 TTree *tree = AliSysInfo::MakeTree("syswatch.log");
777 tree->SetMarkerStyle(kCircle);
778 tree->SetMarkerColor(kBlue);
779 tree->SetMarkerSize(0.5);
780 if (!gROOT->IsBatch()) {
781 tree->SetAlias("event", "id0");
782 tree->SetAlias("memUSED", "mi.fMemUsed");
783 new TCanvas("SysInfo","SysInfo",10,10,800,600);
784 tree->Draw("memUSED:event","","", 1234567890, 0);
790 if (cdir) cdir->cd();
792 if (fDebug > 0) printf("<-AliAnalysisManager::Terminate()\n");
795 //______________________________________________________________________________
796 void AliAnalysisManager::AddTask(AliAnalysisTask *task)
798 // Adds a user task to the global list of tasks.
799 if (fTasks->FindObject(task)) {
800 Warning("AddTask", "Task %s: the same object already added to the analysis manager. Not adding.", task->GetName());
803 task->SetActive(kFALSE);
807 //______________________________________________________________________________
808 AliAnalysisTask *AliAnalysisManager::GetTask(const char *name) const
810 // Retreive task by name.
811 if (!fTasks) return NULL;
812 return (AliAnalysisTask*)fTasks->FindObject(name);
815 //______________________________________________________________________________
816 AliAnalysisDataContainer *AliAnalysisManager::CreateContainer(const char *name,
817 TClass *datatype, EAliAnalysisContType type, const char *filename)
819 // Create a data container of a certain type. Types can be:
820 // kExchangeContainer = 0, used to exchange date between tasks
821 // kInputContainer = 1, used to store input data
822 // kOutputContainer = 2, used for posting results
823 if (fContainers->FindObject(name)) {
824 Error("CreateContainer","A container named %s already defined !\n",name);
827 AliAnalysisDataContainer *cont = new AliAnalysisDataContainer(name, datatype);
828 fContainers->Add(cont);
830 case kInputContainer:
833 case kOutputContainer:
835 if (filename && strlen(filename)) {
836 cont->SetFileName(filename);
837 cont->SetDataOwned(kFALSE); // data owned by the file
840 case kExchangeContainer:
846 //______________________________________________________________________________
847 Bool_t AliAnalysisManager::ConnectInput(AliAnalysisTask *task, Int_t islot,
848 AliAnalysisDataContainer *cont)
850 // Connect input of an existing task to a data container.
852 Error("ConnectInput", "Task pointer is NULL");
855 if (!fTasks->FindObject(task)) {
857 Info("ConnectInput", "Task %s was not registered. Now owned by analysis manager", task->GetName());
859 Bool_t connected = task->ConnectInput(islot, cont);
863 //______________________________________________________________________________
864 Bool_t AliAnalysisManager::ConnectOutput(AliAnalysisTask *task, Int_t islot,
865 AliAnalysisDataContainer *cont)
867 // Connect output of an existing task to a data container.
869 Error("ConnectOutput", "Task pointer is NULL");
872 if (!fTasks->FindObject(task)) {
874 Warning("ConnectOutput", "Task %s not registered. Now owned by analysis manager", task->GetName());
876 Bool_t connected = task->ConnectOutput(islot, cont);
880 //______________________________________________________________________________
881 void AliAnalysisManager::CleanContainers()
883 // Clean data from all containers that have already finished all client tasks.
884 TIter next(fContainers);
885 AliAnalysisDataContainer *cont;
886 while ((cont=(AliAnalysisDataContainer *)next())) {
887 if (cont->IsOwnedData() &&
888 cont->IsDataReady() &&
889 cont->ClientsExecuted()) cont->DeleteData();
893 //______________________________________________________________________________
894 Bool_t AliAnalysisManager::InitAnalysis()
896 // Initialization of analysis chain of tasks. Should be called after all tasks
897 // and data containers are properly connected
898 // Check for input/output containers
900 // Check for top tasks (depending only on input data containers)
901 if (!fTasks->First()) {
902 Error("InitAnalysis", "Analysis has no tasks !");
906 AliAnalysisTask *task;
907 AliAnalysisDataContainer *cont;
910 Bool_t iszombie = kFALSE;
911 Bool_t istop = kTRUE;
913 while ((task=(AliAnalysisTask*)next())) {
916 Int_t ninputs = task->GetNinputs();
917 for (i=0; i<ninputs; i++) {
918 cont = task->GetInputSlot(i)->GetContainer();
926 Error("InitAnalysis", "Input slot %d of task %s has no container connected ! Declared zombie...",
929 if (iszombie) continue;
930 // Check if cont is an input container
931 if (istop && !fInputs->FindObject(cont)) istop=kFALSE;
932 // Connect to parent task
936 fTopTasks->Add(task);
940 Error("InitAnalysis", "No top task defined. At least one task should be connected only to input containers");
943 // Check now if there are orphan tasks
944 for (i=0; i<ntop; i++) {
945 task = (AliAnalysisTask*)fTopTasks->At(i);
950 while ((task=(AliAnalysisTask*)next())) {
951 if (!task->IsUsed()) {
953 Warning("InitAnalysis", "Task %s is orphan", task->GetName());
956 // Check the task hierarchy (no parent task should depend on data provided
957 // by a daughter task)
958 for (i=0; i<ntop; i++) {
959 task = (AliAnalysisTask*)fTopTasks->At(i);
960 if (task->CheckCircularDeps()) {
961 Error("InitAnalysis", "Found illegal circular dependencies between following tasks:");
966 // Check that all containers feeding post-event loop tasks are in the outputs list
967 TIter nextcont(fContainers); // loop over all containers
968 while ((cont=(AliAnalysisDataContainer*)nextcont())) {
969 if (!cont->IsPostEventLoop() && !fOutputs->FindObject(cont)) {
970 if (cont->HasConsumers()) {
971 // Check if one of the consumers is post event loop
972 TIter nextconsumer(cont->GetConsumers());
973 while ((task=(AliAnalysisTask*)nextconsumer())) {
974 if (task->IsPostEventLoop()) {
982 // Check if all special output containers have a file name provided
983 TIter nextout(fOutputs);
984 while ((cont=(AliAnalysisDataContainer*)nextout())) {
985 if (cont->IsSpecialOutput() && !strlen(cont->GetFileName())) {
986 Error("InitAnalysis", "Wrong container %s : a file name MUST be provided for special outputs", cont->GetName());
994 //______________________________________________________________________________
995 void AliAnalysisManager::PrintStatus(Option_t *option) const
997 // Print task hierarchy.
999 Info("PrintStatus", "Analysis manager %s not initialized : call InitAnalysis() first", GetName());
1002 Bool_t getsysInfo = ((fNSysInfo>0) && (fMode==kLocalAnalysis))?kTRUE:kFALSE;
1004 Info("PrintStatus", "System information will be collected each %lld events", fNSysInfo);
1005 TIter next(fTopTasks);
1006 AliAnalysisTask *task;
1007 while ((task=(AliAnalysisTask*)next()))
1008 task->PrintTask(option);
1011 //______________________________________________________________________________
1012 void AliAnalysisManager::ResetAnalysis()
1014 // Reset all execution flags and clean containers.
1018 //______________________________________________________________________________
1019 void AliAnalysisManager::StartAnalysis(const char *type, TTree *tree, Long64_t nentries, Long64_t firstentry)
1021 // Start analysis for this manager. Analysis task can be: LOCAL, PROOF, GRID or
1022 // MIX. Process nentries starting from firstentry
1024 Error("StartAnalysis","Analysis manager was not initialized !");
1027 if (fDebug > 0) printf("StartAnalysis %s\n",GetName());
1028 TString anaType = type;
1030 fMode = kLocalAnalysis;
1031 Bool_t runlocalinit = kTRUE;
1032 if (anaType.Contains("file")) runlocalinit = kFALSE;
1033 if (anaType.Contains("proof")) fMode = kProofAnalysis;
1034 else if (anaType.Contains("grid")) fMode = kGridAnalysis;
1035 else if (anaType.Contains("mix")) fMode = kMixingAnalysis;
1037 if (fMode == kGridAnalysis) {
1038 if (!fGridHandler) {
1039 Error("StartAnalysis", "Cannot start grid analysis without a grid handler.");
1040 Info("===", "Add an AliAnalysisAlien object as plugin for this manager and configure it.");
1043 // Write analysis manager in the analysis file
1044 cout << "===== RUNNING GRID ANALYSIS: " << GetName() << endl;
1045 // run local task configuration
1046 TIter nextTask(fTasks);
1047 AliAnalysisTask *task;
1048 while ((task=(AliAnalysisTask*)nextTask())) {
1051 fGridHandler->StartAnalysis(nentries, firstentry);
1053 // Terminate grid analysis
1054 if (fSelector && fSelector->GetStatus() == -1) return;
1055 if (fGridHandler->GetRunMode() == AliAnalysisGrid::kOffline) return;
1056 cout << "===== MERGING OUTPUTS REGISTERED BY YOUR ANALYSIS JOB: " << GetName() << endl;
1057 if (!fGridHandler->MergeOutputs()) {
1058 // Return if outputs could not be merged or if it alien handler
1059 // was configured for offline mode or local testing.
1062 ImportWrappers(NULL);
1067 SetEventLoop(kFALSE);
1068 // Enable event loop mode if a tree was provided
1069 if (tree || fMode==kMixingAnalysis) SetEventLoop(kTRUE);
1072 TString ttype = "TTree";
1073 if (tree && tree->IsA() == TChain::Class()) {
1074 chain = (TChain*)tree;
1075 if (!chain || !chain->GetListOfFiles()->First()) {
1076 Error("StartAnalysis", "Cannot process null or empty chain...");
1082 // Initialize locally all tasks (happens for all modes)
1084 AliAnalysisTask *task;
1086 while ((task=(AliAnalysisTask*)next())) {
1092 case kLocalAnalysis:
1094 TIter nextT(fTasks);
1095 // Call CreateOutputObjects for all tasks
1096 while ((task=(AliAnalysisTask*)nextT())) {
1097 TDirectory *curdir = gDirectory;
1098 task->CreateOutputObjects();
1099 if (curdir) curdir->cd();
1105 // Run tree-based analysis via AliAnalysisSelector
1106 cout << "===== RUNNING LOCAL ANALYSIS " << GetName() << " ON TREE " << tree->GetName() << endl;
1107 fSelector = new AliAnalysisSelector(this);
1108 tree->Process(fSelector, "", nentries, firstentry);
1110 case kProofAnalysis:
1111 if (!gROOT->GetListOfProofs() || !gROOT->GetListOfProofs()->GetEntries()) {
1112 printf("StartAnalysis: no PROOF!!!\n");
1115 sprintf(line, "gProof->AddInput((TObject*)0x%lx);", (ULong_t)this);
1116 gROOT->ProcessLine(line);
1119 cout << "===== RUNNING PROOF ANALYSIS " << GetName() << " ON CHAIN " << chain->GetName() << endl;
1120 chain->Process("AliAnalysisSelector", "", nentries, firstentry);
1122 printf("StartAnalysis: no chain\n");
1127 Warning("StartAnalysis", "GRID analysis mode not implemented. Running local.");
1129 case kMixingAnalysis:
1130 // Run event mixing analysis
1132 Error("StartAnalysis", "Cannot run event mixing without event pool");
1135 cout << "===== RUNNING EVENT MIXING ANALYSIS " << GetName() << endl;
1136 fSelector = new AliAnalysisSelector(this);
1137 while ((chain=fEventPool->GetNextChain())) {
1139 // Call NotifyBinChange for all tasks
1140 while ((task=(AliAnalysisTask*)next()))
1141 if (!task->IsPostEventLoop()) task->NotifyBinChange();
1142 chain->Process(fSelector);
1144 PackOutput(fSelector->GetOutputList());
1149 //______________________________________________________________________________
1150 void AliAnalysisManager::StartAnalysis(const char *type, const char *dataset, Long64_t nentries, Long64_t firstentry)
1152 // Start analysis for this manager on a given dataset. Analysis task can be:
1153 // LOCAL, PROOF or GRID. Process nentries starting from firstentry.
1155 Error("StartAnalysis","Analysis manager was not initialized !");
1158 if (fDebug > 0) printf("StartAnalysis %s\n",GetName());
1159 TString anaType = type;
1161 if (!anaType.Contains("proof")) {
1162 Error("StartAnalysis", "Cannot process datasets in %s mode. Try PROOF.", type);
1165 fMode = kProofAnalysis;
1167 SetEventLoop(kTRUE);
1168 // Set the dataset flag
1169 TObject::SetBit(kUseDataSet);
1172 // Initialize locally all tasks
1174 AliAnalysisTask *task;
1175 while ((task=(AliAnalysisTask*)next())) {
1179 if (!gROOT->GetListOfProofs() || !gROOT->GetListOfProofs()->GetEntries()) {
1180 printf("StartAnalysis: no PROOF!!!\n");
1183 sprintf(line, "gProof->AddInput((TObject*)0x%lx);", (ULong_t)this);
1184 gROOT->ProcessLine(line);
1185 sprintf(line, "gProof->GetDataSet(\"%s\");", dataset);
1186 if (!gROOT->ProcessLine(line)) {
1187 Error("StartAnalysis", "Dataset %s not found", dataset);
1190 sprintf(line, "gProof->Process(\"%s\", \"AliAnalysisSelector\", \"\", %lld, %lld);",
1191 dataset, nentries, firstentry);
1192 cout << "===== RUNNING PROOF ANALYSIS " << GetName() << " ON DATASET " << dataset << endl;
1193 gROOT->ProcessLine(line);
1196 //______________________________________________________________________________
1197 TFile *AliAnalysisManager::OpenProofFile(const char *filename, const char *option)
1199 // Opens a special output file used in PROOF.
1201 if (fMode!=kProofAnalysis || !fSelector) {
1202 Error("OpenProofFile","Cannot open PROOF file %s",filename);
1205 sprintf(line, "TProofOutputFile *pf = new TProofOutputFile(\"%s\");", filename);
1206 if (fDebug > 1) printf("=== %s\n", line);
1207 gROOT->ProcessLine(line);
1208 sprintf(line, "pf->OpenFile(\"%s\");", option);
1209 gROOT->ProcessLine(line);
1211 gROOT->ProcessLine("pf->Print()");
1212 printf(" == proof file name: %s\n", gFile->GetName());
1214 sprintf(line, "((TList*)0x%lx)->Add(pf);",(ULong_t)fSelector->GetOutputList());
1215 if (fDebug > 1) printf("=== %s\n", line);
1216 gROOT->ProcessLine(line);
1220 //______________________________________________________________________________
1221 void AliAnalysisManager::ExecAnalysis(Option_t *option)
1223 // Execute analysis.
1224 static Long64_t ncalls = 0;
1225 Bool_t getsysInfo = ((fNSysInfo>0) && (fMode==kLocalAnalysis))?kTRUE:kFALSE;
1226 if (getsysInfo && ncalls==0) AliSysInfo::AddStamp("Start", (Int_t)ncalls);
1229 Error("ExecAnalysis", "Analysis manager was not initialized !");
1232 AliAnalysisTask *task;
1233 // Check if the top tree is active.
1236 // De-activate all tasks
1237 while ((task=(AliAnalysisTask*)next())) task->SetActive(kFALSE);
1238 AliAnalysisDataContainer *cont = fCommonInput;
1239 if (!cont) cont = (AliAnalysisDataContainer*)fInputs->At(0);
1241 Error("ExecAnalysis","Cannot execute analysis in TSelector mode without at least one top container");
1244 cont->SetData(fTree); // This will notify all consumers
1245 Long64_t entry = fTree->GetTree()->GetReadEntry();
1248 // Call BeginEvent() for optional input/output and MC services
1249 if (fInputEventHandler) fInputEventHandler ->BeginEvent(entry);
1250 if (fOutputEventHandler) fOutputEventHandler ->BeginEvent(entry);
1251 if (fMCtruthEventHandler) fMCtruthEventHandler->BeginEvent(entry);
1253 // Execute the tasks
1254 // TIter next1(cont->GetConsumers());
1255 TIter next1(fTopTasks);
1256 while ((task=(AliAnalysisTask*)next1())) {
1258 cout << " Executing task " << task->GetName() << endl;
1261 task->ExecuteTask(option);
1264 // Call FinishEvent() for optional output and MC services
1265 if (fInputEventHandler) fInputEventHandler ->FinishEvent();
1266 if (fOutputEventHandler) fOutputEventHandler ->FinishEvent();
1267 if (fMCtruthEventHandler) fMCtruthEventHandler->FinishEvent();
1268 // Gather system information if requested
1269 if (getsysInfo && ((ncalls%fNSysInfo)==0))
1270 AliSysInfo::AddStamp(Form("Event#%lld",ncalls),(Int_t)ncalls);
1273 // The event loop is not controlled by TSelector
1275 // Call BeginEvent() for optional input/output and MC services
1276 if (fInputEventHandler) fInputEventHandler ->BeginEvent(-1);
1277 if (fOutputEventHandler) fOutputEventHandler ->BeginEvent(-1);
1278 if (fMCtruthEventHandler) fMCtruthEventHandler->BeginEvent(-1);
1279 TIter next2(fTopTasks);
1280 while ((task=(AliAnalysisTask*)next2())) {
1281 task->SetActive(kTRUE);
1283 cout << " Executing task " << task->GetName() << endl;
1285 task->ExecuteTask(option);
1288 // Call FinishEvent() for optional output and MC services
1289 if (fInputEventHandler) fInputEventHandler ->FinishEvent();
1290 if (fOutputEventHandler) fOutputEventHandler ->FinishEvent();
1291 if (fMCtruthEventHandler) fMCtruthEventHandler->FinishEvent();
1294 //______________________________________________________________________________
1295 void AliAnalysisManager::FinishAnalysis()
1300 //______________________________________________________________________________
1301 void AliAnalysisManager::SetInputEventHandler(AliVEventHandler* handler)
1303 // Set the input event handler and create a container for it.
1304 fInputEventHandler = handler;
1305 fCommonInput = CreateContainer("cAUTO_INPUT", TChain::Class(), AliAnalysisManager::kInputContainer);
1306 Warning("SetInputEventHandler", " An automatic input container for the input chain was created.\nPlease use: mgr->GetCommonInputContainer() to access it.");
1309 //______________________________________________________________________________
1310 void AliAnalysisManager::SetOutputEventHandler(AliVEventHandler* handler)
1312 // Set the input event handler and create a container for it.
1313 fOutputEventHandler = handler;
1314 fCommonOutput = CreateContainer("cAUTO_OUTPUT", TTree::Class(), AliAnalysisManager::kOutputContainer, "default");
1315 Warning("SetOutputEventHandler", " An automatic output container for the output tree was created.\nPlease use: mgr->GetCommonOutputContainer() to access it.");