]> git.uio.no Git - u/mrichter/AliRoot.git/blobdiff - ANALYSIS/AliAnalysisManager.cxx
Added possibility to save canvases created by Terminate as pictures.
[u/mrichter/AliRoot.git] / ANALYSIS / AliAnalysisManager.cxx
index 136f64ee76b0ee3b93b29347f699417494c79385..d34a434a130c74b5cc991f06c066ff6398c83f52 100644 (file)
@@ -27,6 +27,7 @@
 
 #include <Riostream.h>
 
+#include <TError.h>
 #include <TClass.h>
 #include <TFile.h>
 #include <TKey.h>
@@ -35,6 +36,7 @@
 #include <TSystem.h>
 #include <TROOT.h>
 #include <TCanvas.h>
+#include <TStopwatch.h>
 
 #include "AliAnalysisSelector.h"
 #include "AliAnalysisGrid.h"
@@ -49,6 +51,7 @@
 ClassImp(AliAnalysisManager)
 
 AliAnalysisManager *AliAnalysisManager::fgAnalysisManager = NULL;
+TString AliAnalysisManager::fgCommonFileName = "";
 
 //______________________________________________________________________________
 AliAnalysisManager::AliAnalysisManager(const char *name, const char *title)
@@ -78,6 +81,7 @@ AliAnalysisManager::AliAnalysisManager(const char *name, const char *title)
 {
 // Default constructor.
    fgAnalysisManager = this;
+   fgCommonFileName  = "AnalysisResults.root";
    fTasks      = new TObjArray();
    fTopTasks   = new TObjArray();
    fZombies    = new TObjArray();
@@ -94,7 +98,7 @@ AliAnalysisManager::AliAnalysisManager(const AliAnalysisManager& other)
                     fInputEventHandler(NULL),
                     fOutputEventHandler(NULL),
                     fMCtruthEventHandler(NULL),
-                   fEventPool(NULL),
+                    fEventPool(NULL),
                     fCurrentEntry(-1),
                     fNSysInfo(0),
                     fMode(other.fMode),
@@ -120,6 +124,7 @@ AliAnalysisManager::AliAnalysisManager(const AliAnalysisManager& other)
    fContainers = new TObjArray(*other.fContainers);
    fInputs     = new TObjArray(*other.fInputs);
    fOutputs    = new TObjArray(*other.fOutputs);
+   fgCommonFileName  = "AnalysisResults.root";
    fgAnalysisManager = this;
 }
    
@@ -150,6 +155,7 @@ AliAnalysisManager& AliAnalysisManager::operator=(const AliAnalysisManager& othe
       fSelector   = NULL;
       fGridHandler = NULL;
       fExtraFiles = other.fExtraFiles;
+      fgCommonFileName = "AnalysisResults.root";
       fgAnalysisManager = this;
    }
    return *this;
