]> git.uio.no Git - u/mrichter/AliRoot.git/blobdiff - ANALYSIS/AliAnalysisManager.cxx
- Fix for a recently introduced bug
[u/mrichter/AliRoot.git] / ANALYSIS / AliAnalysisManager.cxx
index b5cbda9bcf1044903de81459376dea3d4c407652..02566ad4a0e393576316bcfb596f6c5fe93a66b3 100644 (file)
 
 //==============================================================================
 //   AliAnalysysManager - Manager analysis class. Allows creation of several
-// analysis tasks and data containers storing their input/output. Allows 
+// analysis tasks and data containers storing their input/output. Allows
 // connecting/chaining tasks via shared data containers. Serializes the current
 // event for all tasks depending only on initial input data.
 //==============================================================================
 //
 //==============================================================================
 
-#include "TClass.h"
-#include "AliLog.h"
+#include <Riostream.h>
+
+#include <TClass.h>
+#include <TFile.h>
+#include <TMethodCall.h>
+#include <TChain.h>
+#include <TSystem.h>
+#include <TROOT.h>
 
-#include "AliAnalysisManager.h"
 #include "AliAnalysisTask.h"
 #include "AliAnalysisDataContainer.h"
 #include "AliAnalysisDataSlot.h"
+#include "AliAnalysisManager.h"
 
 ClassImp(AliAnalysisManager)
 
+AliAnalysisManager *AliAnalysisManager::fgAnalysisManager = NULL;
+
+//______________________________________________________________________________
+AliAnalysisManager::AliAnalysisManager() 
+                   :TNamed(),
+                    fTree(NULL),
+                    fCurrentEntry(-1),
+                    fMode(kLocalAnalysis),
+                    fInitOK(kFALSE),
+                    fTasks(NULL),
+                    fTopTasks(NULL),
+                    fZombies(NULL),
+                    fContainers(NULL),
+                    fInputs(NULL),
+                    fOutputs(NULL)
+{
+// Dummy constructor.
+   fgAnalysisManager = this;
+}
+
 //______________________________________________________________________________
-AliAnalysisManager::AliAnalysisManager() : TSelector()
+AliAnalysisManager::AliAnalysisManager(const char *name, const char *title)
+                   :TNamed(name,title),
+                    fTree(NULL),
+                    fCurrentEntry(-1),
+                    fMode(kLocalAnalysis),
+                    fInitOK(kFALSE),
+                    fDebug(0),
+                    fTasks(NULL),
+                    fTopTasks(NULL),
+                    fZombies(NULL),
+                    fContainers(NULL),
+                    fInputs(NULL),
+                    fOutputs(NULL)
 {
 // Default constructor.
-   if (TClass::IsCallingNew() == TClass::kDummyNew) {
-      fInitOK     = kFALSE;
-      fContainers = 0;
-      fInputs     = 0;
-      fOutputs    = 0;  
-      fTasks      = 0;
-      fTopTasks   = 0;
-      fZombies    = 0;
-      fStatus     = 0;
-   } else {    
-      fInitOK     = kFALSE;
-      fContainers = new TObjArray();
-      fInputs     = new TObjArray();
-      fOutputs    = new TObjArray();  
-      fTasks      = new TObjArray();
-      fTopTasks   = new TObjArray();
-      fZombies    = new TObjArray();
-//      fStatus     = new AliAnalysisInfo(this);
-   }
+   fgAnalysisManager = this;
+   fTasks      = new TObjArray();
+   fTopTasks   = new TObjArray();
+   fZombies    = new TObjArray();
+   fContainers = new TObjArray();
+   fInputs     = new TObjArray();
+   fOutputs    = new TObjArray();
 }
 
 //______________________________________________________________________________
 AliAnalysisManager::AliAnalysisManager(const AliAnalysisManager& other)
