]> git.uio.no Git - u/mrichter/AliRoot.git/blob - ANALYSIS/macros/AnalysisTrainNew.C
Added femtoscopy and kink analysis.
[u/mrichter/AliRoot.git] / ANALYSIS / macros / AnalysisTrainNew.C
1 //===================== ANALYSIS TRAIN ==========================================
2 // To use: copy this macro to your work directory, modify the global part to match
3 // your needs, then run root.
4 //    root[0] .L AnalysisTrain.C
5 // Grid full mode as below (other modes: test, offline, submit, terminate)
6 //    root[1] AnalysisTrainNew("grid", "full")
7 // CAF mode (requires root v5-23-02 + aliroot v4-16-Rev08)
8 //    root[2] AnalysisTrainNew("proof")
9 // Local mode requires AliESds.root or AliAOD.root in ./data directory
10 //    root[3] AnalysisTrainNew("local")
11 // In proof and grid modes, a token is needed and sourcing the produced environment file.
12
13 const char *root_version    = "v5-23-02";
14 const char *aliroot_version = "v4-17-00";
15 const char *cluster         = "alicecaf.cern.ch";
16 //const char *AFversion       = "AF-v4-16";
17 const char *AFversion       = "";
18 // Dataset name. If empty assumes local ESD/AOD. In CAF it is a dataset name.
19 //               In grid has to point to an xml file or be empty if using the plugin
20 // === PROOF
21 // Change CAF dataset here
22 const char *proof_dataset = "/COMMON/COMMON/LHC09a4_run8100X#/esdTree";
23
24 // === ALIEN
25 const char *dataset   = "";
26 // Change production base directory here
27 const char *alien_datadir = "/alice/sim/PDC_09/LHC09a4/";
28 // Use up to 10 non-zero run numbers
29 Int_t run_numbers[10] = {81272,     0,     0,     0,     0,
30                              0,     0,     0,     0,     0};
31 // Activate the following flags ONLY in grid mode and ONLY if the code is not available
32 // in the deployed AliRoot versions. Par file search path: local dir, if not there $ALICE_ROOT.
33 // To refresh par files, remove the ones in the workdir, then do "make <target.par>" in 
34 // AliRoot.
35 Bool_t usePAR        = kFALSE;  // use par files for extra libs
36 Bool_t useCPAR       = kFALSE;  // use par files for common libs
37 // Other flags to steer the analysis
38 Bool_t useDBG        = kTRUE;  // activate debugging
39 Bool_t useMC         = kTRUE;  // use MC info
40 Bool_t useTAGS       = kFALSE; // use ESD tags for selection
41 Bool_t useKFILTER    = kTRUE;  // use Kinematics filter
42 Bool_t useTR         = kFALSE; // use track references
43 Bool_t usePLUGIN     = kTRUE;  // use AliEn plugin
44 Bool_t useCORRFW     = kFALSE; // do not change
45 Bool_t useAODTAGS    = kFALSE; // use AOD tags
46     
47 Int_t iAODanalysis   = 0;      // Analysis on input AOD's
48 Int_t iAODhandler    = 1;      // Analysis produces an AOD or dAOD's
49 Int_t iESDfilter     = 1;      // ESD to AOD filter (barrel + muon tracks)
50 Int_t iMUONcopyAOD   = 0;      // Task that copies only muon events in a separate AOD (PWG3)
51 Int_t iJETAN         = 1;      // Jet analysis (PWG4) - needs ESD filter
52 Int_t iPWG4partcorr  = 1;      // Gamma-hadron correlations task (PWG4)
53 Int_t iPWG3vertexing = 1;      // Vertexing HF task (PWG2)
54 Int_t iPWG2femto     = 1;      // Femtoscopy task (PWG2)
55 Int_t iPWG2spectra   = 1;      // Spectra PWG2 tasks (protons, cascades, V0 check, strange)
56 Int_t iPWG2flow      = 0;      // Flow analysis task (PWG2)
57 Int_t iPWG2res       = 1;      // Resonances task (PWG2)
58 Int_t iPWG2kink      = 1;      // Kink analysis task (PWG2)
59
60 TString anaPars = "";
61 TString anaLibs = "";
62 // Function signatures
63 class AliAnalysisGrid;
64
65 //______________________________________________________________________________
66 void AnalysisTrainNew(const char *analysis_mode="grid", const char *plugin_mode="full")
67 {
68 // Example of running analysis train
69    TString smode(analysis_mode);
70    smode.ToUpper();    
71    // Check compatibility of selected modules
72    CheckModuleFlags(smode);
73
74    printf("==================================================================\n");
75    printf("===========    RUNNING ANALYSIS TRAIN IN %s MODE   ==========\n", smode.Data());
76    printf("==================================================================\n");
77    printf("=  Configuring analysis train for:                               =\n");
78    if (iAODanalysis) printf("=  AOD analysis                                                  =\n");
79    else              printf("=  ESD analysis                                                  =\n");
80    if (iESDfilter)   printf("=  ESD filter                                                    =\n");
81    if (iMUONcopyAOD) printf("=  MUON copy AOD                                                 =\n");
82    if (iJETAN)       printf("=  Jet analysis                                                  =\n");
83    if (iPWG2spectra) printf("=  PWG2 proton, checkCascade, checkV0, strange                   =\n");
84    if (iPWG2femto)   printf("=  PWG2 femtoscopy                                               =\n");
85    if (iPWG2flow)    printf("=  PWG2 flow                                                     =\n");
86    if (iPWG2res)     printf("=  PWG2 resonances                                               =\n");
87    if (iPWG2kink)    printf("=  PWG2 kink analysis                                            =\n");
88    if (iPWG3vertexing) printf("=  PWG3 vertexing                                            =\n");
89    if (iPWG4partcorr)  printf("=  PWG4 gamma-hadron, pi0 and gamma-jet correlations         =\n");
90    printf("==================================================================\n");
91    printf(":: use MC truth      %d\n", (UInt_t)useMC);
92    printf(":: use KINE filter   %d\n", (UInt_t)useKFILTER);
93    printf(":: use track refs    %d\n", (UInt_t)useTR);
94    printf(":: use tags          %d\n", (UInt_t)useTAGS);
95    printf(":: use AOD tags      %d\n", (UInt_t)useAODTAGS);
96    printf(":: use debugging     %d\n", (UInt_t)useDBG);
97    printf(":: use PAR files     %d\n", (UInt_t)usePAR);
98    printf(":: use AliEn plugin  %d\n", (UInt_t)usePLUGIN);
99
100    // Connect to back-end system
101    if (!Connect(smode)) {
102       ::Error("AnalysisTrain", "Could not connect to %s back-end", analysis_mode);
103       return;
104    }   
105
106    // Load common libraries and set include path
107    if (!LoadCommonLibraries(smode)) {
108       ::Error("AnalysisTrain", "Could not load common libraries");
109       return;
110    }   Int_t iPWG2res       = 0;      // Resonances task (PWG2)
111
112     
113    // Load analysis specific libraries
114    if (!LoadAnalysisLibraries(smode)) {
115       ::Error("AnalysisTrain", "Could not load analysis libraries");
116       return;
117    }   
118
119     
120    //==========================================================================
121    // Make the analysis manager and connect event handlers
122    AliAnalysisManager *mgr  = new AliAnalysisManager("Analysis Train", "Production train");
123
124    // Create input handler (input container created automatically)
125    if (iAODanalysis) {
126    // AOD input handler
127       AliAODInputHandler *aodH = new AliAODInputHandler();
128       mgr->SetInputEventHandler(aodH);
129    } else {   
130    // ESD input handler
131       AliESDInputHandler *esdHandler = new AliESDInputHandler();
132       if (useTAGS) esdHandler->SetReadTags();
133       mgr->SetInputEventHandler(esdHandler);       
134    }
135    // Monte Carlo handler
136    if (useMC && !iAODanalysis) {
137       AliMCEventHandler* mcHandler = new AliMCEventHandler();
138       mgr->SetMCtruthEventHandler(mcHandler);
139       mcHandler->SetReadTR(useTR); 
140    }   
141    // AOD output container, created automatically when setting an AOD handler
142    if (iAODhandler) {
143       // AOD output handler
144       AliAODHandler* aodHandler   = new AliAODHandler();
145       mgr->SetOutputEventHandler(aodHandler);
146       if (iAODanalysis) aodHandler->SetCreateNonStandardAOD();
147       if (iPWG3vertexing) aodHandler->SetOutputFileName("AliAOD.VertexingHF.root");
148       else aodHandler->SetOutputFileName("AliAOD.root");
149    }
150    // Debugging if needed
151    if (useDBG) mgr->SetDebugLevel(3);
152
153    //==========================================================================
154    // Create the chain. In this example it is created only from ALIEN files but
155    // can be done to work in batch or grid mode as well.
156    TChain *chain = CreateChain(smode, plugin_mode);
157         
158    //==========================================================================
159    // Load the tasks configuration macros for all wagons. These files are supposed now to be
160    // in the current workdir, but in AliEn they will be in the file catalog, 
161    // mapped from AliRoot and pecified in the jdl input list.
162     
163    // For now connection to top input container and common AOD output container
164    // is done in this macro, but in future these containers will be connected
165    // from each task configuration macro.
166
167    if (iESDfilter && !iAODanalysis) {
168       //  ESD filter task configuration.
169       gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskESDFilter.C");
170       AliAnalysisTaskESDfilter *taskesdfilter = AddTaskESDFilter(useKFILTER);
171    }   
172
173    // AOD tags
174    if (useAODTAGS) {
175       AliAnalysisTaskTagCreator* tagTask = new AliAnalysisTaskTagCreator("AOD Tag Creator");
176       mgr->AddTask(tagTask);
177       AliAnalysisDataContainer *coutTags = mgr->CreateContainer("cTag",  TTree::Class(), 
178                                            AliAnalysisManager::kOutputContainer, "AOD.tag.root");
179       mgr->ConnectInput (tagTask, 0, mgr->GetCommonInputContainer());
180       mgr->ConnectOutput(tagTask, 1, coutTags);
181    }   
182     
183     // Jet analysis
184    if (iJETAN) {
185       gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJets.C");
186       AliAnalysisTaskJets *taskjets = AddTaskJets("AOD", "UA1");
187       if (!taskjets) ::Warning("AnalysisTrainNew", "AliAnalysisTaskJets cannot run for this train conditions - EXCLUDED");
188    }
189        
190    // Proton analysis
191    if (iPWG2spectra) {
192       // protons
193       gROOT->LoadMacro("$ALICE_ROOT/PWG2/SPECTRA/macros/AddTaskProtons.C");
194       AliAnalysisTaskProtons *taskprotons = AddTaskProtons();
195       if (!taskprotons) ::Warning("AnalysisTrainNew", "AliAnalysisTaskProtons cannot run for this train conditions - EXCLUDED");
196       // cascades
197       gROOT->LoadMacro("$ALICE_ROOT/PWG2/SPECTRA/macros/AddTaskCheckCascade.C");
198       AliAnalysisTaskCheckCascade *taskcheckcascade = AddTaskCheckCascade();      
199       if (!taskcheckcascade) ::Warning("AnalysisTrainNew", "AliAnalysisTaskCheckCascade cannot run for this train conditions - EXCLUDED");
200       // v0's
201       gROOT->LoadMacro("$ALICE_ROOT/PWG2/SPECTRA/macros/AddTaskCheckV0.C");
202       AliAnalysisTaskCheckV0 *taskcheckV0 = AddTaskCheckV0();
203       if (!taskcheckV0) ::Warning("AnalysisTrainNew", "AliAnalysisTaskCheckV0 cannot run for this train conditions - EXCLUDED");
204       // strangeness
205       gROOT->LoadMacro("$ALICE_ROOT/PWG2/SPECTRA/macros/AddTaskStrange.C");
206       AliAnalysisTaskStrange *taskstrange = AddTaskStrange();
207       if (!taskstrange) ::Warning("AnalysisTrainNew", "AliAnalysisTaskStrange cannot run for this train conditions - EXCLUDED");
208    }   
209    
210    // Femtoscopy analysis modules
211    if (iPWG2femto) {
212       gROOT->LoadMacro("$ALICE_ROOT/PWG2/FEMTOSCOPY/macros/AddTaskFemto.C");
213       AliAnalysisTaskFemto *taskfemto = AddTaskFemto();
214       if (!taskfemto) ::Warning("AnalysisTrainNew", "AliAnalysisTaskFemto cannot run for this train conditions - EXCLUDED");
215    }   
216
217    // Kink analysis
218    if (iPWG2kink) {
219       gROOT->LoadMacro("$ALICE_ROOT/PWG2/KINK/macros/AddTaskKink.C");
220       AliAnalysisKinkESDMC *taskkink = AddTaskKink();
221       if (!taskkink) ::Warning("AnalysisTrainNew", "AliAnalysisKinkESDMC cannot run for this train conditions - EXCLUDED");
222       gROOT->LoadMacro("$ALICE_ROOT/PWG2/KINK/macros/AddTaskKinkResonance.C");
223       AliResonanceKinkPID *taskkinkres = AddTaskKinkResonance();
224       if (!taskkinkres) ::Warning("AnalysisTrainNew", "AliResonanceKinkPID cannot run for this train conditions - EXCLUDED");
225       gROOT->LoadMacro("$ALICE_ROOT/PWG2/KINK/macros/AddTaskKinkResonanceLikeSign.C");
226       AliResonanceKinkLikeSign *taskkinklikesign = AddTaskKinkResonanceLikeSign();
227       if (!taskkinklikesign) ::Warning("AnalysisTrainNew", "AliResonanceKinkLikeSign cannot run for this train conditions - EXCLUDED");
228    }   
229       
230   // PWG3 vertexing
231    if (iPWG3vertexing) {
232       gROOT->LoadMacro("$ALICE_ROOT/PWG3/vertexingHF/AddTaskVertexingHF.C");
233       AliAnalysisTaskSEVertexingHF *taskvertexingHF = AddTaskVertexingHF();
234       if (!taskvertexingHF) ::Warning("AnalysisTrainNew", "AliAnalysisTaskSEVertexingHF cannot run for this train conditions - EXCLUDED");
235    }   
236       
237    // PWG4 hadron correlations
238    if (iPWG4partcorr) {
239       gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskPartCorr.C");
240       AliAnalysisTaskParticleCorrelation *taskpartcorrPHOS = AddTaskPartCorr("AOD", "PHOS");
241       if (!taskpartcorrPHOS) ::Warning("AnalysisTrainNew", "AliAnalysisTaskParticleCorrelation PHOS cannot run for this train conditions - EXCLUDED");
242       AliAnalysisTaskParticleCorrelation *taskpartcorrEMCAL = AddTaskPartCorr("AOD", "EMCAL");
243       if (!taskpartcorrEMCAL) ::Warning("AnalysisTrainNew", "AliAnalysisTaskParticleCorrelation EMCAL cannot run for this train conditions - EXCLUDED");
244    }   
245    //==========================================================================
246    // FOR THE REST OF THE TASKS THE MACRO AddTaskXXX() is not yet implemented/
247    // Run the analysis
248    //    
249    if (mgr->InitAnalysis()) {
250       mgr->PrintStatus();
251       StartAnalysis(smode, chain);
252    }   
253 }
254
255 //______________________________________________________________________________
256 void StartAnalysis(const char *mode, TChain *chain) {
257 // Start analysis.
258    Int_t imode = -1;
259    AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
260    if (!strcmp(mode, "LOCAL")) imode = 0;
261    if (!strcmp(mode, "PROOF")) imode = 1;
262    if (!strcmp(mode, "GRID"))  imode = 2;
263    switch (imode) {
264       case 0:
265          if (!chain) {
266             ::Error("StartAnalysis", "Cannot create the chain");
267             return;
268          }   
269          mgr->StartAnalysis(mode, chain);
270          return;
271       case 1:
272          if (!strlen(proof_dataset)) {
273             ::Error("StartAnalysis", "proof_dataset is empty");
274             return;
275          }   
276          mgr->StartAnalysis(mode, proof_dataset, 100000);
277          return;
278       case 2:
279          if (usePLUGIN) {
280             if (!mgr->GetGridHandler()) {
281                ::Error("StartAnalysis", "Grid plugin not initialized");
282                return;
283             }   
284             mgr->StartAnalysis("grid");
285          } else {
286             if (!chain) {
287                ::Error("StartAnalysis", "Cannot create the chain");
288                return;
289             }   
290             mgr->StartAnalysis(mode, chain);
291          }   
292          return;
293    }      
294 }          
295     
296 //______________________________________________________________________________
297 void CheckModuleFlags(const char *mode) {
298 // Checks selected modules and insure compatibility
299    Int_t imode = -1;
300    if (!strcmp(mode, "LOCAL")) imode = 0;
301    if (!strcmp(mode, "PROOF")) imode = 1;
302    if (!strcmp(mode, "GRID"))  imode = 2;
303    if (imode==1) {
304       if (!usePAR) {
305          ::Info("CheckModuleFlags", "PAR files enabled due to PROOF analysis");
306          usePAR = kTRUE;
307       }   
308    }  
309    if (imode != 2) {
310       ::Info("CheckModuleFlags", "AliEn plugin disabled since not in GRID mode");
311       usePLUGIN = kFALSE; 
312    }   
313    if (iAODanalysis) {
314    // AOD analysis
315       if (useMC)
316          ::Info("CheckModuleFlags", "MC usage disabled in analysis on AOD's");
317       useMC = kFALSE;
318       useTR = kFALSE;
319       if (iESDfilter)
320          ::Info("CheckModuleFlags", "ESD filter disabled in analysis on AOD's");
321       iESDfilter   = 0;
322       if (!iAODhandler) {
323          if (iJETAN) 
324             ::Info("CheckModuleFlags", "JETAN disabled in analysis on AOD's without AOD handler");
325          iJETAN = 0;
326       }
327       // Disable tasks that do not work yet on AOD data
328       if (iPWG2kink)         
329          ::Info("CheckModuleFlags", "PWG2kink disabled in analysis on AOD's");
330       iPWG2kink = 0;
331    } else {   
332    // ESD analysis
333       iMUONcopyAOD = 0;
334    }       
335    if (iJETAN) iESDfilter=1;
336    if (iESDfilter) iAODhandler=1;
337    if (iPWG2spectra || iPWG2flow || iPWG3vertexing) useCORRFW = kTRUE;
338    if (useKFILTER && !useMC) useKFILTER = kFALSE;
339    if (useAODTAGS && !iAODhandler) useAODTAGS = kFALSE;
340 }
341
342 //______________________________________________________________________________
343 Bool_t Connect(const char *mode) {
344 // Connect <username> to the back-end system.
345    Int_t imode = -1;
346    if (!strcmp(mode, "LOCAL")) imode = 0;
347    if (!strcmp(mode, "PROOF")) imode = 1;
348    if (!strcmp(mode, "GRID"))  imode = 2;
349    TString username = gSystem->Getenv("alien_API_USER");
350    switch (imode) {
351       case 0:
352          break;
353       case 1:
354          if  (!username.Length()) {
355             ::Error(Form("Connect <%s>", mode), "Make sure you:\n \
356                            1. Have called: alien-token-init <username>\n \
357                            2. Have called: >source /tmp/gclient_env_$UID");
358             return kFALSE;
359          }
360          ::Info("Connect", "Connecting user <%s> to PROOF cluster <%s>", 
361                 username.Data(), cluster);
362          TProof::Open(Form("%s@%s", username.Data(), cluster));       
363          if (!gProof) {
364             if (strcmp(gSystem->Getenv("XrdSecGSISRVNAMES"), "lxfsrd0506.cern.ch"))
365                ::Error(Form("Connect <%s>", mode), "Environment XrdSecGSISRVNAMES different from lxfsrd0506.cern.ch");
366             return kFALSE;
367          }
368          break;
369       case 2:      
370          if  (!username.Length()) {
371             ::Error(Form("Connect <%s>", mode), "Make sure you:\n \
372                            1. Have called: alien-token-init <username>\n \
373                            2. Have called: >source /tmp/gclient_env_$UID");
374             return kFALSE;
375          }
376          if (usePLUGIN && !gSystem->Getenv("alien_CLOSE_SE")) {
377             ::Error(Form("Connect <%s>", mode), 
378                            "When using the AliEn plugin it is preferable to define the \
379                            variable alien_CLOSE_SE in your environment.");
380             return kFALSE;
381          }
382          ::Info("Connect", "Connecting user <%s> to AliEn ...", 
383                 username.Data());
384          TGrid::Connect("alien://");
385          if (!gGrid || !gGrid->IsConnected()) return kFALSE;
386          break;
387       default:
388          ::Error("Connect", "Unknown run mode: %s", mode);
389          return kFALSE;
390    }
391    ::Info("Connect","Connected in %s mode", mode);
392    return kTRUE;
393 }
394
395 //______________________________________________________________________________
396 Bool_t LoadCommonLibraries(const char *mode)
397 {
398 // Load common analysis libraries.
399    Int_t imode = -1;
400    if (!strcmp(mode, "LOCAL")) imode = 0;
401    if (!strcmp(mode, "PROOF")) imode = 1;
402    if (!strcmp(mode, "GRID"))  imode = 2;
403    if (!gSystem->Getenv("ALICE_ROOT")) {
404       ::Error("LoadCommonLibraries", "Analysis train requires that analysis libraries are compiled with a local AliRoot"); 
405       return kFALSE;
406    }   
407    Bool_t success = kTRUE;
408    // ROOT libraries
409    gSystem->Load("libTree.so");
410    gSystem->Load("libGeom.so");
411    gSystem->Load("libVMC.so");
412    gSystem->Load("libPhysics.so");
413    
414    // Load framework classes. Par option ignored here.
415    switch (imode) {
416       case 0:
417       case 2:
418          if (useCPAR) {
419             success &= LoadLibrary("STEERBase", mode, kTRUE);
420             success &= LoadLibrary("ESD", mode, kTRUE);
421             success &= LoadLibrary("AOD", mode, kTRUE);
422             success &= LoadLibrary("ANALYSIS", mode, kTRUE);
423             success &= LoadLibrary("ANALYSISalice", mode, kTRUE);
424             if (useCORRFW) success &= LoadLibrary("CORRFW", mode, kTRUE);
425          } else {   
426             success &= LoadLibrary("libSTEERBase.so", mode);
427             success &= LoadLibrary("libESD.so", mode);
428             success &= LoadLibrary("libAOD.so", mode);
429             success &= LoadLibrary("libANALYSIS.so", mode);
430             success &= LoadLibrary("libANALYSISalice.so", mode);
431             if (useCORRFW) success &= LoadLibrary("libCORRFW.so", mode);
432             gROOT->ProcessLine(".include $ALICE_ROOT/include");
433          }   
434          break;
435       case 1:
436          Int_t ires = -1;
437          if (!gSystem->AccessPathName(AFversion)) ires = gProof->UploadPackage(AFversion);
438          if (ires < 0) {
439             success &= LoadLibrary("STEERBase", mode);
440             success &= LoadLibrary("ESD", mode);
441             success &= LoadLibrary("AOD", mode);
442             success &= LoadLibrary("ANALYSIS", mode);
443             success &= LoadLibrary("ANALYSISalice", mode);
444             if (useCORRFW) success &= LoadLibrary("CORRFW", mode);
445          } else { 
446             ires = gProof->EnablePackage(AFversion);
447             if (ires<0) success = kFALSE;
448             if (useCORRFW) success &= LoadLibrary("CORRFW", mode);
449          }
450          break;         
451       default:
452          ::Error("LoadCommonLibraries", "Unknown run mode: %s", mode);
453          return kFALSE;
454    }
455    if (success) {
456       ::Info("LoadCommodLibraries", "Load common libraries:    SUCCESS");
457       ::Info("LoadCommodLibraries", "Include path for Aclic compilation:\n%s",
458               gSystem->GetIncludePath());
459    } else {           
460       ::Info("LoadCommodLibraries", "Load common libraries:    FAILED");
461    }   
462       
463    return success;
464 }
465
466 //______________________________________________________________________________
467 Bool_t LoadAnalysisLibraries(const char *mode)
468 {
469 // Load common analysis libraries.
470    Bool_t success = kTRUE;
471    if (iESDfilter) {
472       if (!LoadLibrary("PWG3base", mode, kTRUE) ||
473           !LoadLibrary("PWG3muon", mode, kTRUE)) return kFALSE;
474    }   
475    // JETAN
476    if (iJETAN) {
477       if (!LoadLibrary("JETAN", mode, kTRUE)) return kFALSE;
478    }   
479             
480    // PWG4 particle correlations
481    if (iPWG4partcorr) {   
482       if (!LoadLibrary("PWG4PartCorrBase", mode, kTRUE) ||
483           !LoadLibrary("PWG4PartCorrDep", mode, kTRUE)) return kFALSE;
484 //      TFile::Cp(gSystem->ExpandPathName("$(ALICE_ROOT)/PWG4/macros/ConfigAnalysisGammaHadronCorrelation.C"), "ConfigAnalysisGammaHadronCorrelation.C");
485 //      TFile::Cp(gSystem->ExpandPathName("$(ALICE_ROOT)/PWG4/macros/ConfigAnalysisPi0.C"), "ConfigAnalysisPi0.C");
486    }
487    // PWG2 task protons 
488    if (iPWG2spectra) {
489       if (!LoadLibrary("PWG2spectra", mode, kTRUE)) return kFALSE;
490    }
491    // PWG2 flow
492    if (iPWG2flow) {
493       if (!LoadLibrary("PWG2AOD", mode, kTRUE) ||
494           !LoadLibrary("PWG2flow", mode, kTRUE)) return kFALSE;
495    }
496    // PWG2 resonances
497    if (iPWG2res) {
498       if (!LoadLibrary("PWG2resonances", mode, kTRUE)) return kFALSE;
499    }   
500    // PWG2 kink
501    if (iPWG2kink) {
502       if (!LoadLibrary("PWG2kink", mode, kTRUE)) return kFALSE;
503    }   
504    // PWG2 femtoscopy
505    if (iPWG2femto) {
506       if (!LoadLibrary("PWG2AOD", mode, kTRUE) ||
507           !LoadLibrary("PWG2femtoscopy", mode, kTRUE) ||
508           !LoadLibrary("PWG2femtoscopyUser", mode, kTRUE)) return kFALSE;
509       TFile::Cp(gSystem->ExpandPathName("$(ALICE_ROOT)/PWG2/FEMTOSCOPY/macros/ConfigFemtoAnalysis.C"), "ConfigFemtoAnalysis.C");
510    }   
511    // Vertexing HF
512    if (iPWG3vertexing) {
513       if (!LoadLibrary("PWG3base", mode, kTRUE) ||
514           !LoadLibrary("PWG3vertexingHF", mode, kTRUE)) return kFALSE;
515    }   
516    ::Info("LoadAnalysisLibraries", "Load other libraries:   SUCCESS");
517    return kTRUE;
518 }
519
520 //______________________________________________________________________________
521 Bool_t LoadLibrary(const char *module, const char *mode, Bool_t rec=kFALSE)
522 {
523 // Load a module library in a given mode. Reports success.
524    Int_t imode = -1;
525    Int_t result;
526    TString smodule(module);
527    if (!strcmp(mode, "LOCAL")) imode = 0;
528    if (!strcmp(mode, "PROOF")) imode = 1;
529    if (!strcmp(mode, "GRID"))  imode = 2;
530    TString mod(module);
531    if (!mod.Length()) {
532       ::Error("LoadLibrary", "Empty module name");
533       return kFALSE;
534    }   
535    // If a library is specified, just load it
536    if (smodule.EndsWith(".so")) {
537       mod.Remove(mod.Index(".so"));
538       result = gSystem->Load(mod);
539       if (result < 0) {
540          ::Error("LoadLibrary", "Could not load library %s", module);
541          return kFALSE;
542       }
543       if (rec) anaLibs += Form("%s.so ",mod.Data()); 
544       return kTRUE;
545    } 
546    // Check if the library is already loaded
547    if (strlen(gSystem->GetLibraries(Form("%s.so", module), "", kFALSE)) > 0)
548       return kTRUE;    
549    switch (imode) {
550       case 0:
551       case 2:
552          if (usePAR) {
553             result = SetupPar(module);
554             if (rec) anaPars += Form("%s.par ", module);
555          } else {
556             result = gSystem->Load(Form("lib%s.so", module));
557             if (rec) anaLibs += Form("lib%s.so ", module);
558          }   
559          break;
560       case 1:
561          result = gProof->UploadPackage(module);
562          if (result<0) {
563             result = gProof->UploadPackage(gSystem->ExpandPathName(Form("$ALICE_ROOT/%s.par", module)));
564             if (result<0) {
565                ::Error("LoadLibrary", "Could not find module %s.par in current directory nor in $ALICE_ROOT", module);
566                return kFALSE;
567             }
568          }   
569          result = gProof->EnablePackage(module);
570          break;
571       default:
572          return kFALSE;
573    }         
574    if (result < 0) {
575       ::Error("LoadLibrary", "Could not load module %s", module);
576       return kFALSE;
577    }
578    return kTRUE;
579 }           
580
581
582 //______________________________________________________________________________
583 TChain *CreateChain(const char *mode, const char *plugin_mode)
584 {
585 // Create the input chain
586    Int_t imode = -1;
587    if (!strcmp(mode, "LOCAL")) imode = 0;
588    if (!strcmp(mode, "PROOF")) imode = 1;
589    if (!strcmp(mode, "GRID"))  imode = 2;
590    TChain *chain = NULL;
591    // Local chain
592    switch (imode) {
593       case 0:
594          if (iAODanalysis) {
595             if (!strlen(dataset)) {
596                // Local AOD
597                chain = new TChain("aodTree");
598                if (gSystem->AccessPathName("data/AliAOD.root")) 
599                   ::Error("CreateChain", "File: AliAOD.root not in ./data dir");
600                else chain->Add("data/AliAOD.root");
601             } else {
602                // Interactive AOD
603                chain = CreateChainSingle(dataset, "aodTree");
604             }
605          } else {      
606             if (!strlen(dataset)) {
607                // Local ESD
608                chain = new TChain("esdTree");
609                if (gSystem->AccessPathName("data/AliESDs.root")) 
610                   ::Error("CreateChain", "File: AliESDs.root not in ./data dir");
611                else chain->Add("data/AliESDs.root");
612             } else {
613                // Interactive ESD
614                chain = CreateChainSingle(dataset, "esdTree");
615             }   
616          }
617          break;
618       case 1:
619          break;
620       case 2:
621          if (usePLUGIN) {
622             AliAnalysisGrid *alienHandler = CreateAlienHandler(plugin_mode);
623             AliAnalysisManager::GetAnalysisManager()->SetGridHandler(alienHandler);
624          } else {
625             TString           treeName = "esdTree";
626             if (iAODanalysis) treeName = "aodTree";
627             chain = CreateChainSingle("wn.xml", treeName);
628          }
629          break;      
630       default:   
631    }
632    if (chain && chain->GetNtrees()) return chain;
633    return NULL;
634 }   
635
636 //______________________________________________________________________________
637 TChain* CreateChainSingle(const char* xmlfile, const char *treeName)
638 {
639    printf("*******************************\n");
640    printf("*** Getting the ESD Chain   ***\n");
641    printf("*******************************\n");
642    TAlienCollection * myCollection  = TAlienCollection::Open(xmlfile);
643
644    if (!myCollection) {
645       ::Error("CreateChainSingle", "Cannot create an AliEn collection from %s", xmlfile) ;
646       return NULL ;
647    }
648
649    TChain* chain = new TChain(treeName);
650    myCollection->Reset() ;
651    while ( myCollection->Next() ) chain->Add(myCollection->GetTURL("")) ;
652    chain->ls();
653    return chain;
654 }
655
656 //______________________________________________________________________________
657 Int_t SetupPar(char* pararchivename)
658 {
659    if (!pararchivename || !strlen(pararchivename)) return -1;
660    char processline[1024];
661    if (gSystem->AccessPathName(Form("%s.par", pararchivename))) {
662       if (!gSystem->AccessPathName(Form("%s/%s.par", gSystem->Getenv("ALICE_ROOT"),pararchivename))) {
663          ::Info("SetupPar", "Getting %s.par from $ALICE_ROOT", pararchivename);
664          TFile::Cp(gSystem->ExpandPathName(Form("$ALICE_ROOT/%s.par", pararchivename)), 
665                    Form("%s.par",pararchivename));
666       } else {
667          ::Error("SetupPar", "Cannot find %s.par", pararchivename);
668          return -1;
669       }   
670    }
671    gSystem->Exec(Form("tar xvzf %s.par", pararchivename));
672
673    TString ocwd = gSystem->WorkingDirectory();
674    if (!gSystem->ChangeDirectory(pararchivename)) return -1;
675         
676    // check for BUILD.sh and execute
677    if (!gSystem->AccessPathName("PROOF-INF/BUILD.sh")) {
678       printf("*******************************\n");
679       printf("*** Building PAR archive    ***\n");
680       printf("*******************************\n");          
681       if (gSystem->Exec("PROOF-INF/BUILD.sh")) {
682          Error("runProcess","Cannot Build the PAR Archive! - Abort!");
683          return -1;
684       }
685    }
686
687         // check for SETUP.C and execute
688         if (!gSystem->AccessPathName("PROOF-INF/SETUP.C")) {
689             printf("*******************************\n");
690             printf("*** Setup PAR archive       ***\n");
691             printf("*******************************\n");
692             gROOT->Macro("PROOF-INF/SETUP.C");
693         }       
694         if (!gSystem->ChangeDirectory(ocwd.Data())) return -1;
695    return 0;
696 }
697
698 //______________________________________________________________________________
699 AliAnalysisGrid* CreateAlienHandler(const char *plugin_mode)
700 {
701 // Check if user has a valid token, otherwise make one. This has limitations.
702 // One can always follow the standard procedure of calling alien-token-init then
703 //   source /tmp/gclient_env_$UID in the current shell.
704    if (!AliAnalysisGrid::CreateToken()) return NULL;
705    AliAnalysisAlien *plugin = new AliAnalysisAlien();
706 // Set the run mode (can be "full", "test", "offline", "submit" or "terminate")
707    plugin->SetRunMode(plugin_mode);
708    plugin->SetNtestFiles(1);
709 //   plugin->SetPreferedSE("ALICE::NIHAM::FILE");
710 // Set versions of used packages
711    plugin->SetAPIVersion("V2.4");
712    plugin->SetROOTVersion(root_version);
713    plugin->SetAliROOTVersion(aliroot_version);
714 // Declare input data to be processed.
715 // Method 1: Create automatically XML collections using alien 'find' command.
716 // Define production directory LFN
717    plugin->SetGridDataDir(alien_datadir);
718 // Set data search pattern
719    if (iAODanalysis) plugin->SetDataPattern("*AliAOD.root");
720    else              plugin->SetDataPattern("*AliESDs.root");
721 // ...then add run numbers to be considered
722    for (Int_t i=0; i<10; i++) {
723       if (run_numbers[i]==0) break;
724       plugin->AddRunNumber(run_numbers[i]);
725    }   
726 // Method 2: Declare existing data files (raw collections, xml collections, root file)
727 // If no path mentioned data is supposed to be in the work directory (see SetGridWorkingDir())
728 // XML collections added via this method can be combined with the first method if
729 // the content is compatible (using or not tags)
730 //   plugin->AddDataFile("tag.xml");
731 //   plugin->AddDataFile("/alice/data/2008/LHC08c/000057657/raw/Run57657.Merged.RAW.tag.root");
732 // Define alien work directory where all files will be copied. Relative to alien $HOME.
733    if (iAODanalysis) plugin->SetGridWorkingDir("analysisAOD");
734    else              plugin->SetGridWorkingDir("analysisESD");
735 // Declare alien output directory. Relative to working directory.
736    plugin->SetGridOutputDir("output"); // In this case will be $HOME/work/output
737
738    TString ana_sources = "";
739    TString ana_add = "";
740    if (usePAR && anaPars.Length()) {
741       printf("%s\n", anaPars.Data());
742       TObjArray *arr;
743       TObjString *objstr;
744       arr = anaPars.Tokenize(" ");
745       TIter next(arr);
746       while ((objstr=(TObjString*)next())) plugin->EnablePackage(objstr->GetString());
747       delete arr;
748    } 
749    
750 // Declare the analysis source files names separated by blancs. To be compiled runtime
751 // using ACLiC on the worker nodes.
752    ana_sources = ana_sources.Strip();
753 // Declare all libraries (other than the default ones for the framework. These will be
754 // loaded by the generated analysis macro. Add all extra files (task .cxx/.h) here.
755    anaLibs     = anaLibs.Strip();   
756    if (ana_sources.Length()) plugin->SetAnalysisSource(ana_sources);
757    if (anaLibs.Length())     plugin->SetAdditionalLibs(anaLibs);
758      
759 // Declare the output file names separated by blancs.
760 // (can be like: file.root or file.root@ALICE::Niham::File)
761    plugin->SetDefaultOutputs();
762    plugin->SetMergeExcludes("AliAOD.root");
763 //   plugin->SetOutputFiles("AliAOD.root");
764 // Optionally define the files to be archived.
765 //   plugin->SetOutputArchive("log_archive.zip:stdout,stderr@ALICE::NIHAM::File root_archive.zip:*.root@ALICE::NIHAM::File");
766    plugin->SetOutputArchive("log_archive.zip:stdout,stderr");
767 // Optionally set a name for the generated analysis macro (default MyAnalysis.C)
768    plugin->SetAnalysisMacro("AnalysisTrainGrid.C");
769 // Optionally set maximum number of input files/subjob (default 100, put 0 to ignore)
770    plugin->SetSplitMaxInputFileNumber(50);
771 // Optionally set number of failed jobs that will trigger killing waiting sub-jobs.
772 //   plugin->SetMaxInitFailed(5);
773 // Optionally resubmit threshold.
774 //   plugin->SetMasterResubmitThreshold(90);
775 // Optionally set time to live (default 30000 sec)
776    plugin->SetTTL(30000);
777 // Optionally set input format (default xml-single)
778    plugin->SetInputFormat("xml-single");
779 // Optionally modify the name of the generated JDL (default analysis.jdl)
780    plugin->SetJDLName("AnalysisTrain.jdl");
781 // Optionally modify the executable name (default analysis.sh)
782    plugin->SetExecutable("AnalysisTrain.sh");
783 // Optionally modify job price (default 1)
784    plugin->SetPrice(1);      
785 // Optionally modify split mode (default 'se')    
786    plugin->SetSplitMode("se");
787    return plugin;
788 }