@@ -437,24 +443,16 @@ void AliAnalysisManager::PackOutput(TList *target)
          }
          // Check if data was posted to this container. If not, issue an error.
          if (!output->GetData() && !isManagedByHandler) {
-            Error("PackOutput", "No data for output container %s. Forgot to PostData ?\n", output->GetName());
+            Error("PackOutput", "No data for output container %s. Forgot to PostData ?", output->GetName());
             continue;
          }   
          if (!output->IsSpecialOutput()) {
             // Normal outputs
             if (strlen(filename) && !isManagedByHandler) {
-               // File resident outputs
-               TFile *file = output->GetFile();
                // Backup current folder
                TDirectory *opwd = gDirectory;
-               // Create file if not existing and register to container.
-               if (file) file->cd();
-               else      file = new TFile(filename, "RECREATE"); 
-               if (file->IsZombie()) {
-                  Fatal("PackOutput", "Could not recreate file %s\n", filename);
-                  return;
-               }   
-               output->SetFile(file);
+               // File resident outputs
+               TFile *file = AliAnalysisManager::OpenFile(output, "RECREATE", kTRUE);
                // Clear file list to release object ownership to user.
                file->Clear();
                // Save data to file, then close.
@@ -479,6 +477,7 @@ void AliAnalysisManager::PackOutput(TList *target)
                   file->ls();
                }   
                file->Close();
+               output->SetFile(NULL);
                // Restore current directory
                if (opwd) opwd->cd();
             } else {
@@ -500,7 +499,7 @@ void AliAnalysisManager::PackOutput(TList *target)
             TFile *file = output->GetFile();
             if (!file) {
                AliAnalysisTask *producer = output->GetProducer();
-               Error("PackOutput", 
+               Fatal("PackOutput", 
                      "File %s for special container %s was NOT opened in %s::CreateOutputObjects !!!",
                      output->GetFileName(), output->GetName(), producer->ClassName());
                continue;
@@ -539,6 +538,7 @@ void AliAnalysisManager::PackOutput(TList *target)
                   file->ls();
                }
                file->Close();
+               output->SetFile(NULL);
             }
             // Restore current directory
             if (opwd) opwd->cd();
@@ -603,6 +603,7 @@ void AliAnalysisManager::ImportWrappers(TList *source)
    AliAnalysisDataWrapper   *wrap;
    Int_t icont = 0;
    Bool_t inGrid = (fMode == kGridAnalysis)?kTRUE:kFALSE;
+   TDirectory *cdir = gDirectory;
    while ((cont=(AliAnalysisDataContainer*)next())) {
       wrap = 0;
       if (cont->GetProducer()->IsPostEventLoop() && !inGrid) continue;
@@ -630,25 +631,21 @@ void AliAnalysisManager::ImportWrappers(TList *source)
          // 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...
-         TFile *f = TFile::Open(filename, "READ");
+         TFile *f = (TFile*)gROOT->GetListOfFiles()->FindObject(filename);
+         if (!f) f = TFile::Open(filename, "READ");
          if (!f) {
             Error("ImportWrappers", "Cannot open file %s in read-only mode", filename);
             continue;
          }   
          TObject *obj = 0;
-         // Try to fetch first a list object having the container name.
-         obj = f->Get(cont->GetName());
-         if (!obj) {
-         // Fetch first object from file having the container type.
-            TIter nextkey(f->GetListOfKeys());
-            TKey *key;
-            while ((key=(TKey*)nextkey())) {
-               obj = f->Get(key->GetName());
-               if (obj && obj->IsA()->InheritsFrom(cont->GetType())) break;
-            }                     
-         }
+         // Cd to the directory pointed by the container
+         TString folder = cont->GetFolderName();
+         if (!folder.IsNull()) f->cd(folder);
+         // Try to fetch first an object having the container name.
+         obj = gDirectory->Get(cont->GetName());
          if (!obj) {
-            Error("ImportWrappers", "Could not find object for container %s in file %s", cont->GetName(), filename);
+            Warning("ImportWrappers", "Could not import object for container %s in file %s:%s.\n Object will not be available in Terminate()", 
+                    cont->GetName(), filename, cont->GetFolderName());
             continue;
          }  
          wrap = new AliAnalysisDataWrapper(obj);
@@ -661,12 +658,13 @@ void AliAnalysisManager::ImportWrappers(TList *source)
       }
       icont++;
       if (fDebug > 1) {
-         printf("   Importing data for container %s", cont->GetName());
+         printf("   Importing data for container %s\n", cont->GetName());
          if (strlen(filename)) printf("    -> file %s\n", filename);
          else printf("\n");
       }   
       cont->ImportData(wrap);
-   }         
+   }
+   if (cdir) cdir->cd();
    if (fDebug > 0) printf("<-AliAnalysisManager::ImportWrappers(): %d containers imported\n", icont);
 }
 
@@ -715,12 +713,33 @@ void AliAnalysisManager::Terminate()
   // the results graphically.
    if (fDebug > 0) printf("->AliAnalysisManager::Terminate()\n");
    AliAnalysisTask *task;