-                   :TSelector(other)
+                   :TNamed(other),
+                    fTree(NULL),
+                    fCurrentEntry(-1),
+                    fMode(other.fMode),
+                    fInitOK(other.fInitOK),
+                    fDebug(other.fDebug),
+                    fTasks(NULL),
+                    fTopTasks(NULL),
+                    fZombies(NULL),
+                    fContainers(NULL),
+                    fInputs(NULL),
+                    fOutputs(NULL)
 {
 // Copy constructor.
-   fInitOK     = other.IsInitialized();
-   fContainers = new TObjArray(*other.GetContainers());
-   fInputs     = new TObjArray(*other.GetInputs());
-   fOutputs    = new TObjArray(*other.GetOutputs());
-   fTasks      = new TObjArray(*other.GetTasks());
-   fTopTasks   = new TObjArray(*other.GetTopTasks());
-   fZombies    = new TObjArray(*other.GetZombieTasks());
-//   fStatus     = new AliAnalysisInfo(this);
+   fTasks      = new TObjArray(*other.fTasks);
+   fTopTasks   = new TObjArray(*other.fTopTasks);
+   fZombies    = new TObjArray(*other.fZombies);
+   fContainers = new TObjArray(*other.fContainers);
+   fInputs     = new TObjArray(*other.fInputs);
+   fOutputs    = new TObjArray(*other.fOutputs);
+   fgAnalysisManager = this;
 }
    
 //______________________________________________________________________________
