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