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(""),
76 // Default constructor.
77 fgAnalysisManager = this;
78 fTasks = new TObjArray();
79 fTopTasks = new TObjArray();
80 fZombies = new TObjArray();
81 fContainers = new TObjArray();
82 fInputs = new TObjArray();
83 fOutputs = new TObjArray();
87 //______________________________________________________________________________
88 AliAnalysisManager::AliAnalysisManager(const AliAnalysisManager& other)
91 fInputEventHandler(NULL),
92 fOutputEventHandler(NULL),
93 fMCtruthEventHandler(NULL),
98 fInitOK(other.fInitOK),
100 fSpecialOutputLocation(""),
111 fTasks = new TObjArray(*other.fTasks);
112 fTopTasks = new TObjArray(*other.fTopTasks);
113 fZombies = new TObjArray(*other.fZombies);
114 fContainers = new TObjArray(*other.fContainers);
115 fInputs = new TObjArray(*other.fInputs);
116 fOutputs = new TObjArray(*other.fOutputs);
117 fgAnalysisManager = this;
120 //______________________________________________________________________________
121 AliAnalysisManager& AliAnalysisManager::operator=(const AliAnalysisManager& other)
124 if (&other != this) {
125 TNamed::operator=(other);
126 fInputEventHandler = other.fInputEventHandler;
127 fOutputEventHandler = other.fOutputEventHandler;
128 fMCtruthEventHandler = other.fMCtruthEventHandler;
129 fEventPool = other.fEventPool;
132 fNSysInfo = other.fNSysInfo;
134 fInitOK = other.fInitOK;
135 fDebug = other.fDebug;
136 fTasks = new TObjArray(*other.fTasks);
137 fTopTasks = new TObjArray(*other.fTopTasks);
138 fZombies = new TObjArray(*other.fZombies);
139 fContainers = new TObjArray(*other.fContainers);
140 fInputs = new TObjArray(*other.fInputs);
141 fOutputs = new TObjArray(*other.fOutputs);
144 fgAnalysisManager = this;
149 //______________________________________________________________________________
150 AliAnalysisManager::~AliAnalysisManager()
153 if (fTasks) {fTasks->Delete(); delete fTasks;}
154 if (fTopTasks) delete fTopTasks;
155 if (fZombies) delete fZombies;
156 if (fContainers) {fContainers->Delete(); delete fContainers;}
157 if (fInputs) delete fInputs;
158 if (fOutputs) delete fOutputs;
159 if (fGridHandler) delete fGridHandler;
160 if (fgAnalysisManager==this) fgAnalysisManager = NULL;
163 //______________________________________________________________________________
164 Int_t AliAnalysisManager::GetEntry(Long64_t entry, Int_t getall)
166 // Read one entry of the tree or a whole branch.
167 if (fDebug > 0) printf("== AliAnalysisManager::GetEntry(%lld)\n", entry);
168 fCurrentEntry = entry;
169 return fTree ? fTree->GetTree()->GetEntry(entry, getall) : 0;
172 //______________________________________________________________________________
173 Bool_t AliAnalysisManager::Init(TTree *tree)
175 // The Init() function is called when the selector needs to initialize
176 // a new tree or chain. Typically here the branch addresses of the tree
177 // will be set. It is normaly not necessary to make changes to the
178 // generated code, but the routine can be extended by the user if needed.
179 // Init() will be called many times when running with PROOF.
180 Bool_t init = kFALSE;
181 if (!tree) return kFALSE; // Should not happen - protected in selector caller
183 printf("->AliAnalysisManager::Init(%s)\n", tree->GetName());
185 // Call InitTree of EventHandler
186 if (fOutputEventHandler) {
187 if (fMode == kProofAnalysis) {
188 init = fOutputEventHandler->Init(0x0, "proof");
190 init = fOutputEventHandler->Init(0x0, "local");
193 Error("Init", "Output event handler failed to initialize");
198 if (fInputEventHandler) {
199 if (fMode == kProofAnalysis) {
200 init = fInputEventHandler->Init(tree, "proof");
202 init = fInputEventHandler->Init(tree, "local");
205 Error("Init", "Input event handler failed to initialize tree");
209 // If no input event handler we need to get the tree once
211 if(!tree->GetTree()) {
212 Long64_t readEntry = tree->LoadTree(0);
213 if (readEntry == -2) {
214 Error("Init", "Input tree has no entry. Aborting");
220 if (fMCtruthEventHandler) {
221 if (fMode == kProofAnalysis) {
222 init = fMCtruthEventHandler->Init(0x0, "proof");
224 init = fMCtruthEventHandler->Init(0x0, "local");
227 Error("Init", "MC event handler failed to initialize");
232 if (!fInitOK) InitAnalysis();
233 if (!fInitOK) return kFALSE;
235 AliAnalysisDataContainer *top = (AliAnalysisDataContainer*)fInputs->At(0);
237 Error("Init","No top input container !");
242 printf("<-AliAnalysisManager::Init(%s)\n", tree->GetName());
247 //______________________________________________________________________________
248 void AliAnalysisManager::SlaveBegin(TTree *tree)
250 // The SlaveBegin() function is called after the Begin() function.
251 // When running with PROOF SlaveBegin() is called on each slave server.
252 // The tree argument is deprecated (on PROOF 0 is passed).
253 if (fDebug > 0) printf("->AliAnalysisManager::SlaveBegin()\n");
254 static Bool_t isCalled = kFALSE;
255 Bool_t init = kFALSE;
256 Bool_t initOK = kTRUE;
258 TDirectory *curdir = gDirectory;
259 // Call SlaveBegin only once in case of mixing
260 if (isCalled && fMode==kMixingAnalysis) return;
261 // Call Init of EventHandler
262 if (fOutputEventHandler) {
263 if (fMode == kProofAnalysis) {
264 TIter nextout(fOutputs);
265 AliAnalysisDataContainer *c_aod;
266 while ((c_aod=(AliAnalysisDataContainer*)nextout())) if (!strcmp(c_aod->GetFileName(),"default")) break;
267 if (c_aod && c_aod->IsSpecialOutput()) {
269 if (fDebug > 1) printf(" Initializing special output file %s...\n", fOutputEventHandler->GetOutputFileName());
270 OpenProofFile(fOutputEventHandler->GetOutputFileName(), "RECREATE");
271 c_aod->SetFile(gFile);
272 init = fOutputEventHandler->Init("proofspecial");
273 if (!init) msg = "Failed to initialize output handler on worker using special proof output";
276 init = fOutputEventHandler->Init("proof");
277 if (!init) msg = "Failed to initialize output handler on worker";
280 init = fOutputEventHandler->Init("local");
281 if (!init) msg = "Failed to initialize output handler on worker";
284 if (!fSelector) Error("SlaveBegin", "Selector not set");
285 else if (!init) {fSelector->Abort(msg); fSelector->SetStatus(-1);}
288 if (fInputEventHandler) {
289 fInputEventHandler->SetInputTree(tree);
290 if (fMode == kProofAnalysis) {
291 init = fInputEventHandler->Init("proof");
292 if (!init) msg = "Failed to initialize input handler on worker";
294 init = fInputEventHandler->Init("local");
295 if (!init) msg = "Failed to initialize input handler";
298 if (!fSelector) Error("SlaveBegin", "Selector not set");
299 else if (!init) {fSelector->Abort(msg); fSelector->SetStatus(-1);}
302 if (fMCtruthEventHandler) {
303 if (fMode == kProofAnalysis) {
304 init = fMCtruthEventHandler->Init("proof");
305 if (!init) msg = "Failed to initialize MC handler on worker";
307 init = fMCtruthEventHandler->Init("local");
308 if (!init) msg = "Failed to initialize MC handler";
311 if (!fSelector) Error("SlaveBegin", "Selector not set");
312 else if (!init) {fSelector->Abort(msg); fSelector->SetStatus(-1);}
314 if (curdir) curdir->cd();
318 AliAnalysisTask *task;
319 // Call CreateOutputObjects for all tasks
320 while ((task=(AliAnalysisTask*)next())) {
322 task->CreateOutputObjects();
323 if (curdir) curdir->cd();
325 if (fDebug > 0) printf("<-AliAnalysisManager::SlaveBegin()\n");
328 //______________________________________________________________________________
329 Bool_t AliAnalysisManager::Notify()
331 // The Notify() function is called when a new file is opened. This
332 // can be either for a new TTree in a TChain or when when a new TTree
333 // is started when using PROOF. It is normaly not necessary to make changes
334 // to the generated code, but the routine can be extended by the
335 // user if needed. The return value is currently not used.
336 if (!fTree) return kFALSE;
338 TFile *curfile = fTree->GetCurrentFile();
340 Error("Notify","No current file");
344 if (fDebug > 0) printf("->AliAnalysisManager::Notify() file: %s\n", curfile->GetName());
346 AliAnalysisTask *task;
347 // Call Notify for all tasks
348 while ((task=(AliAnalysisTask*)next()))
351 // Call Notify of the event handlers
352 if (fInputEventHandler) {
353 fInputEventHandler->Notify(curfile->GetName());
356 if (fOutputEventHandler) {
357 fOutputEventHandler->Notify(curfile->GetName());
360 if (fMCtruthEventHandler) {
361 fMCtruthEventHandler->Notify(curfile->GetName());
363 if (fDebug > 0) printf("<-AliAnalysisManager::Notify()\n");
367 //______________________________________________________________________________
368 Bool_t AliAnalysisManager::Process(Long64_t entry)
370 // The Process() function is called for each entry in the tree (or possibly
371 // keyed object in the case of PROOF) to be processed. The entry argument
372 // specifies which entry in the currently loaded tree is to be processed.
373 // It can be passed to either TTree::GetEntry() or TBranch::GetEntry()
374 // to read either all or the required parts of the data. When processing
375 // keyed objects with PROOF, the object is already loaded and is available
376 // via the fObject pointer.
378 // This function should contain the "body" of the analysis. It can contain
379 // simple or elaborate selection criteria, run algorithms on the data
380 // of the event and typically fill histograms.
382 // WARNING when a selector is used with a TChain, you must use
383 // the pointer to the current TTree to call GetEntry(entry).
384 // The entry is always the local entry number in the current tree.
385 // Assuming that fChain is the pointer to the TChain being processed,
386 // use fChain->GetTree()->GetEntry(entry).
387 if (fDebug > 0) printf("->AliAnalysisManager::Process(%lld)\n", entry);
389 if (fInputEventHandler) fInputEventHandler ->BeginEvent(entry);
390 if (fOutputEventHandler) fOutputEventHandler ->BeginEvent(entry);
391 if (fMCtruthEventHandler) fMCtruthEventHandler->BeginEvent(entry);
395 if (fDebug > 0) printf("<-AliAnalysisManager::Process()\n");
399 //______________________________________________________________________________
400 void AliAnalysisManager::PackOutput(TList *target)
402 // Pack all output data containers in the output list. Called at SlaveTerminate
403 // stage in PROOF case for each slave.
404 if (fDebug > 0) printf("->AliAnalysisManager::PackOutput()\n");
406 Error("PackOutput", "No target. Aborting.");
409 if (fInputEventHandler) fInputEventHandler ->Terminate();
410 if (fOutputEventHandler) fOutputEventHandler ->Terminate();
411 if (fMCtruthEventHandler) fMCtruthEventHandler->Terminate();
413 // Call FinishTaskOutput() for each event loop task (not called for
414 // post-event loop tasks - use Terminate() fo those)
415 TIter nexttask(fTasks);
416 AliAnalysisTask *task;
417 while ((task=(AliAnalysisTask*)nexttask())) {
418 if (!task->IsPostEventLoop()) {
419 if (fDebug > 0) printf("->FinishTaskOutput: task %s\n", task->GetName());
420 task->FinishTaskOutput();
421 if (fDebug > 0) printf("<-FinishTaskOutput: task %s\n", task->GetName());
425 if (fMode == kProofAnalysis) {
426 TIter next(fOutputs);
427 AliAnalysisDataContainer *output;
428 Bool_t isManagedByHandler = kFALSE;
429 while ((output=(AliAnalysisDataContainer*)next())) {
430 // Do not consider outputs of post event loop tasks
431 isManagedByHandler = kFALSE;
432 if (output->GetProducer()->IsPostEventLoop()) continue;
433 const char *filename = output->GetFileName();
434 if (!(strcmp(filename, "default")) && fOutputEventHandler) {
435 isManagedByHandler = kTRUE;
436 filename = fOutputEventHandler->GetOutputFileName();
438 // Check if data was posted to this container. If not, issue an error.
439 if (!output->GetData() && !isManagedByHandler) {
440 Error("PackOutput", "No data for output container %s. Forgot to PostData ?\n", output->GetName());
443 if (!output->IsSpecialOutput()) {
445 if (strlen(filename) && !isManagedByHandler) {
446 // File resident outputs
447 TFile *file = output->GetFile();
448 // Backup current folder
449 TDirectory *opwd = gDirectory;
450 // Create file if not existing and register to container.
451 if (file) file->cd();
452 else file = new TFile(filename, "RECREATE");
453 if (file->IsZombie()) {
454 Fatal("PackOutput", "Could not recreate file %s\n", filename);
457 output->SetFile(file);
458 // Clear file list to release object ownership to user.
460 // Save data to file, then close.
461 if (output->GetData()->InheritsFrom(TCollection::Class())) {
462 // If data is a collection, we set the name of the collection
463 // as the one of the container and we save as a single key.
464 TCollection *coll = (TCollection*)output->GetData();
465 coll->SetName(output->GetName());
466 coll->Write(output->GetName(), TObject::kSingleKey);
468 if (output->GetData()->InheritsFrom(TTree::Class())) {
469 TTree *tree = (TTree*)output->GetData();
470 tree->SetDirectory(file);
473 output->GetData()->Write();
476 if (fDebug > 1) printf("PackOutput %s: memory merge, file resident output\n", output->GetName());
478 printf(" file %s listing content:\n", filename);
482 // Restore current directory
483 if (opwd) opwd->cd();
485 // Memory-resident outputs
486 if (fDebug > 1) printf("PackOutput %s: memory merge memory resident output\n", filename);
488 AliAnalysisDataWrapper *wrap = 0;
489 if (isManagedByHandler) {
490 wrap = new AliAnalysisDataWrapper(fOutputEventHandler->GetTree());
491 wrap->SetName(output->GetName());
493 else wrap =output->ExportData();
494 // Output wrappers must NOT delete data after merging - the user owns them
495 wrap->SetDeleteData(kFALSE);
499 TDirectory *opwd = gDirectory;
500 TFile *file = output->GetFile();
501 if (fDebug > 1 && file) printf("PackOutput %s: file merge, special output\n", output->GetName());
502 if (isManagedByHandler) {
503 // Terminate IO for files managed by the output handler
504 if (file) file->Write();
505 if (file && fDebug > 2) {
506 printf(" handled file %s listing content:\n", file->GetName());
509 fOutputEventHandler->TerminateIO();
514 AliAnalysisTask *producer = output->GetProducer();
516 "File %s for special container %s was NOT opened in %s::CreateOutputObjects !!!",
517 output->GetFileName(), output->GetName(), producer->ClassName());
521 // Release object ownership to users after writing data to file
522 if (output->GetData()->InheritsFrom(TCollection::Class())) {
523 // If data is a collection, we set the name of the collection
524 // as the one of the container and we save as a single key.
525 TCollection *coll = (TCollection*)output->GetData();
526 coll->SetName(output->GetName());
527 coll->Write(output->GetName(), TObject::kSingleKey);
529 if (output->GetData()->InheritsFrom(TTree::Class())) {
530 TTree *tree = (TTree*)output->GetData();
531 tree->SetDirectory(file);
534 output->GetData()->Write();
539 printf(" file %s listing content:\n", output->GetFileName());
542 TString outFilename = file->GetName();
544 // Restore current directory
545 if (opwd) opwd->cd();
546 // Check if a special output location was provided or the output files have to be merged
547 if (strlen(fSpecialOutputLocation.Data())) {
548 TString remote = fSpecialOutputLocation;
550 Int_t gid = gROOT->ProcessLine("gProofServ->GetGroupId();");
551 remote += Form("%s_%d_", gSystem->HostName(), gid);
552 remote += output->GetFileName();
553 TFile::Cp ( outFilename.Data(), remote.Data() );
555 // No special location specified-> use TProofOutputFile as merging utility
556 // The file at this output slot must be opened in CreateOutputObjects
557 if (fDebug > 1) printf(" File %s to be merged...\n", output->GetFileName());
562 if (fDebug > 0) printf("<-AliAnalysisManager::PackOutput: output list contains %d containers\n", target->GetSize());
565 //______________________________________________________________________________
566 void AliAnalysisManager::ImportWrappers(TList *source)
568 // Import data in output containers from wrappers coming in source.
569 if (fDebug > 0) printf("->AliAnalysisManager::ImportWrappers()\n");
570 TIter next(fOutputs);
571 AliAnalysisDataContainer *cont;
572 AliAnalysisDataWrapper *wrap;
574 Bool_t inGrid = (fMode == kGridAnalysis)?kTRUE:kFALSE;
575 while ((cont=(AliAnalysisDataContainer*)next())) {
577 if (cont->GetProducer()->IsPostEventLoop() && !inGrid) continue;
578 const char *filename = cont->GetFileName();
579 Bool_t isManagedByHandler = kFALSE;
580 if (!(strcmp(filename, "default")) && fOutputEventHandler) {
581 isManagedByHandler = kTRUE;
582 filename = fOutputEventHandler->GetOutputFileName();
584 if (cont->IsSpecialOutput() || inGrid) {
585 if (strlen(fSpecialOutputLocation.Data()) && !isManagedByHandler) continue;
586 // Copy merged file from PROOF scratch space.
587 // In case of grid the files are already in the current directory.
591 TObject *pof = source->FindObject(filename);
592 if (!pof || !pof->InheritsFrom("TProofOutputFile")) {
593 Error("ImportWrappers", "TProofOutputFile object not found in output list for container %s", cont->GetName());
596 gROOT->ProcessLine(Form("sprintf((char*)0x%lx, \"%%s\", ((TProofOutputFile*)0x%lx)->GetOutputFileName();)", full_path, pof));
597 gROOT->ProcessLine(Form("sprintf((char*)0x%lx, \"%%s\", gProof->GetUrl();)", ch_url));
598 TString clientUrl(ch_url);
599 TString full_path_str(full_path);
600 if (clientUrl.Contains("localhost")){
601 TObjArray* array = full_path_str.Tokenize ( "//" );
602 TObjString *strobj = ( TObjString *)array->At(1);
603 TObjArray* arrayPort = strobj->GetString().Tokenize ( ":" );
604 TObjString *strobjPort = ( TObjString *) arrayPort->At(1);
605 full_path_str.ReplaceAll(strobj->GetString().Data(),"localhost:PORT");
606 full_path_str.ReplaceAll(":PORT",Form(":%s",strobjPort->GetString().Data()));
607 if (fDebug > 1) Info("ImportWrappers","Using tunnel from %s to %s",full_path_str.Data(),filename);
610 printf(" Copying file %s from PROOF scratch space\n", full_path_str.Data());
611 Bool_t gotit = TFile::Cp(full_path_str.Data(), filename);
613 Error("ImportWrappers", "Could not get file %s from proof scratch space", cont->GetFileName());
617 // Normally we should connect data from the copied file to the
618 // corresponding output container, but it is not obvious how to do this
619 // automatically if several objects in file...
620 TFile *f = TFile::Open(filename, "READ");
622 Error("ImportWrappers", "Cannot open file %s in read-only mode", filename);
626 // Try to fetch first a list object having the container name.
627 obj = f->Get(cont->GetName());
629 // Fetch first object from file having the container type.
630 TIter nextkey(f->GetListOfKeys());
632 while ((key=(TKey*)nextkey())) {
633 obj = f->Get(key->GetName());
634 if (obj && obj->IsA()->InheritsFrom(cont->GetType())) break;
638 Error("ImportWrappers", "Could not find object for container %s in file %s", cont->GetName(), filename);
641 wrap = new AliAnalysisDataWrapper(obj);
642 wrap->SetDeleteData(kFALSE);
644 if (!wrap) wrap = (AliAnalysisDataWrapper*)source->FindObject(cont->GetName());
646 Error("ImportWrappers","Container %s not found in analysis output !", cont->GetName());
651 printf(" Importing data for container %s", cont->GetName());
652 if (strlen(filename)) printf(" -> file %s\n", filename);
655 cont->ImportData(wrap);
657 if (fDebug > 0) printf("<-AliAnalysisManager::ImportWrappers(): %d containers imported\n", icont);
660 //______________________________________________________________________________
661 void AliAnalysisManager::UnpackOutput(TList *source)
663 // Called by AliAnalysisSelector::Terminate only on the client.
664 if (fDebug > 0) printf("->AliAnalysisManager::UnpackOutput()\n");
666 Error("UnpackOutput", "No target. Aborting.");
669 if (fDebug > 1) printf(" Source list contains %d containers\n", source->GetSize());
671 if (fMode == kProofAnalysis) ImportWrappers(source);
673 TIter next(fOutputs);
674 AliAnalysisDataContainer *output;
675 while ((output=(AliAnalysisDataContainer*)next())) {
676 if (!output->GetData()) continue;
677 // Check if there are client tasks that run post event loop
678 if (output->HasConsumers()) {
679 // Disable event loop semaphore
680 output->SetPostEventLoop(kTRUE);
681 TObjArray *list = output->GetConsumers();
682 Int_t ncons = list->GetEntriesFast();
683 for (Int_t i=0; i<ncons; i++) {
684 AliAnalysisTask *task = (AliAnalysisTask*)list->At(i);
685 task->CheckNotify(kTRUE);
686 // If task is active, execute it
687 if (task->IsPostEventLoop() && task->IsActive()) {
688 if (fDebug > 0) printf("== Executing post event loop task %s\n", task->GetName());
694 if (fDebug > 0) printf("<-AliAnalysisManager::UnpackOutput()\n");
697 //______________________________________________________________________________
698 void AliAnalysisManager::Terminate()
700 // The Terminate() function is the last function to be called during
701 // a query. It always runs on the client, it can be used to present
702 // the results graphically.
703 if (fDebug > 0) printf("->AliAnalysisManager::Terminate()\n");
704 AliAnalysisTask *task;
706 // Call Terminate() for tasks
707 while ((task=(AliAnalysisTask*)next())) task->Terminate();
709 TIter next1(fOutputs);
710 AliAnalysisDataContainer *output;
711 while ((output=(AliAnalysisDataContainer*)next1())) {
712 // Special outputs or grid files have the files already closed and written.
713 if (fMode == kGridAnalysis) continue;
714 if (output->IsSpecialOutput()&&(fMode == kProofAnalysis)) continue;
715 const char *filename = output->GetFileName();
716 if (!(strcmp(filename, "default"))) {
717 if (fOutputEventHandler) filename = fOutputEventHandler->GetOutputFileName();
718 TFile *aodfile = (TFile*)gROOT->GetListOfFiles()->FindObject(filename);
720 if (fDebug > 1) printf("Writing output handler file: %s\n", filename);
725 if (!strlen(filename)) continue;
726 if (!output->GetData()) continue;
727 TFile *file = output->GetFile();
728 TDirectory *opwd = gDirectory;
729 file = (TFile*)gROOT->GetListOfFiles()->FindObject(filename);
730 if (!file) file = new TFile(filename, "RECREATE");
731 if (file->IsZombie()) continue;
732 output->SetFile(file);
734 if (fDebug > 1) printf(" writing output data %s to file %s\n", output->GetData()->GetName(), file->GetName());
735 if (output->GetData()->InheritsFrom(TCollection::Class())) {
736 // If data is a collection, we set the name of the collection
737 // as the one of the container and we save as a single key.
738 TCollection *coll = (TCollection*)output->GetData();
739 coll->SetName(output->GetName());
740 coll->Write(output->GetName(), TObject::kSingleKey);
742 if (output->GetData()->InheritsFrom(TTree::Class())) {
743 TTree *tree = (TTree*)output->GetData();
744 tree->SetDirectory(file);
747 output->GetData()->Write();
750 if (opwd) opwd->cd();
753 while ((output=(AliAnalysisDataContainer*)next1())) {
754 // Close all files at output
755 TDirectory *opwd = gDirectory;
756 if (output->GetFile()) output->GetFile()->Close();
757 if (opwd) opwd->cd();
760 if (fInputEventHandler) fInputEventHandler ->TerminateIO();
761 if (fOutputEventHandler) fOutputEventHandler ->TerminateIO();
762 if (fMCtruthEventHandler) fMCtruthEventHandler->TerminateIO();
764 Bool_t getsysInfo = ((fNSysInfo>0) && (fMode==kLocalAnalysis))?kTRUE:kFALSE;
766 TDirectory *cdir = gDirectory;
767 TFile f("syswatch.root", "RECREATE");
769 TTree *tree = AliSysInfo::MakeTree("syswatch.log");
770 tree->SetMarkerStyle(kCircle);
771 tree->SetMarkerColor(kBlue);
772 tree->SetMarkerSize(0.5);
773 if (!gROOT->IsBatch()) {
774 tree->SetAlias("event", "id0");
775 tree->SetAlias("memUSED", "mi.fMemUsed");
776 new TCanvas("SysInfo","SysInfo",10,10,800,600);
777 tree->Draw("memUSED:event","","", 1234567890, 0);
783 if (cdir) cdir->cd();
785 if (fDebug > 0) printf("<-AliAnalysisManager::Terminate()\n");
788 //______________________________________________________________________________
789 void AliAnalysisManager::AddTask(AliAnalysisTask *task)
791 // Adds a user task to the global list of tasks.
792 if (fTasks->FindObject(task)) {
793 Warning("AddTask", "Task %s: the same object already added to the analysis manager. Not adding.", task->GetName());
796 task->SetActive(kFALSE);
800 //______________________________________________________________________________
801 AliAnalysisTask *AliAnalysisManager::GetTask(const char *name) const
803 // Retreive task by name.
804 if (!fTasks) return NULL;
805 return (AliAnalysisTask*)fTasks->FindObject(name);
808 //______________________________________________________________________________
809 AliAnalysisDataContainer *AliAnalysisManager::CreateContainer(const char *name,
810 TClass *datatype, EAliAnalysisContType type, const char *filename)
812 // Create a data container of a certain type. Types can be:
813 // kExchangeContainer = 0, used to exchange date between tasks
814 // kInputContainer = 1, used to store input data
815 // kOutputContainer = 2, used for posting results
816 if (fContainers->FindObject(name)) {
817 Error("CreateContainer","A container named %s already defined !\n",name);
820 AliAnalysisDataContainer *cont = new AliAnalysisDataContainer(name, datatype);
821 fContainers->Add(cont);
823 case kInputContainer:
826 case kOutputContainer:
828 if (filename && strlen(filename)) {
829 cont->SetFileName(filename);
830 cont->SetDataOwned(kFALSE); // data owned by the file
833 case kExchangeContainer:
839 //______________________________________________________________________________
840 Bool_t AliAnalysisManager::ConnectInput(AliAnalysisTask *task, Int_t islot,
841 AliAnalysisDataContainer *cont)
843 // Connect input of an existing task to a data container.
844 if (!fTasks->FindObject(task)) {
846 Info("ConnectInput", "Task %s was not registered. Now owned by analysis manager", task->GetName());
848 Bool_t connected = task->ConnectInput(islot, cont);
852 //______________________________________________________________________________
853 Bool_t AliAnalysisManager::ConnectOutput(AliAnalysisTask *task, Int_t islot,
854 AliAnalysisDataContainer *cont)
856 // Connect output of an existing task to a data container.
857 if (!fTasks->FindObject(task)) {
859 Warning("ConnectOutput", "Task %s not registered. Now owned by analysis manager", task->GetName());
861 Bool_t connected = task->ConnectOutput(islot, cont);
865 //______________________________________________________________________________
866 void AliAnalysisManager::CleanContainers()
868 // Clean data from all containers that have already finished all client tasks.
869 TIter next(fContainers);
870 AliAnalysisDataContainer *cont;
871 while ((cont=(AliAnalysisDataContainer *)next())) {
872 if (cont->IsOwnedData() &&
873 cont->IsDataReady() &&
874 cont->ClientsExecuted()) cont->DeleteData();
878 //______________________________________________________________________________
879 Bool_t AliAnalysisManager::InitAnalysis()
881 // Initialization of analysis chain of tasks. Should be called after all tasks
882 // and data containers are properly connected
883 // Check for input/output containers
885 // Check for top tasks (depending only on input data containers)
886 if (!fTasks->First()) {
887 Error("InitAnalysis", "Analysis has no tasks !");
891 AliAnalysisTask *task;
892 AliAnalysisDataContainer *cont;
895 Bool_t iszombie = kFALSE;
896 Bool_t istop = kTRUE;
898 while ((task=(AliAnalysisTask*)next())) {
901 Int_t ninputs = task->GetNinputs();
902 for (i=0; i<ninputs; i++) {
903 cont = task->GetInputSlot(i)->GetContainer();
911 Error("InitAnalysis", "Input slot %d of task %s has no container connected ! Declared zombie...",
914 if (iszombie) continue;
915 // Check if cont is an input container
916 if (istop && !fInputs->FindObject(cont)) istop=kFALSE;
917 // Connect to parent task
921 fTopTasks->Add(task);
925 Error("InitAnalysis", "No top task defined. At least one task should be connected only to input containers");
928 // Check now if there are orphan tasks
929 for (i=0; i<ntop; i++) {
930 task = (AliAnalysisTask*)fTopTasks->At(i);
935 while ((task=(AliAnalysisTask*)next())) {
936 if (!task->IsUsed()) {
938 Warning("InitAnalysis", "Task %s is orphan", task->GetName());
941 // Check the task hierarchy (no parent task should depend on data provided
942 // by a daughter task)
943 for (i=0; i<ntop; i++) {
944 task = (AliAnalysisTask*)fTopTasks->At(i);
945 if (task->CheckCircularDeps()) {
946 Error("InitAnalysis", "Found illegal circular dependencies between following tasks:");
951 // Check that all containers feeding post-event loop tasks are in the outputs list
952 TIter nextcont(fContainers); // loop over all containers
953 while ((cont=(AliAnalysisDataContainer*)nextcont())) {
954 if (!cont->IsPostEventLoop() && !fOutputs->FindObject(cont)) {
955 if (cont->HasConsumers()) {
956 // Check if one of the consumers is post event loop
957 TIter nextconsumer(cont->GetConsumers());
958 while ((task=(AliAnalysisTask*)nextconsumer())) {
959 if (task->IsPostEventLoop()) {
967 // Check if all special output containers have a file name provided
968 TIter nextout(fOutputs);
969 while ((cont=(AliAnalysisDataContainer*)nextout())) {
970 if (cont->IsSpecialOutput() && !strlen(cont->GetFileName())) {
971 Error("InitAnalysis", "Wrong container %s : a file name MUST be provided for special outputs", cont->GetName());
979 //______________________________________________________________________________
980 void AliAnalysisManager::PrintStatus(Option_t *option) const
982 // Print task hierarchy.
984 Info("PrintStatus", "Analysis manager %s not initialized : call InitAnalysis() first", GetName());
987 Bool_t getsysInfo = ((fNSysInfo>0) && (fMode==kLocalAnalysis))?kTRUE:kFALSE;
989 Info("PrintStatus", "System information will be collected each %lld events", fNSysInfo);
990 TIter next(fTopTasks);
991 AliAnalysisTask *task;
992 while ((task=(AliAnalysisTask*)next()))
993 task->PrintTask(option);
996 //______________________________________________________________________________
997 void AliAnalysisManager::ResetAnalysis()
999 // Reset all execution flags and clean containers.
1003 //______________________________________________________________________________
1004 void AliAnalysisManager::StartAnalysis(const char *type, TTree *tree, Long64_t nentries, Long64_t firstentry)
1006 // Start analysis for this manager. Analysis task can be: LOCAL, PROOF, GRID or
1007 // MIX. Process nentries starting from firstentry
1009 Error("StartAnalysis","Analysis manager was not initialized !");
1012 if (fDebug > 0) printf("StartAnalysis %s\n",GetName());
1013 TString anaType = type;
1015 fMode = kLocalAnalysis;
1016 Bool_t runlocalinit = kTRUE;
1017 if (anaType.Contains("file")) runlocalinit = kFALSE;
1018 if (anaType.Contains("proof")) fMode = kProofAnalysis;
1019 else if (anaType.Contains("grid")) fMode = kGridAnalysis;
1020 else if (anaType.Contains("mix")) fMode = kMixingAnalysis;
1022 if (fMode == kGridAnalysis) {
1023 if (!fGridHandler) {
1024 Error("StartAnalysis", "Cannot start grid analysis without a grid handler.");
1025 Info("===", "Add an AliAnalysisAlien object as plugin for this manager and configure it.");
1028 // Write analysis manager in the analysis file
1029 cout << "===== RUNNING GRID ANALYSIS: " << GetName() << endl;
1030 // run local task configuration
1031 TIter nextTask(fTasks);
1032 AliAnalysisTask *task;
1033 while ((task=(AliAnalysisTask*)nextTask())) {
1036 fGridHandler->StartAnalysis(nentries, firstentry);
1038 // Terminate grid analysis
1039 if (fSelector && fSelector->GetStatus() == -1) return;
1040 if (fGridHandler->GetRunMode() == AliAnalysisGrid::kOffline) return;
1041 cout << "===== MERGING OUTPUTS REGISTERED BY YOUR ANALYSIS JOB: " << GetName() << endl;
1042 if (!fGridHandler->MergeOutputs()) {
1043 // Return if outputs could not be merged or if it alien handler
1044 // was configured for offline mode or local testing.
1047 ImportWrappers(NULL);
1052 SetEventLoop(kFALSE);
1053 // Enable event loop mode if a tree was provided
1054 if (tree || fMode==kMixingAnalysis) SetEventLoop(kTRUE);
1057 TString ttype = "TTree";
1058 if (tree && tree->IsA() == TChain::Class()) {
1059 chain = (TChain*)tree;
1060 if (!chain || !chain->GetListOfFiles()->First()) {
1061 Error("StartAnalysis", "Cannot process null or empty chain...");
1067 // Initialize locally all tasks (happens for all modes)
1069 AliAnalysisTask *task;
1071 while ((task=(AliAnalysisTask*)next())) {
1077 case kLocalAnalysis:
1079 TIter nextT(fTasks);
1080 // Call CreateOutputObjects for all tasks
1081 while ((task=(AliAnalysisTask*)nextT())) {
1082 TDirectory *curdir = gDirectory;
1083 task->CreateOutputObjects();
1084 if (curdir) curdir->cd();
1090 // Run tree-based analysis via AliAnalysisSelector
1091 cout << "===== RUNNING LOCAL ANALYSIS " << GetName() << " ON TREE " << tree->GetName() << endl;
1092 fSelector = new AliAnalysisSelector(this);
1093 tree->Process(fSelector, "", nentries, firstentry);
1095 case kProofAnalysis:
1096 if (!gROOT->GetListOfProofs() || !gROOT->GetListOfProofs()->GetEntries()) {
1097 printf("StartAnalysis: no PROOF!!!\n");
1100 sprintf(line, "gProof->AddInput((TObject*)0x%lx);", (ULong_t)this);
1101 gROOT->ProcessLine(line);
1104 cout << "===== RUNNING PROOF ANALYSIS " << GetName() << " ON CHAIN " << chain->GetName() << endl;
1105 chain->Process("AliAnalysisSelector", "", nentries, firstentry);
1107 printf("StartAnalysis: no chain\n");
1112 Warning("StartAnalysis", "GRID analysis mode not implemented. Running local.");
1114 case kMixingAnalysis:
1115 // Run event mixing analysis
1117 Error("StartAnalysis", "Cannot run event mixing without event pool");
1120 cout << "===== RUNNING EVENT MIXING ANALYSIS " << GetName() << endl;
1121 fSelector = new AliAnalysisSelector(this);
1122 while ((chain=fEventPool->GetNextChain())) {
1124 // Call NotifyBinChange for all tasks
1125 while ((task=(AliAnalysisTask*)next()))
1126 if (!task->IsPostEventLoop()) task->NotifyBinChange();
1127 chain->Process(fSelector);
1129 PackOutput(fSelector->GetOutputList());
1134 //______________________________________________________________________________
1135 void AliAnalysisManager::StartAnalysis(const char *type, const char *dataset, Long64_t nentries, Long64_t firstentry)
1137 // Start analysis for this manager on a given dataset. Analysis task can be:
1138 // LOCAL, PROOF or GRID. Process nentries starting from firstentry.
1140 Error("StartAnalysis","Analysis manager was not initialized !");
1143 if (fDebug > 0) printf("StartAnalysis %s\n",GetName());
1144 TString anaType = type;
1146 if (!anaType.Contains("proof")) {
1147 Error("StartAnalysis", "Cannot process datasets in %s mode. Try PROOF.", type);
1150 fMode = kProofAnalysis;
1152 SetEventLoop(kTRUE);
1153 // Set the dataset flag
1154 TObject::SetBit(kUseDataSet);
1157 // Initialize locally all tasks
1159 AliAnalysisTask *task;
1160 while ((task=(AliAnalysisTask*)next())) {
1164 if (!gROOT->GetListOfProofs() || !gROOT->GetListOfProofs()->GetEntries()) {
1165 printf("StartAnalysis: no PROOF!!!\n");
1168 sprintf(line, "gProof->AddInput((TObject*)0x%lx);", (ULong_t)this);
1169 gROOT->ProcessLine(line);
1170 sprintf(line, "gProof->GetDataSet(\"%s\");", dataset);
1171 if (!gROOT->ProcessLine(line)) {
1172 Error("StartAnalysis", "Dataset %s not found", dataset);
1175 sprintf(line, "gProof->Process(\"%s\", \"AliAnalysisSelector\", \"\", %lld, %lld);",
1176 dataset, nentries, firstentry);
1177 cout << "===== RUNNING PROOF ANALYSIS " << GetName() << " ON DATASET " << dataset << endl;
1178 gROOT->ProcessLine(line);
1181 //______________________________________________________________________________
1182 TFile *AliAnalysisManager::OpenProofFile(const char *filename, const char *option)
1184 // Opens a special output file used in PROOF.
1186 if (fMode!=kProofAnalysis || !fSelector) {
1187 Error("OpenProofFile","Cannot open PROOF file %s",filename);
1190 sprintf(line, "TProofOutputFile *pf = new TProofOutputFile(\"%s\");", filename);
1191 if (fDebug > 1) printf("=== %s\n", line);
1192 gROOT->ProcessLine(line);
1193 sprintf(line, "pf->OpenFile(\"%s\");", option);
1194 gROOT->ProcessLine(line);
1196 gROOT->ProcessLine("pf->Print()");
1197 printf(" == proof file name: %s\n", gFile->GetName());
1199 sprintf(line, "((TList*)0x%lx)->Add(pf);",(ULong_t)fSelector->GetOutputList());
1200 if (fDebug > 1) printf("=== %s\n", line);
1201 gROOT->ProcessLine(line);
1205 //______________________________________________________________________________
1206 void AliAnalysisManager::ExecAnalysis(Option_t *option)
1208 // Execute analysis.
1209 static Long64_t ncalls = 0;
1210 Bool_t getsysInfo = ((fNSysInfo>0) && (fMode==kLocalAnalysis))?kTRUE:kFALSE;
1211 if (getsysInfo && ncalls==0) AliSysInfo::AddStamp("Start", (Int_t)ncalls);
1214 Error("ExecAnalysis", "Analysis manager was not initialized !");
1217 AliAnalysisTask *task;
1218 // Check if the top tree is active.
1221 // De-activate all tasks
1222 while ((task=(AliAnalysisTask*)next())) task->SetActive(kFALSE);
1223 AliAnalysisDataContainer *cont = (AliAnalysisDataContainer*)fInputs->At(0);
1225 Error("ExecAnalysis","Cannot execute analysis in TSelector mode without at least one top container");
1228 cont->SetData(fTree); // This will notify all consumers
1229 Long64_t entry = fTree->GetTree()->GetReadEntry();
1232 // Call BeginEvent() for optional input/output and MC services
1233 if (fInputEventHandler) fInputEventHandler ->BeginEvent(entry);
1234 if (fOutputEventHandler) fOutputEventHandler ->BeginEvent(entry);
1235 if (fMCtruthEventHandler) fMCtruthEventHandler->BeginEvent(entry);
1237 // Execute the tasks
1238 // TIter next1(cont->GetConsumers());
1239 TIter next1(fTopTasks);
1240 while ((task=(AliAnalysisTask*)next1())) {
1242 cout << " Executing task " << task->GetName() << endl;
1245 task->ExecuteTask(option);
1248 // Call FinishEvent() for optional output and MC services
1249 if (fInputEventHandler) fInputEventHandler ->FinishEvent();
1250 if (fOutputEventHandler) fOutputEventHandler ->FinishEvent();
1251 if (fMCtruthEventHandler) fMCtruthEventHandler->FinishEvent();
1252 // Gather system information if requested
1253 if (getsysInfo && ((ncalls%fNSysInfo)==0))
1254 AliSysInfo::AddStamp(Form("Event#%lld",ncalls),(Int_t)ncalls);
1257 // The event loop is not controlled by TSelector
1259 // Call BeginEvent() for optional input/output and MC services
1260 if (fInputEventHandler) fInputEventHandler ->BeginEvent(-1);
1261 if (fOutputEventHandler) fOutputEventHandler ->BeginEvent(-1);
1262 if (fMCtruthEventHandler) fMCtruthEventHandler->BeginEvent(-1);
1263 TIter next2(fTopTasks);
1264 while ((task=(AliAnalysisTask*)next2())) {
1265 task->SetActive(kTRUE);
1267 cout << " Executing task " << task->GetName() << endl;
1269 task->ExecuteTask(option);
1272 // Call FinishEvent() for optional output and MC services
1273 if (fInputEventHandler) fInputEventHandler ->FinishEvent();
1274 if (fOutputEventHandler) fOutputEventHandler ->FinishEvent();
1275 if (fMCtruthEventHandler) fMCtruthEventHandler->FinishEvent();
1278 //______________________________________________________________________________
1279 void AliAnalysisManager::FinishAnalysis()