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