]> git.uio.no Git - u/mrichter/AliRoot.git/blobdiff - ANALYSIS/AliAnalysisManager.cxx
Added AddTrackParams() method for convenience + some comments
[u/mrichter/AliRoot.git] / ANALYSIS / AliAnalysisManager.cxx
index 6f19e353e8cf48129143effde027616c9d13d427..04531c7fc7280eccd9b43fe446c85825cfc8ee24 100644 (file)
@@ -37,6 +37,7 @@
 #include <TCanvas.h>
 
 #include "AliAnalysisSelector.h"
+#include "AliAnalysisGrid.h"
 #include "AliAnalysisTask.h"
 #include "AliAnalysisDataContainer.h"
 #include "AliAnalysisDataSlot.h"
@@ -56,7 +57,7 @@ AliAnalysisManager::AliAnalysisManager(const char *name, const char *title)
                     fInputEventHandler(NULL),
                     fOutputEventHandler(NULL),
                     fMCtruthEventHandler(NULL),
-                   fEventPool(NULL),
+                    fEventPool(NULL),
                     fCurrentEntry(-1),
                     fNSysInfo(0),
                     fMode(kLocalAnalysis),
@@ -69,7 +70,10 @@ AliAnalysisManager::AliAnalysisManager(const char *name, const char *title)
                     fContainers(NULL),
                     fInputs(NULL),
                     fOutputs(NULL),
-                    fSelector(NULL)
+                    fCommonInput(NULL),
+                    fCommonOutput(NULL),
+                    fSelector(NULL),
+                    fGridHandler(NULL)
 {
 // Default constructor.
    fgAnalysisManager = this;
@@ -102,7 +106,10 @@ AliAnalysisManager::AliAnalysisManager(const AliAnalysisManager& other)
                     fContainers(NULL),
                     fInputs(NULL),
                     fOutputs(NULL),
-                    fSelector(NULL)
+                    fCommonInput(NULL),
+                    fCommonOutput(NULL),
+                    fSelector(NULL),
+                    fGridHandler(NULL)
 {
 // Copy constructor.
    fTasks      = new TObjArray(*other.fTasks);
@@ -136,7 +143,10 @@ AliAnalysisManager& AliAnalysisManager::operator=(const AliAnalysisManager& othe
       fContainers = new TObjArray(*other.fContainers);
       fInputs     = new TObjArray(*other.fInputs);
       fOutputs    = new TObjArray(*other.fOutputs);
+      fCommonInput = NULL;
+      fCommonOutput = NULL;
       fSelector   = NULL;
+      fGridHandler = NULL;
       fgAnalysisManager = this;
    }
    return *this;
@@ -152,6 +162,7 @@ AliAnalysisManager::~AliAnalysisManager()
    if (fContainers) {fContainers->Delete(); delete fContainers;}
    if (fInputs) delete fInputs;
    if (fOutputs) delete fOutputs;
+   if (fGridHandler) delete fGridHandler;
    if (fgAnalysisManager==this) fgAnalysisManager = NULL;
 }
 
@@ -165,60 +176,79 @@ Int_t AliAnalysisManager::GetEntry(Long64_t entry, Int_t getall)
 }
    
 //______________________________________________________________________________