@@ -80,15 +116,19 @@ AliAnalysisManager& AliAnalysisManager::operator=(const AliAnalysisManager& othe
 {
 // Assignment
    if (&other != this) {
-      TSelector::operator=(other);
-      fInitOK     = other.IsInitialized();
-      fContainers = new TObjArray(*other.GetContainers());
-      fInputs     = new TObjArray(*other.GetInputs());
-      fOutputs    = new TObjArray(*other.GetOutputs());
-      fTasks      = new TObjArray(*other.GetTasks());
-      fTopTasks   = new TObjArray(*other.GetTopTasks());
-      fZombies    = new TObjArray(*other.GetZombieTasks());
-//      fStatus     = new AliAnalysisInfo(this);
+      TNamed::operator=(other);
+      fTree       = NULL;
+      fCurrentEntry = -1;
+      fMode       = other.fMode;
+      fInitOK     = other.fInitOK;
+      fDebug      = other.fDebug;
+      fTasks      = new TObjArray(*other.fTasks);
+      fTopTasks   = new TObjArray(*other.fTopTasks);
+      fZombies    = new TObjArray(*other.fZombies);
+      fContainers = new TObjArray(*other.fContainers);
+      fInputs     = new TObjArray(*other.fInputs);
+      fOutputs    = new TObjArray(*other.fOutputs);
+      fgAnalysisManager = this;
    }
    return *this;
 }
@@ -97,42 +137,110 @@ AliAnalysisManager& AliAnalysisManager::operator=(const AliAnalysisManager& othe
 AliAnalysisManager::~AliAnalysisManager()
 {
 // Destructor.
-   if (fContainers) {fContainers->Delete(); delete fContainers;}
-   if (fInputs) delete fInputs;
-   if (fOutputs) delete fOutputs;
    if (fTasks) {fTasks->Delete(); delete fTasks;}
    if (fTopTasks) delete fTopTasks;
    if (fZombies) delete fZombies;
+   if (fContainers) {fContainers->Delete(); delete fContainers;}
+   if (fInputs) delete fInputs;
+   if (fOutputs) delete fOutputs;
+   if (fgAnalysisManager==this) fgAnalysisManager = NULL;
 }
 
 //______________________________________________________________________________
-void AliAnalysisManager::Init(TTree */*tree*/)
+Int_t AliAnalysisManager::GetEntry(Long64_t entry, Int_t getall)
+{
+// Read one entry of the tree or a whole branch.
+   if (fDebug > 1) {
+      cout << "== AliAnalysisManager::GetEntry()" << endl;
+   }   
+   fCurrentEntry = entry;
+   return fTree ? fTree->GetTree()->GetEntry(entry, getall) : 0;
+}
+   
+//______________________________________________________________________________
+void 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;
+   if (fDebug > 1) {
+      printf("->AliAnalysisManager::Init(%s)\n", tree->GetName());
+   }
+   if (!fInitOK) InitAnalysis();
+   if (!fInitOK) return;
+   fTree = tree;
+   AliAnalysisDataContainer *top = (AliAnalysisDataContainer*)fInputs->At(0);
+   if (!top) {
+      cout<<"Error: No top input container !" <<endl;
+      return;
+   }
+   top->SetData(tree);
+   if (fDebug > 1) {
+      printf("<-AliAnalysisManager::Init(%s)\n", tree->GetName());
+   }
 }
 
 //______________________________________________________________________________
-void AliAnalysisManager::Begin(TTree */*tree*/)
+void AliAnalysisManager::Begin(TTree *tree)
 {
   // The Begin() function is called at the start of the query.
   // When running with PROOF Begin() is only called on the client.
   // The tree argument is deprecated (on PROOF 0 is passed).
+   if (fDebug > 1) {
+      cout << "AliAnalysisManager::Begin()" << endl;
+   }   
+   Init(tree);
 }
 
 //______________________________________________________________________________
-void AliAnalysisManager::SlaveBegin(TTree */*tree*/)
+void AliAnalysisManager::SlaveBegin(TTree *tree)
 {
   // The SlaveBegin() function is called after the Begin() function.
   // When running with PROOF SlaveBegin() is called on each slave server.
   // The tree argument is deprecated (on PROOF 0 is passed).
+   if (fDebug > 1) {
+      cout << "->AliAnalysisManager::SlaveBegin()" << endl;
+   }
+
+   TIter next(fTasks);
+   AliAnalysisTask *task;
+   // Call CreateOutputObjects for all tasks
+   while ((task=(AliAnalysisTask*)next())) {
+      TDirectory *curdir = gDirectory;
+      task->CreateOutputObjects();
+      if (curdir) curdir->cd();
+   }   
+   if (fMode == kLocalAnalysis) Init(tree);   
+   if (fDebug > 1) {
+      cout << "<-AliAnalysisManager::SlaveBegin()" << endl;
+   }
 }
 
 //______________________________________________________________________________
-Bool_t AliAnalysisManager::Process(Long64_t /*entry*/)
+Bool_t AliAnalysisManager::Notify()
+{
+   // The Notify() function is called when a new file is opened. This
+   // can be either for a new TTree in a TChain or when when a new TTree
+   // 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) {
+      TFile *curfile = fTree->GetCurrentFile();
+      if (curfile && fDebug>1) printf("AliAnalysisManager::Notify() file: %s\n", curfile->GetName());
+      TIter next(fTasks);
+      AliAnalysisTask *task;
+      // Call Notify for all tasks
+      while ((task=(AliAnalysisTask*)next())) 
+         task->Notify();      
+   }
+   return kTRUE;
+}    
+
+//______________________________________________________________________________
+Bool_t AliAnalysisManager::Process(Long64_t entry)
 {
   // The Process() function is called for each entry in the tree (or possibly
   // keyed object in the case of PROOF) to be processed. The entry argument
@@ -151,15 +259,123 @@ Bool_t AliAnalysisManager::Process(Long64_t /*entry*/)
   //  The entry is always the local entry number in the current tree.
   //  Assuming that fChain is the pointer to the TChain being processed,
   //  use fChain->GetTree()->GetEntry(entry).
-  return kFALSE;
+   if (fDebug > 1) {
+      cout << "->AliAnalysisManager::Process()" << endl;
+   }
+   GetEntry(entry);
+   ExecAnalysis();
+   if (fDebug > 1) {
+      cout << "<-AliAnalysisManager::Process()" << endl;
+   }
+   return kTRUE;
 }
 
 //______________________________________________________________________________
