]> git.uio.no Git - u/mrichter/AliRoot.git/blob - PWG4/macros/anaExampleTask.C
Reader: Add option to remove or not event with primary vertex not reconstructed
[u/mrichter/AliRoot.git] / PWG4 / macros / anaExampleTask.C
1 /* $Id:  $ */
2 //--------------------------------------------------
3 // Example macro to do analysis with the 
4 // AliAnalysisTaksSE
5 // Can be executed with Root and AliRoot
6 //
7 // Pay attention to the options and definitions
8 // set in the lines below
9 //
10 //  Author : Gustavo Conesa Balbastre (INFN-LNF)
11 //
12 //-------------------------------------------------
13 enum anaModes {mLocal, mLocalCAF,mPROOF,mGRID};
14 //mLocal: Analyze locally files in your computer
15 //mLocalCAF: Analyze locally CAF files
16 //mPROOF: Analyze CAF files with PROOF
17
18 //---------------------------------------------------------------------------
19 //Settings to read locally several files, only for "mLocal" mode
20 //The different values are default, they can be set with environmental 
21 //variables: INDIR, PATTERN, NEVENT, respectivelly
22 char * kInDir = "/user/data/files/"; 
23 char * kPattern = ""; // Data are in files kInDir/kPattern+i 
24 Int_t kEvent = 1; // Number of files
25 //---------------------------------------------------------------------------
26 //Collection file for grid analysis
27 char * kXML = "collection.xml";
28 //---------------------------------------------------------------------------
29 //Scale histograms from file. Change to kTRUE when xsection file exists
30 //Put name of file containing xsection 
31 //Put number of events per ESD file
32 //This is an specific case for normalization of Pythia files.
33 const Bool_t kGetXSectionFromFileAndScale = kFALSE ;
34 const char * kXSFileName = "pyxsec.root";
35 const Int_t kNumberOfEventsPerFile = 100; 
36 //---------------------------------------------------------------------------
37
38 const Bool_t kMC = kTRUE; //With real data kMC = kFALSE
39 const TString kInputData = "ESD";//ESD, AOD, MC
40 TString kTreeName = "esdTree";
41
42 void anaExampleTask(Int_t mode=mLocal)
43 {
44   // Main
45
46   //--------------------------------------------------------------------
47   // Load analysis libraries
48   // Look at the method below, 
49   // change whatever you need for your analysis case
50   // ------------------------------------------------------------------
51   LoadLibraries(mode) ;
52   
53   //-------------------------------------------------------------------------------------------------
54   //Create chain from ESD and from cross sections files, look below for options.
55   //------------------------------------------------------------------------------------------------- 
56   if(kInputData == "ESD") kTreeName = "esdTree" ;
57   else if(kInputData == "AOD") kTreeName = "aodTree" ;
58   else if (kInputData == "MC") kTreeName = "TE" ;
59   else {
60     cout<<"Wrong  data type "<<kInputData<<endl;
61     break;
62   }
63         
64   TChain *chain   = new TChain(kTreeName) ;
65   TChain * chainxs = new TChain("Xsection") ;
66   CreateChain(mode, chain, chainxs);  
67
68   if(chain){
69     AliLog::SetGlobalLogLevel(AliLog::kError);//Minimum prints on screen
70     
71     //--------------------------------------
72     // Make the analysis manager
73     //-------------------------------------
74     AliAnalysisManager *mgr  = new AliAnalysisManager("Manager", "Manager");
75     // MC handler
76     if(kMC || kInputData == "MC"){
77       AliMCEventHandler* mcHandler = new AliMCEventHandler();
78       mcHandler->SetReadTR(kFALSE);//Do not search TrackRef file
79       mgr->SetMCtruthEventHandler(mcHandler);
80       if( kInputData == "MC") mgr->SetInputEventHandler(NULL);
81     }
82
83     // AOD output handler
84     AliAODHandler* aodoutHandler   = new AliAODHandler();
85     aodoutHandler->SetOutputFileName("aod.root");
86     //aodoutHandler->SetCreateNonStandardAOD();
87     mgr->SetOutputEventHandler(aodoutHandler);
88     
89     //input
90     if(kInputData == "ESD"){
91       // ESD handler
92       AliESDInputHandler *esdHandler = new AliESDInputHandler();
93       mgr->SetInputEventHandler(esdHandler);
94     }
95     if(kInputData == "AOD"){
96       // AOD handler
97       AliAODInputHandler *aodHandler = new AliAODInputHandler();
98       mgr->SetInputEventHandler(aodHandler);
99     }
100
101     //mgr->SetDebugLevel(-1); // For debugging
102
103     //-------------------------------------------------------------------------
104     //Define task, put here any other task that you want to use.
105     //-------------------------------------------------------------------------
106     AliAnalysisTaskPHOSExample * taskex = new AliAnalysisTaskPHOSExample ("Gamma");
107     mgr->AddTask(taskex);
108     
109     // Create containers for input/output
110     AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer();
111     AliAnalysisDataContainer *coutput1 = mgr->GetCommonOutputContainer();
112     AliAnalysisDataContainer *coutput2 = mgr->CreateContainer("histos", TList::Class(),
113                                                               AliAnalysisManager::kOutputContainer, "histos.root");
114     
115     mgr->ConnectInput  (taskex,     0, cinput1);
116     mgr->ConnectOutput (taskex,     0, coutput1 );
117     mgr->ConnectOutput (taskex,     1, coutput2 );
118   
119     //------------------------  
120     //Scaling task
121     //-----------------------
122     Int_t nfiles = chainxs->GetEntries();
123     if(kGetXSectionFromFileAndScale && nfiles > 0){
124       //Get the cross section
125       Double_t xsection=0; 
126       Float_t ntrials = 0;
127       GetAverageXsection(chainxs, xsection, ntrials);
128       
129       AliAnaScale * scale = new AliAnaScale("scale") ;
130       scale->Set(xsection/ntrials/nfiles) ;
131       scale->MakeSumw2(kFALSE);//If you want histograms with error bars set to kTRUE
132       //scale->SetDebugLevel(2);
133       mgr->AddTask(scale);
134                 
135       AliAnalysisDataContainer *coutput3 = mgr->CreateContainer("histosscaled", TList::Class(),
136                                                                 AliAnalysisManager::kOutputContainer, "gammahistosscaled.root");
137       mgr->ConnectInput  (scale,     0, coutput2);
138       mgr->ConnectOutput (scale,     0, coutput3 );
139     }
140     
141     //-----------------------
142     // Run the analysis
143     //-----------------------    
144     TString smode = "";
145     if (mode==mLocal || mode == mLocalCAF) 
146       smode = "local";
147     else if (mode==mPROOF) 
148       smode = "proof";
149     else if (mode==mGRID) 
150       smode = "local";
151     
152     mgr->InitAnalysis();
153     mgr->PrintStatus();
154     mgr->StartAnalysis(smode.Data(),chain);
155           
156     cout <<" Analysis ended sucessfully "<< endl ;
157           
158   }
159   else cout << "Chain was not produced ! "<<endl;
160   
161 }
162
163 void  LoadLibraries(const anaModes mode) {
164   
165   //--------------------------------------
166   // Load the needed libraries most of them already loaded by aliroot
167   //--------------------------------------
168   gSystem->Load("libTree.so");
169   gSystem->Load("libGeom.so");
170   gSystem->Load("libVMC.so");
171   gSystem->Load("libXMLIO.so");
172   
173   //----------------------------------------------------------
174   // >>>>>>>>>>> Local mode <<<<<<<<<<<<<< 
175   //----------------------------------------------------------
176   if (mode==mLocal || mode == mLocalCAF || mode == mGRID) {
177     //--------------------------------------------------------
178     // If you want to use already compiled libraries 
179     // in the aliroot distribution
180     //--------------------------------------------------------
181     //gSystem->Load("libSTEERBase");
182     //gSystem->Load("libESD");
183     //gSystem->Load("libAOD");
184     //gSystem->Load("libANALYSIS");
185     //gSystem->Load("libANALYSISalice");
186         //gSystem->Load("libPHOSUtils");
187         //gSystem->Load("libEMCALUtils");         
188     //gSystem->Load("libPWG4PartCorrBase");
189         //gSystem->Load("libPWG4PartCorrDep");
190
191     //--------------------------------------------------------
192     //If you want to use root and par files from aliroot
193     //--------------------------------------------------------  
194     SetupPar("STEERBase");
195     SetupPar("ESD");
196     SetupPar("AOD");
197     SetupPar("ANALYSIS");
198     SetupPar("ANALYSISalice");
199     SetupPar("PHOSUtils");
200         SetupPar("EMCALUtils");
201     SetupPar("PWG4PartCorrBase");
202     SetupPar("PWG4PartCorrDep");
203   }
204
205   //---------------------------------------------------------
206   // <<<<<<<<<< PROOF mode >>>>>>>>>>>>
207   //---------------------------------------------------------
208   else if (mode==mPROOF) {
209     //
210     // Connect to proof
211     // Put appropriate username here
212     // TProof::Reset("proof://mgheata@lxb6046.cern.ch"); 
213     TProof::Open("proof://mgheata@lxb6046.cern.ch");
214     
215     // Enable the STEERBase Package
216     gProof->UploadPackage("STEERBase.par");
217     gProof->EnablePackage("STEERBase");
218     // Enable the ESD Package
219     gProof->UploadPackage("ESD.par");
220     gProof->EnablePackage("ESD");
221     // Enable the AOD Package
222     gProof->UploadPackage("AOD.par");
223     gProof->EnablePackage("AOD");
224     // Enable the Analysis Package
225     gProof->UploadPackage("ANALYSIS.par");
226     gProof->EnablePackage("ANALYSIS");
227         // Enable the PHOSUtils Package
228         gProof->UploadPackage("PHOSUtils.par");
229         gProof->EnablePackage("PHOSUtils");
230         // Enable the EMCALUtils Package
231         gProof->UploadPackage("EMCALUtils.par");
232         gProof->EnablePackage("EMCALUtils");
233     // Enable PartCorr analysis
234     gProof->UploadPackage("PWG4PartCorrBase.par");
235     gProof->EnablePackage("PWG4PartCorrBase");
236     gProof->UploadPackage("PWG4PartCorrDep.par");
237     gProof->EnablePackage("PWG4PartCorrDep");
238     //
239     gProof->ShowEnabledPackages();
240   }  
241   
242 }
243
244 void SetupPar(char* pararchivename)
245 {
246   //Load par files, create analysis libraries
247   //For testing, if par file already decompressed and modified
248   //classes then do not decompress.
249  
250   TString cdir(Form("%s", gSystem->WorkingDirectory() )) ; 
251   TString parpar(Form("%s.par", pararchivename)) ; 
252   if ( gSystem->AccessPathName(parpar.Data()) ) {
253     gSystem->ChangeDirectory(gSystem->Getenv("ALICE_ROOT")) ;
254     TString processline(Form(".! make %s", parpar.Data())) ; 
255     gROOT->ProcessLine(processline.Data()) ;
256     gSystem->ChangeDirectory(cdir) ; 
257     //processline = Form(".! mv /tmp/%s .", parpar.Data()) ;
258         processline = Form(".! mv $ALICE_ROOT/%s .", parpar.Data()) ;
259     gROOT->ProcessLine(processline.Data()) ;
260   } 
261   if ( gSystem->AccessPathName(pararchivename) ) {  
262     TString processline = Form(".! tar xvzf %s",parpar.Data()) ;
263     gROOT->ProcessLine(processline.Data());
264   }
265   
266   TString ocwd = gSystem->WorkingDirectory();
267   gSystem->ChangeDirectory(pararchivename);
268   
269   // check for BUILD.sh and execute
270   if (!gSystem->AccessPathName("PROOF-INF/BUILD.sh")) {
271     printf("*******************************\n");
272     printf("*** Building PAR archive    ***\n");
273     cout<<pararchivename<<endl;
274     printf("*******************************\n");
275     
276     if (gSystem->Exec("PROOF-INF/BUILD.sh")) {
277       Error("runProcess","Cannot Build the PAR Archive! - Abort!");
278       return -1;
279     }
280   }
281   // check for SETUP.C and execute
282   if (!gSystem->AccessPathName("PROOF-INF/SETUP.C")) {
283     printf("*******************************\n");
284     printf("*** Setup PAR archive       ***\n");
285     cout<<pararchivename<<endl;
286     printf("*******************************\n");
287     gROOT->Macro("PROOF-INF/SETUP.C");
288   }
289   
290   gSystem->ChangeDirectory(ocwd.Data());
291   printf("Current dir: %s\n", ocwd.Data());
292 }
293
294
295
296 void CreateChain(const anaModes mode, TChain * chain, TChain * chainxs){
297   //Fills chain with data
298   TString ocwd = gSystem->WorkingDirectory();
299   
300   //-----------------------------------------------------------
301   //Analysis of CAF data locally and with PROOF
302   //-----------------------------------------------------------
303   if(mode ==mPROOF || mode ==mLocalCAF){
304     // Chain from CAF
305     gROOT->LoadMacro("$ALICE_ROOT/PWG0/CreateESDChain.C");
306     // The second parameter is the number of input files in the chain
307     chain = CreateESDChain("ESD12001.txt", 5);  
308   }
309   
310   //---------------------------------------
311   //Local files analysis
312   //---------------------------------------
313   else if(mode == mLocal){    
314     //If you want to add several ESD files sitting in a common directory INDIR
315     //Specify as environmental variables the directory (INDIR), the number of files 
316     //to analyze (NEVENT) and the pattern name of the directories with files (PATTERN)
317
318     if(gSystem->Getenv("INDIR"))  
319       kInDir = gSystem->Getenv("INDIR") ; 
320     else cout<<"INDIR not set, use default: "<<kInDir<<endl;    
321     
322     if(gSystem->Getenv("PATTERN"))   
323       kPattern = gSystem->Getenv("PATTERN") ; 
324     else  cout<<"PATTERN not set, use default: "<<kPattern<<endl;
325     
326     if(gSystem->Getenv("NEVENT"))
327       kEvent = atoi(gSystem->Getenv("NEVENT")) ;
328     else cout<<"NEVENT not set, use default: "<<kEvent<<endl;
329     
330     //Check if env variables are set and are correct
331     if ( kInDir  && kEvent) {
332       printf("Get %d files from directory %s\n",kEvent,kInDir);
333       if ( ! gSystem->cd(kInDir) ) {//check if ESDs directory exist
334         printf("%s does not exist\n", kInDir) ;
335         return ;
336       }
337       cout<<"INDIR : "<<kInDir<<endl;
338       cout<<"NEVENT : "<<kEvent<<endl;
339       cout<<"PATTERN: " <<kPattern<<endl;
340                 
341       TString datafile="";
342       if(kInputData == "ESD") datafile = "AliESDs.root" ;
343       else if(kInputData == "AOD") datafile = "aod.root" ;
344       else if(kInputData == "MC")  datafile = "galice.root" ;
345
346       //Loop on ESD files, add them to chain
347       Int_t event =0;
348       Int_t skipped=0 ; 
349       char file[120] ;
350       char filexs[120] ;
351       
352       for (event = 0 ; event < kEvent ; event++) {
353         sprintf(file, "%s/%s%d/%s", kInDir,kPattern,event,datafile.Data()) ; 
354         sprintf(filexs, "%s/%s%d/%s", kInDir,kPattern,event,kXSFileName) ; 
355         TFile * fESD = 0 ; 
356         //Check if file exists and add it, if not skip it
357         if ( fESD = TFile::Open(file)) {
358           if ( fESD->Get(kTreeName) ) { 
359             printf("++++ Adding %s\n", file) ;
360             chain->AddFile(file);
361             chainxs->Add(filexs) ; 
362           }
363         }
364         else { 
365           printf("---- Skipping %s\n", file) ;
366           skipped++ ;
367         }
368       }
369       printf("number of entries # %lld, skipped %d\n", chain->GetEntries(), skipped) ;  
370     }
371     else {
372       TString input = "AliESDs.root" ;
373       cout<<">>>>>> No list added, take a single file <<<<<<<<< "<<input<<endl;
374       chain->AddFile(input);
375     }
376     
377   }// local files analysis
378   
379   //------------------------------
380   //GRID xml files
381   //-----------------------------
382   else if(mode == mGRID){
383     //Get colection file. It is specified by the environmental
384     //variable XML
385
386     if(gSystem->Getenv("XML") )
387       kXML = gSystem->Getenv("XML");
388     else
389       sprintf(kXML, "collection.xml") ; 
390     
391     if (!TFile::Open(kXML)) {
392       printf("No collection file with name -- %s -- was found\n",kXML);
393       return ;
394     }
395     else cout<<"XML file "<<kXML<<endl;
396
397     //Load necessary libraries and connect to the GRID
398     gSystem->Load("libNetx.so") ; 
399     gSystem->Load("libRAliEn.so"); 
400     TGrid::Connect("alien://") ;
401
402     //Feed Grid with collection file
403     //TGridCollection * collection =  (TGridCollection*)gROOT->ProcessLine(Form("TAlienCollection::Open(\"%s\", 0)", kXML));
404     TGridCollection * collection = (TGridCollection*) TAlienCollection::Open(kXML);
405     if (! collection) {
406       AliError(Form("%s not found", kXML)) ; 
407       return kFALSE ; 
408     }
409     TGridResult* result = collection->GetGridResult("",0 ,0);
410    
411     // Makes the ESD chain 
412     printf("*** Getting the Chain       ***\n");
413     for (Int_t index = 0; index < result->GetEntries(); index++) {
414       TString alienURL = result->GetKey(index, "turl") ; 
415       cout << "================== " << alienURL << endl ; 
416       chain->Add(alienURL) ; 
417       alienURL.ReplaceAll("AliESDs.root",kXSFileName);
418       chainxs->Add(alienURL) ; 
419     }
420   }// xml analysis
421   
422   gSystem->ChangeDirectory(ocwd.Data());
423 }
424
425 //________________________________________________
426 void GetAverageXsection(TTree * tree, Double_t & xs, Float_t & ntr)
427 {
428   // Read the PYTHIA statistics from the file pyxsec.root created by
429   // the function WriteXsection():
430   // integrated cross section (xsection) and
431   // the  number of Pyevent() calls (ntrials)
432   // and calculate the weight per one event xsection/ntrials
433   // The spectrum calculated by a user should be
434   // multiplied by this weight, something like this:
435   // TH1F *userSpectrum ... // book and fill the spectrum
436   // userSpectrum->Scale(weight)
437   //
438   // Yuri Kharlov 19 June 2007
439   // Gustavo Conesa 15 April 2008
440   Double_t xsection = 0;
441   UInt_t    ntrials = 0;
442   xs = 0;
443   ntr = 0;
444   
445   Int_t nfiles =  tree->GetEntries()  ;
446   if (tree && nfiles > 0) {
447     tree->SetBranchAddress("xsection",&xsection);
448     tree->SetBranchAddress("ntrials",&ntrials);
449     for(Int_t i = 0; i < nfiles; i++){
450       tree->GetEntry(i);
451       xs += xsection ;
452       ntr += ntrials ;
453       cout << "xsection " <<xsection<<" ntrials "<<ntrials<<endl; 
454     }
455     
456     xs =   xs /  nfiles;
457     ntr =  ntr / nfiles;
458     cout << "-----------------------------------------------------------------"<<endl;
459     cout << "Average of "<< nfiles<<" files: xsection " <<xs<<" ntrials "<<ntr<<endl; 
460     cout << "-----------------------------------------------------------------"<<endl;
461   } 
462   else cout << " >>>> Empty tree !!!! <<<<< "<<endl;
463   
464 }
465
466
467