+   AliAnalysisDataContainer *output;
    TIter next(fTasks);
+   TStopwatch timer;
    // Call Terminate() for tasks
-   while ((task=(AliAnalysisTask*)next())) task->Terminate();
+   while ((task=(AliAnalysisTask*)next())) {
+      // Save all the canvases produced by the Terminate
+      TString pictname = Form("%s_%s", task->GetName(), task->ClassName());
+      Int_t istart = gROOT->GetListOfCanvases()->GetEntries()-1;
+      task->Terminate();
+      if (TObject::TestBit(kSaveCanvases)) {
+         timer.Start();
+         while (timer.CpuTime()<5) {
+            timer.Continue();
+            gSystem->ProcessEvents();
+         }   
+         Int_t iend = gROOT->GetListOfCanvases()->GetEntries()-1;
+         if (istart == iend) continue;
+         TCanvas *canvas;
+         for (Int_t ipict=0; ipict<iend-istart; ipict++) {
+            canvas = (TCanvas*)gROOT->GetListOfCanvases()->At(istart+ipict);
+            if (!canvas) continue;         
+            canvas->SaveAs(Form("%s_%02d.gif", pictname.Data(),ipict));
+         }   
+      }
+   }   
    //
    TIter next1(fOutputs);
-   AliAnalysisDataContainer *output;
    while ((output=(AliAnalysisDataContainer*)next1())) {
       // Special outputs or grid files have the files already closed and written.
       if (fMode == kGridAnalysis) continue;
@@ -737,14 +756,23 @@ void AliAnalysisManager::Terminate()
       }      
       if (!strlen(filename)) continue;
       if (!output->GetData()) continue;
-      TFile *file = output->GetFile();
       TDirectory *opwd = gDirectory;
-      file = (TFile*)gROOT->GetListOfFiles()->FindObject(filename);
+      TFile *file = output->GetFile();
+      if (!file) file = (TFile*)gROOT->GetListOfFiles()->FindObject(filename);
       if (!file) file = new TFile(filename, "RECREATE");
-      if (file->IsZombie()) continue;
+      if (file->IsZombie()) {
+         Error("Terminate", "Cannot open output file %s", filename);
+         continue;
+      }   
       output->SetFile(file);
       file->cd();
-      if (fDebug > 1) printf("   writing output data %s to file %s\n", output->GetData()->GetName(), file->GetName());
+      // Check for a folder request
+      TString dir = output->GetFolderName();
+      if (!dir.IsNull()) {
+         if (!file->GetDirectory(dir)) file->mkdir(dir);
+         file->cd(dir);
+      }  
+      if (fDebug > 1) printf("   writing output data %s to file %s:%s\n", output->GetData()->GetName(), file->GetName(), output->GetFolderName());
       if (output->GetData()->InheritsFrom(TCollection::Class())) {
       // If data is a collection, we set the name of the collection 
       // as the one of the container and we save as a single key.
@@ -768,6 +796,7 @@ void AliAnalysisManager::Terminate()
       TDirectory *opwd = gDirectory;
       if (output->GetFile()) {
          output->GetFile()->Close();
+         output->SetFile(NULL);
          // Copy merged outputs in alien if requested
          if (fSpecialOutputLocation.Length() && 
              fSpecialOutputLocation.BeginsWith("alien://")) {
@@ -803,6 +832,12 @@ void AliAnalysisManager::Terminate()
          delete tree;
       }
       if (cdir) cdir->cd();
+   }
+   // Validate the output files
+   if (ValidateOutputFiles()) {
+      ofstream out;
+      out.open("outputs_valid", ios::out);
+      out.close();
    }      
    if (fDebug > 0) printf("<-AliAnalysisManager::Terminate()\n");
 }