-void AliAnalysisManager::SlaveTerminate()
+void AliAnalysisManager::PackOutput(TList *target)
 {
-  // The SlaveTerminate() function is called after all entries or objects
-  // have been processed. When running with PROOF SlaveTerminate() is called
-  // on each slave server.
+  // Pack all output data containers in the output list. Called at SlaveTerminate
+  // stage in PROOF case for each slave.
+   if (fDebug > 1) {
+      cout << "->AliAnalysisManager::PackOutput()" << endl;
+   }   
+   if (!target) {
+      Error("PackOutput", "No target. Aborting.");
+      return;
+   }
+
+   if (fMode == kProofAnalysis) {
+      TIter next(fOutputs);
+      AliAnalysisDataContainer *output;
+      while ((output=(AliAnalysisDataContainer*)next())) {
+         if (fDebug > 1) printf("   Packing container %s...\n", output->GetName());
+         if (output->GetData()) target->Add(output->ExportData());
+      }
+   } 
+   if (fDebug > 1) {
+      printf("<-AliAnalysisManager::PackOutput: output list contains %d containers\n", target->GetSize());
+   }
+}
+
+//______________________________________________________________________________
+void AliAnalysisManager::ImportWrappers(TList *source)
+{
+// Import data in output containers from wrappers coming in source.
+   if (fDebug > 1) {
+      cout << "->AliAnalysisManager::ImportWrappers()" << endl;
+   }   
+   TIter next(fOutputs);
+   AliAnalysisDataContainer *cont;
+   AliAnalysisDataWrapper   *wrap;
+   Int_t icont = 0;
+   while ((cont=(AliAnalysisDataContainer*)next())) {
+      wrap = (AliAnalysisDataWrapper*)source->FindObject(cont->GetName());
+      if (!wrap && fDebug>1) {
+         printf("(WW) ImportWrappers: container %s not found in analysis output !\n", cont->GetName());
+         continue;
+      }
+      icont++;
+      if (fDebug > 1) printf("   Importing data for container %s\n", wrap->GetName());
+      if (cont->GetFileName()) printf("    -> %s\n", cont->GetFileName());
+      cont->ImportData(wrap);
+   }         
+   if (fDebug > 1) {
+      cout << "<-AliAnalysisManager::ImportWrappers(): "<< icont << " containers imported" << endl;
+   }   
+}
+
+//______________________________________________________________________________
+void AliAnalysisManager::UnpackOutput(TList *source)
+{
+  // Called by AliAnalysisSelector::Terminate. Output containers should
+  // be in source in the same order as in fOutputs.
+   if (fDebug > 1) {
+      cout << "->AliAnalysisManager::UnpackOutput()" << endl;
+   }   
+   if (!source) {
+      Error("UnpackOutput", "No target. Aborting.");
+      return;
+   }
+   if (fDebug > 1) {
+      printf("   Source list contains %d containers\n", source->GetSize());
+   }   
+
+   if (fMode == kProofAnalysis) ImportWrappers(source);
+
+   TIter next(fOutputs);
+   AliAnalysisDataContainer *output;
+   while ((output=(AliAnalysisDataContainer*)next())) {
+      if (!output->GetData()) continue;
+      // Check if the output need to be written to a file.
+      const char *filename = output->GetFileName();
+      if (!filename || !strlen(filename)) continue;
+      TFile *file = (TFile*)gROOT->GetListOfFiles()->FindObject(filename);
+      if (file) file->cd();
+      else      file = new TFile(filename, "RECREATE");
+      if (file->IsZombie()) continue;
+      // Reparent data to this file
+      TMethodCall callEnv;
+      if (output->GetData()->IsA())
+         callEnv.InitWithPrototype(output->GetData()->IsA(), "SetDirectory", "TDirectory*");
+      if (callEnv.IsValid()) {
+         callEnv.SetParam((Long_t) file);
+         callEnv.Execute(output->GetData());
+      }
+      output->GetData()->Write();
+      // Check if there are client tasks that run in single-shot mode.
+      if (!output->HasConsumers()) continue;
+      output->SetEventByEvent(kFALSE);
+      TObjArray *list = output->GetConsumers();
+      Int_t ncons = list->GetEntriesFast();
+      for (Int_t i=0; i<ncons; i++) {
+         AliAnalysisTask *task = (AliAnalysisTask*)list->At(i);
+         task->CheckNotify(kTRUE);
+         // If task is active, execute it
+         if (task->IsActive()) task->ExecuteTask();         
+      }
+   }
+   if (fDebug > 1) {
+      cout << "<-AliAnalysisManager::UnpackOutput()" << endl;
+   }   
 }
 
 //______________________________________________________________________________
@@ -167,7 +383,17 @@ void AliAnalysisManager::Terminate()
 {
   // The Terminate() function is the last function to be called during
   // a query. It always runs on the client, it can be used to present
-  // the results graphically or save the results to file.
+  // the results graphically.
+   if (fDebug > 1) {
+      cout << "->AliAnalysisManager::Terminate()" << endl;
+   }   
+   AliAnalysisTask *task;
+   TIter next(fTasks);
+   // Call Terminate() for tasks
+   while ((task=(AliAnalysisTask*)next())) task->Terminate();
+   if (fDebug > 1) {
+      cout << "<-AliAnalysisManager::Terminate()" << endl;
+   }   
 }
 
 //______________________________________________________________________________