-void AliAnalysisManager::Init(TTree *tree)
+Bool_t AliAnalysisManager::Init(TTree *tree)
 {
   // The Init() function is called when the selector needs to initialize
   // a new tree or chain. Typically here the branch addresses of the tree
   // will be set. It is normaly not necessary to make changes to the
   // generated code, but the routine can be extended by the user if needed.
   // Init() will be called many times when running with PROOF.
-   if (!tree) return;
+   Bool_t init = kFALSE;
+   if (!tree) return kFALSE; // Should not happen - protected in selector caller
    if (fDebug > 0) {
       printf("->AliAnalysisManager::Init(%s)\n", tree->GetName());
    }
-
    // Call InitTree of EventHandler
    if (fOutputEventHandler) {
       if (fMode == kProofAnalysis) {
-         fOutputEventHandler->Init(0x0, "proof");
+         init = fOutputEventHandler->Init(0x0, "proof");
       } else {
-         fOutputEventHandler->Init(0x0, "local");
+         init = fOutputEventHandler->Init(0x0, "local");
       }
+      if (!init) {
+         Error("Init", "Output event handler failed to initialize");
+         return kFALSE;
+      }         
    }
-
+   
    if (fInputEventHandler) {
       if (fMode == kProofAnalysis) {
-         fInputEventHandler->Init(tree, "proof");
+         init = fInputEventHandler->Init(tree, "proof");
       } else {
-         fInputEventHandler->Init(tree, "local");
+         init = fInputEventHandler->Init(tree, "local");
       }
+      if (!init) {
+         Error("Init", "Input event handler failed to initialize tree"); 
+         return kFALSE;
+      }         
    } else {
       // If no input event handler we need to get the tree once
       // for the chain
-      if(!tree->GetTree()) tree->LoadTree(0);
+      if(!tree->GetTree()) {
+         Long64_t readEntry = tree->LoadTree(0);
+         if (readEntry == -2) {
+            Error("Init", "Input tree has no entry. Aborting");
+            return kFALSE;
+         }
+      }   
    }
-   
 
    if (fMCtruthEventHandler) {
       if (fMode == kProofAnalysis) {
-         fMCtruthEventHandler->Init(0x0, "proof");
+         init = fMCtruthEventHandler->Init(0x0, "proof");
       } else {
-         fMCtruthEventHandler->Init(0x0, "local");
+         init = fMCtruthEventHandler->Init(0x0, "local");
       }
+      if (!init) {
+         Error("Init", "MC event handler failed to initialize"); 
+         return kFALSE;
+      }         
    }
 
    if (!fInitOK) InitAnalysis();
-   if (!fInitOK) return;
+   if (!fInitOK) return kFALSE;
    fTree = tree;
-   AliAnalysisDataContainer *top = (AliAnalysisDataContainer*)fInputs->At(0);
+   AliAnalysisDataContainer *top = fCommonInput;
+   if (!top) top = (AliAnalysisDataContainer*)fInputs->At(0);
    if (!top) {
       Error("Init","No top input container !");
-      return;
+      return kFALSE;
    }
    top->SetData(tree);
    if (fDebug > 0) {
       printf("<-AliAnalysisManager::Init(%s)\n", tree->GetName());
    }
+   return kTRUE;
 }
 
 //______________________________________________________________________________
@@ -229,6 +259,9 @@ void AliAnalysisManager::SlaveBegin(TTree *tree)
   // The tree argument is deprecated (on PROOF 0 is passed).
    if (fDebug > 0) printf("->AliAnalysisManager::SlaveBegin()\n");
    static Bool_t isCalled = kFALSE;
+   Bool_t init = kFALSE;
+   Bool_t initOK = kTRUE;
+   TString msg;
    TDirectory *curdir = gDirectory;
    // Call SlaveBegin only once in case of mixing
    if (isCalled && fMode==kMixingAnalysis) return;
@@ -243,34 +276,51 @@ void AliAnalysisManager::SlaveBegin(TTree *tree)
             if (fDebug > 1) printf("   Initializing special output file %s...\n", fOutputEventHandler->GetOutputFileName());
             OpenProofFile(fOutputEventHandler->GetOutputFileName(), "RECREATE");
             c_aod->SetFile(gFile);
-            fOutputEventHandler->Init("proofspecial");
+            init = fOutputEventHandler->Init("proofspecial");
+            if (!init) msg = "Failed to initialize output handler on worker using special proof output";
          } else {
             // Merging in memory
-            fOutputEventHandler->Init("proof");
+            init = fOutputEventHandler->Init("proof");
+            if (!init) msg = "Failed to initialize output handler on worker";
          }   
       } else {
-         fOutputEventHandler->Init("local");
+         init = fOutputEventHandler->Init("local");
+         if (!init) msg = "Failed to initialize output handler on worker";
       }
+      initOK &= init;
+      if (!fSelector) Error("SlaveBegin", "Selector not set");
+      else if (!init) {fSelector->Abort(msg); fSelector->SetStatus(-1);}
    }
 
    if (fInputEventHandler) {
       fInputEventHandler->SetInputTree(tree);
       if (fMode == kProofAnalysis) {
-         fInputEventHandler->Init("proof");
+         init = fInputEventHandler->Init("proof");
+         if (!init) msg = "Failed to initialize input handler on worker";
       } else {
-         fInputEventHandler->Init("local");
+         init = fInputEventHandler->Init("local");
+         if (!init) msg = "Failed to initialize input handler";
       }
+      initOK &= init;
+      if (!fSelector) Error("SlaveBegin", "Selector not set");      
+      else if (!init) {fSelector->Abort(msg); fSelector->SetStatus(-1);}
    }
 
    if (fMCtruthEventHandler) {
       if (fMode == kProofAnalysis) {
-         fMCtruthEventHandler->Init("proof");
+         init = fMCtruthEventHandler->Init("proof");
+         if (!init) msg = "Failed to initialize MC handler on worker";
       } else {
-         fMCtruthEventHandler->Init("local");
+         init = fMCtruthEventHandler->Init("local");
+         if (!init) msg = "Failed to initialize MC handler";
       }
+      initOK &= init;
+      if (!fSelector) Error("SlaveBegin", "Selector not set");      
+      else if (!init) {fSelector->Abort(msg); fSelector->SetStatus(-1);}
    }
    if (curdir) curdir->cd();