@@ -832,11 +867,13 @@ AliAnalysisDataContainer *AliAnalysisManager::CreateContainer(const char *name,
                                 TClass *datatype, EAliAnalysisContType type, const char *filename)
 {
 // Create a data container of a certain type. Types can be:
-//   kExchangeContainer  = 0, used to exchange date between tasks
+//   kExchangeContainer  = 0, used to exchange data between tasks
 //   kInputContainer   = 1, used to store input data
-//   kOutputContainer  = 2, used for posting results
+//   kOutputContainer  = 2, used for writing result to a file
+// filename: composed by file#folder (e.g. results.root#INCLUSIVE) - will write
+// the output object to a folder inside the output file
    if (fContainers->FindObject(name)) {
-      Error("CreateContainer","A container named %s already defined !\n",name);
+      Error("CreateContainer","A container named %s already defined !",name);
       return NULL;
    }   
    AliAnalysisDataContainer *cont = new AliAnalysisDataContainer(name, datatype);
@@ -910,8 +947,10 @@ Bool_t AliAnalysisManager::InitAnalysis()
 {
 // Initialization of analysis chain of tasks. Should be called after all tasks
 // and data containers are properly connected
-   // Check for input/output containers
+   // Reset flag and remove valid_outputs file if exists
    fInitOK = kFALSE;
+   if (!gSystem->AccessPathName("outputs_valid"))
+      gSystem->Unlink("outputs_valid");
    // Check for top tasks (depending only on input data containers)
    if (!fTasks->First()) {
       Error("InitAnalysis", "Analysis has no tasks !");
@@ -1127,7 +1166,7 @@ void AliAnalysisManager::StartAnalysis(const char *type, TTree *tree, Long64_t n
          break;
       case kProofAnalysis:
          if (!gROOT->GetListOfProofs() || !gROOT->GetListOfProofs()->GetEntries()) {
-            printf("StartAnalysis: no PROOF!!!\n");
+            Error("StartAnalysis", "No PROOF!!! Aborting.");
             return;
          }   
          sprintf(line, "gProof->AddInput((TObject*)0x%lx);", (ULong_t)this);
@@ -1137,7 +1176,7 @@ void AliAnalysisManager::StartAnalysis(const char *type, TTree *tree, Long64_t n
             cout << "===== RUNNING PROOF ANALYSIS " << GetName() << " ON CHAIN " << chain->GetName() << endl;
             chain->Process("AliAnalysisSelector", "", nentries, firstentry);
          } else {
-            printf("StartAnalysis: no chain\n");
+            Error("StartAnalysis", "No chain!!! Aborting.");
             return;
          }      
          break;
@@ -1195,7 +1234,7 @@ void AliAnalysisManager::StartAnalysis(const char *type, const char *dataset, Lo
    }
    
    if (!gROOT->GetListOfProofs() || !gROOT->GetListOfProofs()->GetEntries()) {
-      printf("StartAnalysis: no PROOF!!!\n");
+      Error("StartAnalysis", "No PROOF!!! Aborting.");
       return;
    }   
    sprintf(line, "gProof->AddInput((TObject*)0x%lx);", (ULong_t)this);
@@ -1212,32 +1251,138 @@ void AliAnalysisManager::StartAnalysis(const char *type, const char *dataset, Lo
 }   
 
 //______________________________________________________________________________
-TFile *AliAnalysisManager::OpenProofFile(const char *filename, const char *option)
+TFile *AliAnalysisManager::OpenFile(AliAnalysisDataContainer *cont, const char *option, Bool_t ignoreProof)
+{
+// Opens according the option the file specified by cont->GetFileName() and changes
+// current directory to cont->GetFolderName(). If the file was already opened, it
+// checks if the option UPDATE was preserved. File open via TProofOutputFile can
+// be optionally ignored.
+  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
+  TString filename = cont->GetFileName();
+  TFile *f = NULL;
+  if (filename.IsNull()) {
+    ::Error("AliAnalysisManager::OpenFile", "No file name specified for container %s", cont->GetName());
+    return NULL;
+  }
+  if (mgr->GetAnalysisType()==AliAnalysisManager::kProofAnalysis && cont->IsSpecialOutput()
+      && !ignoreProof)
+    f = mgr->OpenProofFile(cont,option);
+  else {
+    // Check first if the file is already opened
+    f = (TFile*)gROOT->GetListOfFiles()->FindObject(filename);
+    if (f) {
+      // Check if option "UPDATE" was preserved 
+      TString opt(option);
+      opt.ToUpper();
+      if ((opt=="UPDATE") && (opt!=f->GetOption())) 
+        ::Fatal("AliAnalysisManager::OpenFile", "File %s already opened, but not in UPDATE mode!", cont->GetFileName());
+    } else {
+      f = TFile::Open(filename, option);
+    }    
+  }   
+  if (f && !f->IsZombie() && !f->TestBit(TFile::kRecovered)) {
+    cont->SetFile(f);
+    // Cd to file
+    f->cd();
+    // Check for a folder request
+    TString dir = cont->GetFolderName(); 
+    if (!dir.IsNull()) {
+      if (!f->GetDirectory(dir)) f->mkdir(dir);
+      f->cd(dir);
+    }
+    return f;
+  }
+  ::Fatal("AliAnalysisManager::OpenFile", "File %s could not be opened", filename.Data());
+  cont->SetFile(NULL);
+  return NULL;
+}    
+//______________________________________________________________________________
+TFile *AliAnalysisManager::OpenProofFile(AliAnalysisDataContainer *cont, const char *option)
 {
 // Opens a special output file used in PROOF.
-   char line[256];
-   if (fMode!=kProofAnalysis || !fSelector) {
-      Error("OpenProofFile","Cannot open PROOF file %s",filename);
-      return NULL;
-   } 
-   if (fSpecialOutputLocation.Length()) {
-      TFile *f = (TFile*)gROOT->GetListOfFiles()->FindObject(filename);
-      if (!f) f = new TFile(filename, option);
+  TString line;
+  TString filename = cont->GetFileName();
+  if (cont == fCommonOutput) {
+     if (fOutputEventHandler) filename = fOutputEventHandler->GetOutputFileName();
+     else Fatal("OpenProofFile","No output container. Aborting.");
+  }   
+  TFile *f = NULL;
+  if (fMode!=kProofAnalysis || !fSelector) {
+    Fatal("OpenProofFile","Cannot open PROOF file %s: no PROOF or selector",filename.Data());
+    return NULL;
+  } 
+  if (fSpecialOutputLocation.Length()) {
+    f = (TFile*)gROOT->GetListOfFiles()->FindObject(filename);
+    if (f) {
+      // Check if option "UPDATE" was preserved 
+      TString opt(option);
+      opt.ToUpper();
+      if ((opt=="UPDATE") && (opt!=f->GetOption()))
+        Fatal("OpenProofFile", "File %s already opened, but not in UPDATE mode!", cont->GetFileName());
+    } else {
+      f = new TFile(filename, option);
+    }
+    if (f && !f->IsZombie() && !f->TestBit(TFile::kRecovered)) {
+      cont->SetFile(f);
+      // Cd to file
+      f->cd();
+      // Check for a folder request
+      TString dir = cont->GetFolderName(); 
+      if (dir.Length()) {
+        if (!f->GetDirectory(dir)) f->mkdir(dir);
+        f->cd(dir);
+      }      
       return f;
-   }   
-   sprintf(line, "TProofOutputFile *pf = new TProofOutputFile(\"%s\");", filename);
-   if (fDebug > 1) printf("=== %s\n", line);
-   gROOT->ProcessLine(line);
-   sprintf(line, "pf->OpenFile(\"%s\");", option);
-   gROOT->ProcessLine(line);
-   if (fDebug > 1) {
+    }
+    Fatal("OpenProofFile", "File %s could not be opened", cont->GetFileName());
+    cont->SetFile(NULL);
+    return NULL;       
+  }
+  // Check if there is already a proof output file in the output list
+  TObject *pof = fSelector->GetOutputList()->FindObject(filename);
+  if (pof) {
+    // Get the actual file
+    line = Form("((TProofOutputFile*)0x%lx)->GetFileName();", (ULong_t)pof);
+    filename = (const char*)gROOT->ProcessLine(line);
+    f = (TFile*)gROOT->GetListOfFiles()->FindObject(filename);
+    if (!f) Fatal("OpenProofFile", "Proof output file found but no file opened for %s", filename.Data());
+    // Check if option "UPDATE" was preserved 
+    TString opt(option);
+    opt.ToUpper();
+    if ((opt=="UPDATE") && (opt!=f->GetOption())) 
+      Fatal("OpenProofFile", "File %s already opened, but not in UPDATE mode!", cont->GetFileName());
+  } else {
+    line = Form("TProofOutputFile *pf = new TProofOutputFile(\"%s\");", filename.Data());
+    if (fDebug > 1) printf("=== %s\n", line.Data());
+    gROOT->ProcessLine(line);
+    line = Form("pf->OpenFile(\"%s\");", option);
+    gROOT->ProcessLine(line);
+    f = gFile;
+    if (fDebug > 1) {
       gROOT->ProcessLine("pf->Print()");
-      printf(" == proof file name: %s\n", gFile->GetName());
-   }   
-   sprintf(line, "((TList*)0x%lx)->Add(pf);",(ULong_t)fSelector->GetOutputList());
-   if (fDebug > 1) printf("=== %s\n", line);
-   gROOT->ProcessLine(line);
-   return gFile;
+      printf(" == proof file name: %s", f->GetName());
+    }   
+    // Add to proof output list
+    line = Form("((TList*)0x%lx)->Add(pf);",(ULong_t)fSelector->GetOutputList());
+    if (fDebug > 1) printf("=== %s", line.Data());
+    gROOT->ProcessLine(line);
+  }
+  if (f && !f->IsZombie() && !f->TestBit(TFile::kRecovered)) {
+    cont->SetFile(f);
+    // Cd to file
+    f->cd();
+    // Check for a folder request
+    TString dir = cont->GetFolderName(); 
+    if (!dir.IsNull()) {
+      if (!f->GetDirectory(dir)) f->mkdir(dir);
+      f->cd(dir);
+    }
+    return f;
+  }
+  Fatal("OpenProofFile", "File %s could not be opened", cont->GetFileName());
+  cont->SetFile(NULL);  
+  return NULL;
 }   
 
 //______________________________________________________________________________
@@ -1402,3 +1547,38 @@ void AliAnalysisManager::GetAnalysisTypeString(TString &type) const
          type = "mix";
    }
 }
+
+//______________________________________________________________________________
+Bool_t AliAnalysisManager::ValidateOutputFiles() const
+{
+// Validate all output files.
+   TIter next(fOutputs);
+   AliAnalysisDataContainer *output;
+   TDirectory *cdir = gDirectory;
+   TString openedFiles;
+   while ((output=(AliAnalysisDataContainer*)next())) {
+      TString filename = output->GetFileName();
+      if (filename == "default") {
+         if (!fOutputEventHandler) continue;
+         filename = fOutputEventHandler->GetOutputFileName();
+      }
+      // Check if the file is closed
+      if (openedFiles.Contains(filename)) continue;;
+      TFile *file = (TFile*)gROOT->GetListOfFiles()->FindObject(filename);
+      if (file) {
+         Warning("ValidateOutputs", "File %s was not closed. Closing.", filename.Data());
+         file->Close();
+      }
+      file = TFile::Open(filename);
+      if (!file || file->IsZombie() || file->TestBit(TFile::kRecovered)) {
+         Error("ValidateOutputs", "Output file <%s> was not created or invalid", filename.Data());
+         cdir->cd();
+         return kFALSE;
+      }
+      file->Close();
+      openedFiles += filename;
+      openedFiles += " ";
+   }
+   cdir->cd();
+   return kTRUE;
+}