@@ -188,10 +414,10 @@ AliAnalysisTask *AliAnalysisManager::GetTask(const char *name) const
 
 //______________________________________________________________________________
 AliAnalysisDataContainer *AliAnalysisManager::CreateContainer(const char *name, 
-                                TClass *datatype, EAliAnalysisContType type)
+                                TClass *datatype, EAliAnalysisContType type, const char *filename)
 {
 // Create a data container of a certain type. Types can be:
-//   kNormalContainer  = 0, used to exchange date between tasks
+//   kExchangeContainer  = 0, used to exchange date between tasks
 //   kInputContainer   = 1, used to store input data
 //   kOutputContainer  = 2, used for posting results
    AliAnalysisDataContainer *cont = new AliAnalysisDataContainer(name, datatype);
@@ -201,9 +427,11 @@ AliAnalysisDataContainer *AliAnalysisManager::CreateContainer(const char *name,
          fInputs->Add(cont);
          break;
       case kOutputContainer:
+         if (fOutputs->FindObject(name)) printf("CreateContainer: warning: a container named %s existing !\n",name);
          fOutputs->Add(cont);
+         if (filename && strlen(filename)) cont->SetFileName(filename);
          break;
-      case kNormalContainer:
+      case kExchangeContainer:
          break;   
    }
    return cont;
@@ -216,7 +444,7 @@ Bool_t AliAnalysisManager::ConnectInput(AliAnalysisTask *task, Int_t islot,
 // Connect input of an existing task to a data container.
    if (!fTasks->FindObject(task)) {
       AddTask(task);
-      AliInfo(Form("Task %s not registered. Now owned by analysis manager", task->GetName()));
+      Warning("ConnectInput", "Task %s not registered. Now owned by analysis manager", task->GetName());
    } 
    Bool_t connected = task->ConnectInput(islot, cont);
    return connected;
@@ -229,7 +457,7 @@ Bool_t AliAnalysisManager::ConnectOutput(AliAnalysisTask *task, Int_t islot,
 // Connect output of an existing task to a data container.
    if (!fTasks->FindObject(task)) {
       AddTask(task);
-      AliInfo(Form("Task %s not registered. Now owned by analysis manager", task->GetName()));
+      Warning("ConnectOutput", "Task %s not registered. Now owned by analysis manager", task->GetName());
    } 
    Bool_t connected = task->ConnectOutput(islot, cont);
    return connected;
@@ -255,17 +483,9 @@ Bool_t AliAnalysisManager::InitAnalysis()
 // and data containers are properly connected
    // Check for input/output containers
    fInitOK = kFALSE;
-   if (!fInputs->GetEntriesFast()) {
-      AliError("No input container defined. At least one container should store input data");
-      return kFALSE;
-   }   
-   if (!fOutputs->GetEntriesFast()) {
-      AliError("No output container defined. At least one container should store output data");
-      return kFALSE;
-   }   
    // Check for top tasks (depending only on input data containers)
    if (!fTasks->First()) {
-      AliError("Analysis have no tasks !");
+      Error("InitAnalysis", "Analysis has no tasks !");
       return kFALSE;
    }   
    TIter next(fTasks);
@@ -273,44 +493,37 @@ Bool_t AliAnalysisManager::InitAnalysis()
    AliAnalysisDataContainer *cont;
    Int_t ntop = 0;
    Int_t nzombies = 0;
-   Bool_t is_zombie = kFALSE;
-   Bool_t is_top = kTRUE;
+   Bool_t iszombie = kFALSE;
+   Bool_t istop = kTRUE;
    Int_t i;
    while ((task=(AliAnalysisTask*)next())) {
-      is_top = kTRUE;
-      is_zombie = kFALSE;
+      istop = kTRUE;
+      iszombie = kFALSE;
       Int_t ninputs = task->GetNinputs();
-      if (!ninputs) {
-         task->SetZombie();
-         fZombies->Add(task);
-         nzombies++;
-         AliWarning(Form("Task %s has no input slots defined ! Declared zombie...",task->GetName()));
-         continue;
-      }
       for (i=0; i<ninputs; i++) {
          cont = task->GetInputSlot(i)->GetContainer();
          if (!cont) {
-            if (!is_zombie) {
+            if (!iszombie) {
                task->SetZombie();
                fZombies->Add(task);
                nzombies++;
-               is_zombie = kTRUE;
+               iszombie = kTRUE;
             }   
-            AliWarning(Form("Input slot %i of task %s has no container connected ! Declared zombie...",
-                       i,task->GetName()));
+            Error("InitAnalysis", "Input slot %d of task %s has no container connected ! Declared zombie...", 
+                  i, task->GetName()); 
          }
-         if (is_zombie) continue;
+         if (iszombie) continue;
          // Check if cont is an input container
-         if (is_top && !fInputs->FindObject(cont)) is_top=kFALSE;
+         if (istop && !fInputs->FindObject(cont)) istop=kFALSE;
          // Connect to parent task
       }
-      if (is_top) {
+      if (istop) {
          ntop++;
          fTopTasks->Add(task);
       }
    }
    if (!ntop) {
-      AliError("No top task defined. At least one task should be connected only to input containers");
+      Error("InitAnalysis", "No top task defined. At least one task should be connected only to input containers");
       return kFALSE;
    }                        
    // Check now if there are orphan tasks
@@ -323,7 +536,7 @@ Bool_t AliAnalysisManager::InitAnalysis()
    while ((task=(AliAnalysisTask*)next())) {
       if (!task->IsUsed()) {
          norphans++;
-         AliWarning(Form("Task %s is orphan",task->GetName()));
+         Warning("InitAnalysis", "Task %s is orphan", task->GetName());
       }   
    }          
    // Check the task hierarchy (no parent task should depend on data provided
@@ -331,11 +544,12 @@ Bool_t AliAnalysisManager::InitAnalysis()
    for (i=0; i<ntop; i++) {
       task = (AliAnalysisTask*)fTopTasks->At(i);
       if (task->CheckCircularDeps()) {
-         AliError("Found illegal circular dependencies between following tasks:");
+         Error("InitAnalysis", "Found illegal circular dependencies between following tasks:");
          PrintStatus("dep");
          return kFALSE;
       }   
    }
+   fInitOK = kTRUE;
    return kTRUE;
 }   
 
@@ -356,14 +570,144 @@ void AliAnalysisManager::ResetAnalysis()
    CleanContainers();
 }
 
+//______________________________________________________________________________
+void AliAnalysisManager::StartAnalysis(const char *type, TTree *tree)
+{
+// Start analysis for this manager. Analysis task can be: LOCAL, PROOF or GRID.
+   if (!fInitOK) {
+      Error("StartAnalysis","Analysis manager was not initialized !");
+      return;
+   }
+   if (fDebug>1) {
+      cout << "StartAnalysis: " << GetName() << endl;   
+   }   
+   TString anaType = type;
+   anaType.ToLower();
+   fMode = kLocalAnalysis;
+   if (tree) {
+      if (anaType.Contains("proof"))     fMode = kProofAnalysis;
+      else if (anaType.Contains("grid")) fMode = kGridAnalysis;
+   }
+   if (fMode == kGridAnalysis) {
+      Warning("StartAnalysis", "GRID analysis mode not implemented. Running local.");
+      fMode = kLocalAnalysis;
+   }
+   char line[128];
+   SetEventLoop(kFALSE);
+   // Disable by default all branches and set event loop mode
+   if (tree) {
+//      tree->SetBranchStatus("*",0);
+      SetEventLoop(kTRUE);
+   }   
+   AliAnalysisDataContainer *cont = 0;
+   TIter nextc(fInputs);
+   // Force top containers have the same event loop type as the analysis
+   while ((cont=(AliAnalysisDataContainer*)nextc())) cont->SetEventByEvent(IsEventLoop());
+   AliAnalysisDataContainer *cont_top = (AliAnalysisDataContainer*)fInputs->First();
+
+   TChain *chain = dynamic_cast<TChain*>(tree);
+
+   // Initialize locally all tasks
+   TIter next(fTasks);
+   AliAnalysisTask *task;
+   while ((task=(AliAnalysisTask*)next())) {
+      for (Int_t islot=0; islot<task->GetNinputs(); islot++) {
+         cont = task->GetInputSlot(islot)->GetContainer();
+         if (cont==cont_top) break;
+         cont = 0;
+      }
+      // All tasks feeding from the top containers must have the same event loop type
+//      if (cont) task->SetExecPerEvent(IsEventLoop());
+//      else task->SetExecPerEvent(task->IsExecPerEvent());         
+      task->LocalInit();
+   }
+   
+   switch (fMode) {
+      case kLocalAnalysis:
+         if (!tree) {
+            TIter next(fTasks);
+            AliAnalysisTask *task;
+            // Call CreateOutputObjects for all tasks
+            while ((task=(AliAnalysisTask*)next())) {
+               TDirectory *curdir = gDirectory;
+               task->CreateOutputObjects();
+               if (curdir) curdir->cd();
+            }   
+            ExecAnalysis();
+            Terminate();
+            return;
+         } 
+         // Run tree-based analysis via AliAnalysisSelector  
+         gROOT->ProcessLine(".L $ALICE_ROOT/ANALYSIS/AliAnalysisSelector.cxx+");
+         cout << "===== RUNNING LOCAL ANALYSIS " << GetName() << " ON TREE " << tree->GetName() << endl;
+         sprintf(line, "AliAnalysisSelector *selector = new AliAnalysisSelector((AliAnalysisManager*)0x%lx);",(ULong_t)this);
+         gROOT->ProcessLine(line);
+         sprintf(line, "((TTree*)0x%lx)->Process(selector);",(ULong_t)tree);
+         gROOT->ProcessLine(line);
+         break;
+      case kProofAnalysis:
+         if (!gROOT->GetListOfProofs() || !gROOT->GetListOfProofs()->GetEntries()) {
+            printf("StartAnalysis: no PROOF!!!\n");
+            return;
+         }   
+         sprintf(line, "gProof->AddInput((TObject*)0x%lx);", (ULong_t)this);
+         gROOT->ProcessLine(line);
+         if (chain) {
+            chain->SetProof();
+            cout << "===== RUNNING PROOF ANALYSIS " << GetName() << " ON CHAIN " << chain->GetName() << endl;
+            chain->Process(gSystem->ExpandPathName("$ALICE_ROOT/ANALYSIS/AliAnalysisSelector.cxx+"));
+         } else {
+            printf("StartAnalysis: no chain\n");
+            return;
+         }      
+         break;
+      case kGridAnalysis:
+         Warning("StartAnalysis", "GRID analysis mode not implemented. Running local.");
+   }   
+}   
+
 //______________________________________________________________________________
 void AliAnalysisManager::ExecAnalysis(Option_t *option)
 {
 // Execute analysis.
-   TIter next(fTopTasks);
+   if (!fInitOK) {
+     Error("ExecAnalysis", "Analysis manager was not initialized !");
+      return;
+   }   
    AliAnalysisTask *task;
-   while ((task=(AliAnalysisTask*)next()))
+   // Check if the top tree is active.
+   if (fTree) {
+      if (fDebug>1) {
+         printf("AliAnalysisManager::ExecAnalysis\n");
+      }   
+      TIter next(fTasks);
+   // De-activate all tasks
+      while ((task=(AliAnalysisTask*)next())) task->SetActive(kFALSE);
+      AliAnalysisDataContainer *cont = (AliAnalysisDataContainer*)fInputs->At(0);
+      if (!cont) {
+             Error("ExecAnalysis","Cannot execute analysis in TSelector mode without at least one top container");
+         return;
+      }   
+      cont->SetData(fTree); // This will notify all consumers
+      TIter next1(cont->GetConsumers());
+      while ((task=(AliAnalysisTask*)next1())) {
+//         task->SetActive(kTRUE);
+         if (fDebug >1) {
+            cout << "    Executing task " << task->GetName() << endl;
+         }   
+         task->ExecuteTask(option);
+      }
+      return;
+   }   
+   // The event loop is not controlled by TSelector   
+   TIter next2(fTopTasks);
+   while ((task=(AliAnalysisTask*)next2())) {
+      task->SetActive(kTRUE);
+      if (fDebug > 1) {
+         cout << "    Executing task " << task->GetName() << endl;
+      }   
       task->ExecuteTask(option);
+   }   
 }
 
 //______________________________________________________________________________