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