-   
+   isCalled = kTRUE;
+   if (!initOK) return;   
    TIter next(fTasks);
    AliAnalysisTask *task;
    // Call CreateOutputObjects for all tasks
@@ -279,8 +329,6 @@ void AliAnalysisManager::SlaveBegin(TTree *tree)
       task->CreateOutputObjects();
       if (curdir) curdir->cd();
    }
-   isCalled = kTRUE;
-
    if (fDebug > 0) printf("<-AliAnalysisManager::SlaveBegin()\n");
 }
 
@@ -292,10 +340,8 @@ Bool_t AliAnalysisManager::Notify()
    // is started when using PROOF. It is normaly not necessary to make changes
    // to the generated code, but the routine can be extended by the
    // user if needed. The return value is currently not used.
-   if (!fTree) {
-      Error("Notify","No current tree.");
-      return kFALSE;
-   }   
+   if (!fTree) return kFALSE;
+
    TFile *curfile = fTree->GetCurrentFile();
    if (!curfile) {
       Error("Notify","No current file");
@@ -532,42 +578,49 @@ void AliAnalysisManager::ImportWrappers(TList *source)
    AliAnalysisDataContainer *cont;
    AliAnalysisDataWrapper   *wrap;
    Int_t icont = 0;
+   Bool_t inGrid = (fMode == kGridAnalysis)?kTRUE:kFALSE;
    while ((cont=(AliAnalysisDataContainer*)next())) {
       wrap = 0;
-      if (cont->GetProducer()->IsPostEventLoop()) continue;
+      if (cont->GetProducer()->IsPostEventLoop() && !inGrid) continue;
       const char *filename = cont->GetFileName();
       Bool_t isManagedByHandler = kFALSE;
       if (!(strcmp(filename, "default")) && fOutputEventHandler) {
          isManagedByHandler = kTRUE;
          filename = fOutputEventHandler->GetOutputFileName();
       }
-      if (cont->IsSpecialOutput()) {
+      if (cont->IsSpecialOutput() || inGrid) {
          if (strlen(fSpecialOutputLocation.Data()) && !isManagedByHandler) continue;
-         // Copy merged file from PROOF scratch space
-         char full_path[512];
-         char ch_url[512];
-         TObject *pof =  source->FindObject(filename);
-         if (!pof || !pof->InheritsFrom("TProofOutputFile")) {
-            Error("ImportWrappers", "TProofOutputFile object not found in output list for container %s", cont->GetName());
-            continue;
-         }
-         gROOT->ProcessLine(Form("sprintf((char*)0x%lx, \"%%s\", ((TProofOutputFile*)0x%lx)->GetOutputFileName();)", full_path, pof));
-         gROOT->ProcessLine(Form("sprintf((char*)0x%lx, \"%%s\", gProof->GetUrl();)", ch_url));
-         TString clientUrl(ch_url);
-         TString full_path_str(full_path);
-         if (clientUrl.Contains("localhost")){
-            TObjArray* array = full_path_str.Tokenize ( "//" );
-            TObjString *strobj = ( TObjString *)array->At(1);
-            full_path_str.ReplaceAll(strobj->GetString().Data(),"localhost:11094");
-            if (fDebug > 1) Info("ImportWrappers","Using tunnel from %s to %s",full_path_str.Data(),filename);
-         }
-         if (fDebug > 1) 
-            printf("   Copying file %s from PROOF scratch space\n", full_path_str.Data());
-         Bool_t gotit = TFile::Cp(full_path_str.Data(), filename); 
-         if (!gotit) {
-            Error("ImportWrappers", "Could not get file %s from proof scratch space", cont->GetFileName());
-            continue;
-         }
+         // Copy merged file from PROOF scratch space. 
+         // In case of grid the files are already in the current directory.
+         if (!inGrid) {
+            char full_path[512];
+            char ch_url[512];
+            TObject *pof =  source->FindObject(filename);
+            if (!pof || !pof->InheritsFrom("TProofOutputFile")) {
+               Error("ImportWrappers", "TProofOutputFile object not found in output list for container %s", cont->GetName());
+               continue;
+            }
+            gROOT->ProcessLine(Form("sprintf((char*)0x%lx, \"%%s\", ((TProofOutputFile*)0x%lx)->GetOutputFileName();)", full_path, pof));
+            gROOT->ProcessLine(Form("sprintf((char*)0x%lx, \"%%s\", gProof->GetUrl();)", ch_url));
+            TString clientUrl(ch_url);
+            TString full_path_str(full_path);
+            if (clientUrl.Contains("localhost")){
+               TObjArray* array = full_path_str.Tokenize ( "//" );
+               TObjString *strobj = ( TObjString *)array->At(1);
+               TObjArray* arrayPort = strobj->GetString().Tokenize ( ":" );
+               TObjString *strobjPort = ( TObjString *) arrayPort->At(1);
+               full_path_str.ReplaceAll(strobj->GetString().Data(),"localhost:PORT");
+               full_path_str.ReplaceAll(":PORT",Form(":%s",strobjPort->GetString().Data()));
+               if (fDebug > 1) Info("ImportWrappers","Using tunnel from %s to %s",full_path_str.Data(),filename);
+            }
+            if (fDebug > 1) 
+               printf("   Copying file %s from PROOF scratch space\n", full_path_str.Data());
+            Bool_t gotit = TFile::Cp(full_path_str.Data(), filename); 
+            if (!gotit) {
+               Error("ImportWrappers", "Could not get file %s from proof scratch space", cont->GetFileName());
+               continue;
+            }
+         }   
          // Normally we should connect data from the copied file to the
          // corresponding output container, but it is not obvious how to do this
          // automatically if several objects in file...
@@ -663,8 +716,9 @@ void AliAnalysisManager::Terminate()
    TIter next1(fOutputs);
    AliAnalysisDataContainer *output;
    while ((output=(AliAnalysisDataContainer*)next1())) {
-      // Special outputs have the files already closed and written.
-     if (output->IsSpecialOutput()&&(fMode == kProofAnalysis)) continue;
+      // Special outputs or grid files have the files already closed and written.
+      if (fMode == kGridAnalysis) continue;
+      if (output->IsSpecialOutput()&&(fMode == kProofAnalysis)) continue;
       const char *filename = output->GetFileName();
       if (!(strcmp(filename, "default"))) {
          if (fOutputEventHandler) filename = fOutputEventHandler->GetOutputFileName();
@@ -725,14 +779,9 @@ void AliAnalysisManager::Terminate()
          tree->SetMarkerSize(0.5);
          if (!gROOT->IsBatch()) {
             tree->SetAlias("event", "id0");
-            tree->SetAlias("memUSED", "pI.fMemVirtual");
-            tree->SetAlias("userCPU", "pI.fCpuUser");
-            TCanvas *c = new TCanvas("SysInfo","SysInfo",10,10,800,600);
-            c->Divide(2,1,0.01,0.01);
-            c->cd(1);
+            tree->SetAlias("memUSED", "mi.fMemUsed");
+            new TCanvas("SysInfo","SysInfo",10,10,800,600);
             tree->Draw("memUSED:event","","", 1234567890, 0);
-            c->cd(2);
-            tree->Draw("userCPU:event","","", 1234567890, 0);
          }   
          tree->Write();
          f.Close();
@@ -799,6 +848,10 @@ Bool_t AliAnalysisManager::ConnectInput(AliAnalysisTask *task, Int_t islot,
                                         AliAnalysisDataContainer *cont)
 {
 // Connect input of an existing task to a data container.
+   if (!task) {
+      Error("ConnectInput", "Task pointer is NULL");
+      return kFALSE;
+   }   
    if (!fTasks->FindObject(task)) {
       AddTask(task);
       Info("ConnectInput", "Task %s was not registered. Now owned by analysis manager", task->GetName());
@@ -812,6 +865,10 @@ Bool_t AliAnalysisManager::ConnectOutput(AliAnalysisTask *task, Int_t islot,
                                         AliAnalysisDataContainer *cont)
 {
 // Connect output of an existing task to a data container.
+   if (!task) {
+      Error("ConnectOutput", "Task pointer is NULL");
+      return kFALSE;
+   }   
    if (!fTasks->FindObject(task)) {
       AddTask(task);
       Warning("ConnectOutput", "Task %s not registered. Now owned by analysis manager", task->GetName());
@@ -971,13 +1028,40 @@ void AliAnalysisManager::StartAnalysis(const char *type, TTree *tree, Long64_t n
    TString anaType = type;
    anaType.ToLower();
    fMode = kLocalAnalysis;
+   Bool_t runlocalinit = kTRUE;
+   if (anaType.Contains("file")) runlocalinit = kFALSE;
    if (anaType.Contains("proof"))     fMode = kProofAnalysis;
    else if (anaType.Contains("grid")) fMode = kGridAnalysis;
    else if (anaType.Contains("mix"))  fMode = kMixingAnalysis;
 
    if (fMode == kGridAnalysis) {
-      Warning("StartAnalysis", "GRID analysis mode not implemented. Running local.");
-      fMode = kLocalAnalysis;
+      if (!fGridHandler) {
+         Error("StartAnalysis", "Cannot start grid analysis without a grid handler.");
+         Info("===", "Add an AliAnalysisAlien object as plugin for this manager and configure it.");
+         return;
+      }
+      // Write analysis manager in the analysis file
+      cout << "===== RUNNING GRID ANALYSIS: " << GetName() << endl;
+      // run local task configuration
+      TIter nextTask(fTasks);
+      AliAnalysisTask *task;
+      while ((task=(AliAnalysisTask*)nextTask())) {
+         task->LocalInit();
+      }
+      fGridHandler->StartAnalysis(nentries, firstentry);
+
+      // Terminate grid analysis
+      if (fSelector && fSelector->GetStatus() == -1) return;
+      if (fGridHandler->GetRunMode() == AliAnalysisGrid::kOffline) return;
+      cout << "===== MERGING OUTPUTS REGISTERED BY YOUR ANALYSIS JOB: " << GetName() << endl;
+      if (!fGridHandler->MergeOutputs()) {
+         // Return if outputs could not be merged or if it alien handler
+         // was configured for offline mode or local testing.
+         return;
+      }
+      ImportWrappers(NULL);
+      Terminate();
+      return;
    }
    char line[256];
    SetEventLoop(kFALSE);
@@ -998,9 +1082,11 @@ void AliAnalysisManager::StartAnalysis(const char *type, TTree *tree, Long64_t n
    // Initialize locally all tasks (happens for all modes)
    TIter next(fTasks);
    AliAnalysisTask *task;
-   while ((task=(AliAnalysisTask*)next())) {
-      task->LocalInit();
-   }
+   if (runlocalinit) {
+      while ((task=(AliAnalysisTask*)next())) {
+         task->LocalInit();
+      }
+   }   
    
    switch (fMode) {
       case kLocalAnalysis:
@@ -1149,7 +1235,8 @@ void AliAnalysisManager::ExecAnalysis(Option_t *option)
       TIter next(fTasks);
    // De-activate all tasks
       while ((task=(AliAnalysisTask*)next())) task->SetActive(kFALSE);
-      AliAnalysisDataContainer *cont = (AliAnalysisDataContainer*)fInputs->At(0);
+      AliAnalysisDataContainer *cont = fCommonInput;
+      if (!cont) cont = (AliAnalysisDataContainer*)fInputs->At(0);
       if (!cont) {
              Error("ExecAnalysis","Cannot execute analysis in TSelector mode without at least one top container");
          return;
@@ -1209,3 +1296,21 @@ void AliAnalysisManager::FinishAnalysis()
 {
 // Finish analysis.
 }
+
+//______________________________________________________________________________
+void AliAnalysisManager::SetInputEventHandler(AliVEventHandler*  handler)
+{
+// Set the input event handler and create a container for it.
+   fInputEventHandler   = handler;
+   fCommonInput = CreateContainer("cAUTO_INPUT", TChain::Class(), AliAnalysisManager::kInputContainer);
+   Warning("SetInputEventHandler", " An automatic input container for the input chain was created.\nPlease use: mgr->GetCommonInputContainer() to access it.");
+}
+
+//______________________________________________________________________________
+void AliAnalysisManager::SetOutputEventHandler(AliVEventHandler*  handler)
+{
+// Set the input event handler and create a container for it.
+   fOutputEventHandler   = handler;
+   fCommonOutput = CreateContainer("cAUTO_OUTPUT", TTree::Class(), AliAnalysisManager::kOutputContainer, "default");
+   Warning("SetOutputEventHandler", " An automatic output container for the output tree was created.\nPlease use: mgr->GetCommonOutputContainer() to access it.");
+}