]> git.uio.no Git - u/mrichter/AliRoot.git/blob - PWG4/macros/ana.C
Completion of previous checkin
[u/mrichter/AliRoot.git] / PWG4 / macros / ana.C
1 /* $Id:  $ */
2 //--------------------------------------------------
3 // Example macro to do analysis with the 
4 // analysis classes in PWG4PartCorr
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 ana(Int_t mode=mLocal, TString configName = "ConfigAnalysisPhoton")
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     }
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(-1); // For debugging, do not uncomment if you want no messages.
101
102     //-------------------------------------------------------------------------
103     //Define task, put here any other task that you want to use.
104     //-------------------------------------------------------------------------
105     AliAnalysisTaskParticleCorrelation * taskpwg4 = new AliAnalysisTaskParticleCorrelation ("Particle");
106     taskpwg4->SetConfigFileName(configName); //Default name is ConfigAnalysis
107                 
108     mgr->AddTask(taskpwg4);
109     
110     // Create containers for input/output
111     AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer();
112     AliAnalysisDataContainer *coutput1 = mgr->GetCommonOutputContainer();
113     AliAnalysisDataContainer *coutput2 = mgr->CreateContainer("histos", TList::Class(),
114                                                               AliAnalysisManager::kOutputContainer, "histos.root");
115     
116     mgr->ConnectInput  (taskpwg4,     0, cinput1);
117     mgr->ConnectOutput (taskpwg4,     0, coutput1 );
118     mgr->ConnectOutput (taskpwg4,     1, coutput2 );
119   
120     //------------------------  
121     //Scaling task
122     //-----------------------
123     Int_t nfiles = chainxs->GetEntries();
124     //cout<<"Get? "<<kGetXSectionFromFileAndScale<<" nfiles "<<nfiles<<endl;
125     if(kGetXSectionFromFileAndScale && nfiles > 0){
126       //cout<<"Init AnaScale"<<endl;
127       //Get the cross section
128       Double_t xsection=0; 
129       Float_t ntrials = 0;
130       GetAverageXsection(chainxs, xsection, ntrials);
131       
132       AliAnaScale * scale = new AliAnaScale("scale") ;
133       scale->Set(xsection/ntrials/kNumberOfEventsPerFile/nfiles) ;
134       scale->MakeSumw2(kFALSE);//If you want histograms with error bars set to kTRUE
135       //scale->SetDebugLevel(2);
136       mgr->AddTask(scale);
137       
138       AliAnalysisDataContainer *coutput3 = mgr->CreateContainer("histosscaled", TList::Class(),
139                                                                 AliAnalysisManager::kOutputContainer, "histosscaled.root");
140       mgr->ConnectInput  (scale,     0, coutput2);
141       mgr->ConnectOutput (scale,     0, coutput3 );
142     }
143     
144     //-----------------------
145     // Run the analysis
146     //-----------------------    
147     TString smode = "";
148     if (mode==mLocal || mode == mLocalCAF) 
149       smode = "local";
150     else if (mode==mPROOF) 
151       smode = "proof";
152     else if (mode==mGRID) 
153       smode = "local";
154     
155     mgr->InitAnalysis();
156     mgr->PrintStatus();
157     mgr->StartAnalysis(smode.Data(),chain);
158
159 cout <<" Analysis ended sucessfully "<< endl ;
160
161   }
162   else cout << "Chain was not produced ! "<<endl;
163   
164 }
165
166 void  LoadLibraries(const anaModes mode) {
167   
168   //--------------------------------------
169   // Load the needed libraries most of them already loaded by aliroot
170   //--------------------------------------
171   gSystem->Load("libTree.so");
172   gSystem->Load("libGeom.so");
173   gSystem->Load("libVMC.so");
174   gSystem->Load("libXMLIO.so");
175   
176   //----------------------------------------------------------
177   // >>>>>>>>>>> Local mode <<<<<<<<<<<<<< 
178   //----------------------------------------------------------
179   if (mode==mLocal || mode == mLocalCAF || mode == mGRID) {
180     //--------------------------------------------------------
181     // If you want to use already compiled libraries 
182     // in the aliroot distribution
183     //--------------------------------------------------------
184     //gSystem->Load("libSTEERBase");
185     //gSystem->Load("libESD");
186     //gSystem->Load("libAOD");
187     //gSystem->Load("libANALYSIS");
188     //gSystem->Load("libANALYSISalice");
189     //gSystem->Load("libPHOSUtils");
190     //gSystem->Load("libPWG4PartCorrBase");
191     //gSystem->Load("libPWG4PartCorrDep");
192         
193     //--------------------------------------------------------
194     //If you want to use root and par files from aliroot
195     //--------------------------------------------------------  
196     SetupPar("STEERBase");
197     SetupPar("ESD");
198     SetupPar("AOD");
199     SetupPar("ANALYSIS");
200     SetupPar("ANALYSISalice");
201 //If your analysis needs PHOS geometry uncomment following lines
202 //      SetupPar("PHOSUtils");
203 //      //Create Geometry
204 //    TGeoManager::Import("geometry.root") ; //need file "geometry.root" in local dir!!!!
205      SetupPar("PWG4PartCorrBase");
206      SetupPar("PWG4PartCorrDep");
207   }
208
209   //---------------------------------------------------------
210   // <<<<<<<<<< PROOF mode >>>>>>>>>>>>
211   //---------------------------------------------------------
212   else if (mode==mPROOF) {
213     //
214     // Connect to proof
215     // Put appropriate username here
216     // TProof::Reset("proof://mgheata@lxb6046.cern.ch"); 
217     TProof::Open("proof://mgheata@lxb6046.cern.ch");
218     
219     //    gProof->ClearPackages();
220     //    gProof->ClearPackage("ESD");
221     //    gProof->ClearPackage("AOD");
222     //    gProof->ClearPackage("ANALYSIS");   
223     //    gProof->ClearPackage("PWG4PartCorrBase");
224     //    gProof->ClearPackage("PWG4PartCorrDep");
225     
226     // Enable the STEERBase Package
227     gProof->UploadPackage("STEERBase.par");
228     gProof->EnablePackage("STEERBase");
229     // Enable the ESD Package
230     gProof->UploadPackage("ESD.par");
231     gProof->EnablePackage("ESD");
232     // Enable the AOD Package
233     gProof->UploadPackage("AOD.par");
234     gProof->EnablePackage("AOD");
235     // Enable the Analysis Package
236     gProof->UploadPackage("ANALYSIS.par");
237     gProof->EnablePackage("ANALYSIS");
238         // Enable the PHOS geometry Package
239     //gProof->UploadPackage("PHOSUtils.par");
240     //gProof->EnablePackage("PHOSUtils");
241     // Enable PartCorr analysis
242     gProof->UploadPackage("PWG4PartCorrBase.par");
243     gProof->EnablePackage("PWG4PartCorrBase");
244         gProof->UploadPackage("PWG4PartCorrDep.par");
245     gProof->EnablePackage("PWG4PartCorrDep");    
246     gProof->ShowEnabledPackages();
247   }  
248   
249 }
250
251 void SetupPar(char* pararchivename)
252 {
253   //Load par files, create analysis libraries
254   //For testing, if par file already decompressed and modified
255   //classes then do not decompress.
256  
257   TString cdir(Form("%s", gSystem->WorkingDirectory() )) ; 
258   TString parpar(Form("%s.par", pararchivename)) ; 
259   if ( gSystem->AccessPathName(parpar.Data()) ) {
260     gSystem->ChangeDirectory(gSystem->Getenv("ALICE_ROOT")) ;
261     TString processline(Form(".! make %s", parpar.Data())) ; 
262     gROOT->ProcessLine(processline.Data()) ;
263     gSystem->ChangeDirectory(cdir) ; 
264     processline = Form(".! mv $ALICE_ROOT/%s .", parpar.Data()) ;
265     gROOT->ProcessLine(processline.Data()) ;
266   } 
267   if ( gSystem->AccessPathName(pararchivename) ) {  
268     TString processline = Form(".! tar xvzf %s",parpar.Data()) ;
269     gROOT->ProcessLine(processline.Data());
270   }
271   
272   TString ocwd = gSystem->WorkingDirectory();
273   gSystem->ChangeDirectory(pararchivename);
274   
275   // check for BUILD.sh and execute
276   if (!gSystem->AccessPathName("PROOF-INF/BUILD.sh")) {
277     printf("*******************************\n");
278     printf("*** Building PAR archive    ***\n");
279     cout<<pararchivename<<endl;
280     printf("*******************************\n");
281     
282     if (gSystem->Exec("PROOF-INF/BUILD.sh")) {
283       Error("runProcess","Cannot Build the PAR Archive! - Abort!");
284       return -1;
285     }
286   }
287   // check for SETUP.C and execute
288   if (!gSystem->AccessPathName("PROOF-INF/SETUP.C")) {
289     printf("*******************************\n");
290     printf("*** Setup PAR archive       ***\n");
291     cout<<pararchivename<<endl;
292     printf("*******************************\n");
293     gROOT->Macro("PROOF-INF/SETUP.C");
294   }
295   
296   gSystem->ChangeDirectory(ocwd.Data());
297   printf("Current dir: %s\n", ocwd.Data());
298 }
299
300
301
302 void CreateChain(const anaModes mode, TChain * chain, TChain * chainxs){
303   //Fills chain with data
304   TString ocwd = gSystem->WorkingDirectory();
305   
306   //-----------------------------------------------------------
307   //Analysis of CAF data locally and with PROOF
308   //-----------------------------------------------------------
309   if(mode ==mPROOF || mode ==mLocalCAF){
310     // Chain from CAF
311     gROOT->LoadMacro("$ALICE_ROOT/PWG0/CreateESDChain.C");
312     // The second parameter is the number of input files in the chain
313     chain = CreateESDChain("ESD12001.txt", 5);  
314   }
315   
316   //---------------------------------------
317   //Local files analysis
318   //---------------------------------------
319   else if(mode == mLocal){    
320     //If you want to add several ESD files sitting in a common directory INDIR
321     //Specify as environmental variables the directory (INDIR), the number of files 
322     //to analyze (NEVENT) and the pattern name of the directories with files (PATTERN)
323
324     if(gSystem->Getenv("INDIR"))  
325       kInDir = gSystem->Getenv("INDIR") ; 
326     else cout<<"INDIR not set, use default: "<<kInDir<<endl;    
327     
328     if(gSystem->Getenv("PATTERN"))   
329       kPattern = gSystem->Getenv("PATTERN") ; 
330     else  cout<<"PATTERN not set, use default: "<<kPattern<<endl;
331     
332     if(gSystem->Getenv("NEVENT"))
333       kEvent = atoi(gSystem->Getenv("NEVENT")) ;
334     else cout<<"NEVENT not set, use default: "<<kEvent<<endl;
335     
336     //Check if env variables are set and are correct
337     if ( kInDir  && kEvent) {
338       printf("Get %d files from directory %s\n",kEvent,kInDir);
339       if ( ! gSystem->cd(kInDir) ) {//check if ESDs directory exist
340         printf("%s does not exist\n", kInDir) ;
341         return ;
342       }
343       cout<<"INDIR : "<<kInDir<<endl;
344       cout<<"NEVENT : "<<kEvent<<endl;
345       cout<<"PATTERN: " <<kPattern<<endl;
346       
347       TString datafile="";
348       if(kInputData == "ESD") datafile = "AliESDs.root" ;
349       else if(kInputData == "AOD") datafile = "aod.root" ;
350       else if(kInputData == "MC")  datafile = "galice.root" ;
351       
352       //Loop on ESD files, add them to chain
353       Int_t event =0;
354       Int_t skipped=0 ; 
355       char file[120] ;
356       char filexs[120] ;
357       
358       for (event = 0 ; event < kEvent ; event++) {
359         sprintf(file, "%s/%s%d/%s", kInDir,kPattern,event,datafile.Data()) ; 
360         sprintf(filexs, "%s/%s%d/%s", kInDir,kPattern,event,kXSFileName) ; 
361         TFile * fESD = 0 ; 
362         //Check if file exists and add it, if not skip it
363         if ( fESD = TFile::Open(file)) {
364           if ( fESD->Get(kTreeName) ) { 
365             printf("++++ Adding %s\n", file) ;
366             chain->AddFile(file);
367             chainxs->Add(filexs) ; 
368           }
369         }
370         else { 
371           printf("---- Skipping %s\n", file) ;
372           skipped++ ;
373         }
374       }
375       printf("number of entries # %lld, skipped %d\n", chain->GetEntries(), skipped*100) ;      
376     }
377     else {
378       TString input = "AliESDs.root" ;
379       cout<<">>>>>> No list added, take a single file <<<<<<<<< "<<input<<endl;
380       chain->AddFile(input);
381     }
382     
383   }// local files analysis
384   
385   //------------------------------
386   //GRID xml files
387   //-----------------------------
388   else if(mode == mGRID){
389     //Get colection file. It is specified by the environmental
390     //variable XML
391
392     if(gSystem->Getenv("XML") )
393       kXML = gSystem->Getenv("XML");
394     else
395       sprintf(kXML, "collection.xml") ; 
396     
397     if (!TFile::Open(kXML)) {
398       printf("No collection file with name -- %s -- was found\n",kXML);
399       return ;
400     }
401     else cout<<"XML file "<<kXML<<endl;
402
403     //Load necessary libraries and connect to the GRID
404     gSystem->Load("libNetx.so") ; 
405     gSystem->Load("libRAliEn.so"); 
406     TGrid::Connect("alien://") ;
407
408     //Feed Grid with collection file
409     //TGridCollection * collection =  (TGridCollection*)gROOT->ProcessLine(Form("TAlienCollection::Open(\"%s\", 0)", kXML));
410     TGridCollection * collection = (TGridCollection*) TAlienCollection::Open(kXML);
411     if (! collection) {
412       AliError(Form("%s not found", kXML)) ; 
413       return kFALSE ; 
414     }
415     TGridResult* result = collection->GetGridResult("",0 ,0);
416    
417     // Makes the ESD chain 
418     printf("*** Getting the Chain       ***\n");
419     for (Int_t index = 0; index < result->GetEntries(); index++) {
420       TString alienURL = result->GetKey(index, "turl") ; 
421       cout << "================== " << alienURL << endl ; 
422       chain->Add(alienURL) ; 
423       alienURL.ReplaceAll("AliESDs.root",kXSFileName);
424       chainxs->Add(alienURL) ; 
425     }
426   }// xml analysis
427   
428   gSystem->ChangeDirectory(ocwd.Data());
429 }
430
431 //________________________________________________
432 void GetAverageXsection(TTree * tree, Double_t & xs, Float_t & ntr)
433 {
434   // Read the PYTHIA statistics from the file pyxsec.root created by
435   // the function WriteXsection():
436   // integrated cross section (xsection) and
437   // the  number of Pyevent() calls (ntrials)
438   // and calculate the weight per one event xsection/ntrials
439   // The spectrum calculated by a user should be
440   // multiplied by this weight, something like this:
441   // TH1F *userSpectrum ... // book and fill the spectrum
442   // userSpectrum->Scale(weight)
443   //
444   // Yuri Kharlov 19 June 2007
445   // Gustavo Conesa 15 April 2008
446   Double_t xsection = 0;
447   UInt_t    ntrials = 0;
448   xs = 0;
449   ntr = 0;
450   
451   Int_t nfiles =  tree->GetEntries()  ;
452   if (tree && nfiles > 0) {
453     tree->SetBranchAddress("xsection",&xsection);
454     tree->SetBranchAddress("ntrials",&ntrials);
455     for(Int_t i = 0; i < nfiles; i++){
456       tree->GetEntry(i);
457       xs += xsection ;
458       ntr += ntrials ;
459       cout << "xsection " <<xsection<<" ntrials "<<ntrials<<endl; 
460     }
461     
462     xs =   xs /  nfiles;
463     ntr =  ntr / nfiles;
464     cout << "-----------------------------------------------------------------"<<endl;
465     cout << "Average of "<< nfiles<<" files: xsection " <<xs<<" ntrials "<<ntr<<endl; 
466     cout << "-----------------------------------------------------------------"<<endl;
467   } 
468   else cout << " >>>> Empty tree !!!! <<<<< "<<endl;
469   
470 }
471
472
473