]> git.uio.no Git - u/mrichter/AliRoot.git/blob - PWG4/macros/AnalysisTrainPWG4Jets.C
05596fc17e50538db68820a2c18617a41d9c999a
[u/mrichter/AliRoot.git] / PWG4 / macros / AnalysisTrainPWG4Jets.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] AnalysisTrainPWG-244Jets("grid", "full")
7 // CAF mode (requires root v5-23-02 + aliroot v4-16-Rev08)
8 //    root[2] AnalysisTrainPWG4Jets("proof")
9 // Local mode requires AliESds.root or AliAOD.root in ./data directory
10 //    root[3] AnalysisTrainPWG4Jets("local")
11 // In proof and grid modes, a token is needed and sourcing the produced environment file.
12 //
13 // If 'saveTrain' flag is set, the train will generate a directory name and run
14 // in this directory. A configuration file 'ConfigTrain.C' will be generated. 
15 // One can replay at any time the train via:
16 //    root[1] AnalysisTrainPWG4Jets(ana_mode, plugin_mode, "train_default_<date>/ConfigTrain.C")
17
18 // For Usage with fastjet run in "offline" first and then "submit"
19 // jdl and analysismacro are automatically patched after "offline" mode
20
21 // =============================================================================
22 // ### General Steering variables
23 // =============================================================================
24 //== general setup variables
25 TString     kTrainName         = "testAnalysis"; // *CHANGE ME* (no blancs or special characters)
26 TString     kJobTag            = "PWG4 Jet Tasks analysis train configured"; // *CHANGE ME*
27
28 // Usage of par files ONLY in grid mode and ONLY if the code is not available
29 // in the deployed AliRoot versions. Par file search path: local dir, if not there $ALICE_ROOT.
30 // To refresh par files, remove the ones in the workdir, then do "make <target.par>" in 
31 // AliRoot.
32 Bool_t      kUsePAR             = kFALSE;  // use par files for extra libs
33 Bool_t      kUseCPAR            = kFALSE;  // use par files for common libs
34 Bool_t      kFillAOD = kFALSE;  // switch of AOD filling for on the fly analysis
35
36 //== general input and output variables
37 Int_t       iAODanalysis       = 1;      // Analysis on input AOD's
38 Int_t       iAODhandler        = 1;      // Analysis produces an AOD or dAOD's
39 Int_t       iESDfilter         = 0;      // ESD to AOD filter (barrel + muon tracks)
40 Int_t       iPhysicsSelection  = 1;      // ESD to AOD filter (barrel + muon tracks)
41 Bool_t      kUseKinefilter     = kFALSE; // use Kinematics filter
42 Bool_t      kUseMuonfilter     = kFALSE; // use Kinematics filter
43 TString     kCommonOutputFileName = "PWG4_JetTasksOutput.root";
44
45
46 //== general process variables
47
48 // ### Other flags to steer the analysis
49 //==============================================================================
50 Bool_t      kUseDate            = kFALSE; // use date in train name
51 Bool_t      kUseDebug           = kTRUE; // activate debugging
52 Int_t       kUseSysInfo         = 0; // activate debugging
53 Bool_t      kUseMC              = kTRUE;  // use MC info
54 Bool_t      kIsMC               = kTRUE;  // is MC info, if false it overwrites Use(AOD)MC
55 Bool_t      kUseAODMC           = kTRUE;  // use MC infA
56 Bool_t      kUseESDTags         = kFALSE; // use ESD tags for selection
57 Bool_t      kUseTR              = kFALSE;  // use track references
58 Bool_t      kUseAODTags         = kFALSE;  // use AOD tags
59 Bool_t      kSaveTrain          = kFALSE;  // save train configuration as: 
60
61 // ### Analysis modules to be included. Some may not be yet fully implemented.
62 //==============================================================================
63 Int_t       iJETAN             = 1;      // Jet analysis (PWG4) // 1 write standard 2 write non-standard jets, 3 wrtie both
64 Int_t       iDIJETAN           = 1;
65 Int_t       iJETANLib          = 1;
66 Int_t       iPWG1QASym         = 0;      // Eva's QA task compiled on the fly...
67 Int_t       iPWG4JetTasks      = 0;      // all jet tasks flag for lib laoding
68 Int_t       iPWG4JetServices   = 0;      // jet spectrum analysis
69 Int_t       iPWG4JetSpectrum   = 0;      // jet spectrum analysis
70 Int_t       iPWG4UE            = 0;      // Underlying Event analysis
71 Int_t       iPWG4TmpSourceSara = 0;      // Underlying Event analysis
72 Int_t       iPWG4PtQAMC        = 0;      // Marta's QA tasks 
73 Int_t       iPWG4PtSpectra     = 0;      // Marta's QA tasks 
74 Int_t       iPWG4PtQATPC       = 0;      // Marta's QA tasks 
75 Int_t       iPWG4ThreeJets     = 0;      // Sona's thrust task
76 Int_t       iPWG4KMeans        = 0;      // Andreas' KMeans task 
77 Int_t       iPWG4Cluster       = 0;      // CKB cluster task 
78 Int_t       iPWG4PartCorrLibs  = 0;      // Gustavo's part corr analysis
79 Int_t       iPWG4PartCorr      = 0;      // Gustavo's part corr analysis
80 Int_t       iPWG4CaloQA        = 0;      // Gustavo's part corr analysis
81 Int_t       iPWG4JetCorr       = 0;     // Paul's jet corr analysis
82 Int_t       iPWG4Tagged        = 0;      // Gustavo's part corr analysis
83 Int_t       iPWG4omega3pi      = 0;      // Omega to 3 pi analysis (PWG4) 
84 Int_t       iPWG4GammaConv     = 0;      // Gamma Conversio
85 Int_t       kHighPtFilterMask  = 16;     // change depending on the used AOD Filter
86 TString     kDeltaAODJetName   = "AliAOD.Jets.root";     
87 TString     kDeltaAODPartCorrName   = "deltaAODPartCorr.root";     
88
89
90 //==============================================================================
91 // ### PROOF Steering varibales
92 //==============================================================================
93 //== proof setup variables
94 TString     kProofCluster      = "alicecaf.cern.ch";
95 Bool_t      kProofUseAFPAR     = kFALSE;  // use AF special par file
96 TString     kProofAFversion          = "AF-v4-17";
97 //== proof input and output variables
98 TString     kProofDataSet      = "/COMMON/COMMON/LHC09a4_run8100X#/esdTree";
99 Bool_t      kProofSaveToAlien   = kFALSE; // save proof outputs in AliEn train_[trainName]_ddMonthyyyy_time.C
100 TString     kProofOutdir       = "";
101 Bool_t      kProofClearPackages = kFALSE;
102 Int_t       kProofEvents = 10000;
103 Int_t       kProofOffset = 0;
104 //== proof process variables
105
106
107 //==============================================================================
108 // ### Grid plugin Steering varibiables
109 //==============================================================================
110 //== grid plugin setup variables
111 Bool_t      kPluginUse         = kTRUE;   // do not change
112 Bool_t      kPluginUseProductionMode  = kFALSE;   // use the plugin in production mode
113 TString     kPluginRootVersion       = "v5-25-04-3";  // *CHANGE ME IF MORE RECENT IN GRID*
114 TString     kPluginAliRootVersion    = "v4-18-15-AN";  // *CHANGE ME IF MORE RECENT IN GRID*                                          
115 // TString kPluginExecutableCommand = "root -b -q";
116 TString     kPluginExecutableCommand = "source /Users/kleinb/setup_32bit_aliroot_trunk_clean_root_trunk.sh; alienroot -b -q ";
117 // == grid plugin input and output variables
118 TString     kGridDatadir      = "/alice/sim/PDC_08b/LHC09a1/AOD/";
119 TString     kGridLocalRunList = "";
120 TString     kGridOutdir       = ""; // AliEn output directory. If blank will become output_<kTrainName>
121 Int_t       kGridRunRange[2]       =  {0, -1}; // Set the run range
122 TString     kGridRunPattern        = "%03d"; // important for leading zeroes!!
123 TString     kGridPassPattern       = "";
124 TString     kGridExtraFiles        = ""; // files that will be added to the input list in the JDL...
125 Int_t       kGridMaxMergeFiles      = 50; // Number of files merged in a chunkgridrunragn
126 TString     kGridMergeExclude       = "AliAOD.root"; // Files that should not be merged
127 TString     kGridOutputStorages      = "ALICE::NIHAM::File,ALICE::CNAF::SE,ALICE::FZK::SE,ALICE::GSI::SE,ALICE::Legnaro::SE"; // Make replicas on the storages
128 // == grid process variables
129 Int_t       kGridRunsPerMaster     = 100; // Number of runs per master job
130 Int_t       kGridFilesPerJob       = 100; // Maximum number of files per job (gives size of AOD)
131
132 //==============================================================================
133 // ### Local Steering variables
134 //==============================================================================
135 //== local setup variables
136 //== local input and output variables
137 TString     kLocalXMLDataset   = ""; // Change local xml dataset for local interactive analysis
138 TString     kLocalDataList   = "local_deltaaod.txt"; // Change local xml dataset for local interactive analysis
139 // == local process variables
140
141
142
143 // Temporaries.
144 TString anaPars = "";
145 TString anaLibs = "";
146 TString anaLibsExtra = "";
147 TString anaSources = "";
148 // Function signatures
149 class AliAnalysisAlien;
150
151 //______________________________________________________________________________
152 void AnalysisTrainPWG4Jets(const char *analysis_mode="local", 
153                            const char *plugin_mode="",
154                            const char *config_file="",Int_t iOffset = 0)
155 {
156 // Main analysis train macro. If a configuration file is provided, all parameters
157 // are taken from there but may be altered by CheckModuleFlags.
158    if (strlen(config_file) && !LoadConfig(config_file)) return;
159    if(iOffset)kProofOffset = iOffset;
160    TString smode(analysis_mode);
161    smode.ToUpper();
162    if (kSaveTrain)WriteConfig();
163    // Check compatibility of selected modules
164    CheckModuleFlags(smode);
165    //   gROOT->ProcessLine(".trace");
166
167    printf("==================================================================\n");
168    printf("===========    RUNNING ANALYSIS TRAIN %s IN %s MODE   ==========\n", kTrainName.Data(),smode.Data());
169    printf("==================================================================\n");
170    printf("=  Configuring analysis train for:                               =\n");
171    if (iAODanalysis) printf("=  AOD analysis                                                  =\n");
172    else              printf("=  ESD analysis                                                  =\n");
173    if (iPhysicsSelection)   printf("=  Physics selection                                                    =\n");
174    if (iESDfilter)   printf("=  ESD filter                                                    =\n");
175    if (iJETAN)       printf("=  Jet analysis                                                  =\n");
176    printf("==================================================================\n");
177    printf(":: use Fill AOD      %d\n", (UInt_t)kFillAOD);
178    printf(":: use MC truth      %d\n", (UInt_t)kUseMC);
179    printf(":: use KINE filter   %d\n", (UInt_t)kUseKinefilter);
180    printf(":: use track refs    %d\n", (UInt_t)kUseTR);
181    printf(":: use tags          %d\n", (UInt_t)kUseESDTags);
182    printf(":: use AOD tags      %d\n", (UInt_t)kUseAODTags);
183    printf(":: use debugging     %d\n", (UInt_t)kUseDebug);
184    printf(":: use PAR files     %d\n", (UInt_t)kUsePAR);
185    printf(":: use AliEn plugin  %d\n", (UInt_t)kPluginUse);
186    printf(":: use PWG1 QA sym       %d\n", iPWG1QASym);
187    printf(":: use PWG4 Source Sara  %d\n",iPWG4TmpSourceSara);
188    printf(":: use PWG4 Jet tasks    %d\n",iPWG4JetTasks);
189    printf(":: use PWG4 Jet Services %d\n",iPWG4JetServices);     
190    printf(":: use PWG4 Jet Spectrum %d\n",iPWG4JetSpectrum);
191    printf(":: use PWG4 UE           %d \n",iPWG4UE); 
192    printf(":: use PWG4 Pt QA MC     %d\n",iPWG4PtQAMC);
193    printf(":: use PWG4 Pt Spectra   %d\n",iPWG4PtSpectra);
194    printf(":: use PWG4 Pt QA TPC    %d\n",iPWG4PtQATPC);     
195    printf(":: use PWG4 Three Jets   %d\n",iPWG4ThreeJets);
196    printf(":: use PWG4 KMeans       %d\n",iPWG4KMeans);
197    printf(":: use PWG4 Cluster       %d\n",iPWG4Cluster);
198    printf(":: use PWG4 Part Corr    %d\n",iPWG4PartCorr);
199    printf(":: use PWG4 Calo QA    %d\n",iPWG4CaloQA);
200    printf(":: use PWG4 Jet Corr    %d\n",iPWG4JetCorr);
201    printf(":: use PWG4 Tagged       %d\n",iPWG4Tagged);
202    printf(":: use PWG4 omega to 3 pions %d\n",iPWG4omega3pi);
203
204    printf(":: use PWG4 Gamma Conv   %d\n",iPWG4GammaConv);
205    printf(":: use HighPt FilterMask %d\n",kHighPtFilterMask);    
206
207
208    //==========================================================================
209    // Connect to back-end system
210    if (!Connect(smode)) {
211       ::Error("AnalysisTrain", "Could not connect to %s back-end", analysis_mode);
212       return;
213    }   
214
215    // Load common libraries and set include path
216    if (!LoadCommonLibraries(smode)) {
217       ::Error("AnalysisTrain", "Could not load common libraries");
218       return;
219    }
220     
221    // Make the analysis manager and connect event handlers
222    AliAnalysisManager *mgr  = new AliAnalysisManager("PWG4Train", "pwg4 mini train");
223    if (kCommonOutputFileName.Length()>0)mgr->SetCommonFileName(kCommonOutputFileName.Data());
224    if (kProofSaveToAlien) mgr->SetSpecialOutputLocation(kProofOutdir);
225    if (!strcmp(plugin_mode, "test")) mgr->SetNSysInfo(1);
226    if (kUseSysInfo)mgr->SetNSysInfo(kUseSysInfo);
227    // Load analysis specific libraries
228    if (!LoadAnalysisLibraries(smode)) {
229       ::Error("AnalysisTrain", "Could not load analysis libraries");
230      return;
231    }   
232
233    // Create input handler (input container created automatically)
234    if (iAODanalysis) {
235    // AOD input handler
236       AliAODInputHandler *aodH = new AliAODInputHandler();
237       mgr->SetInputEventHandler(aodH);
238       if (iPWG4JetTasks) aodH->AddFriend(Form("deltas/%s",kDeltaAODJetName.Data()));
239       if (iPWG4PartCorr) aodH->AddFriend(Form("deltas/%s"kDeltaAODJetName.Data()));
240    } else {   
241    // ESD input handler
242       AliESDInputHandler *esdHandler = new AliESDInputHandler();
243       if (kUseESDTags) esdHandler->SetReadTags();
244       mgr->SetInputEventHandler(esdHandler);       
245       if(iPWG4PtQATPC)esdHandler->SetActiveBranches("ESDfriend");
246    }
247
248    // Monte Carlo handler
249    if (kUseMC && !iAODanalysis) {
250       AliMCEventHandler* mcHandler = new AliMCEventHandler();
251       mgr->SetMCtruthEventHandler(mcHandler);
252       mcHandler->SetReadTR(kUseTR); 
253    }   
254    // AOD output container, created automatically when setting an AOD handler
255    if (iAODhandler) {
256       // AOD output handler
257       AliAODHandler* aodHandler   = new AliAODHandler();
258       aodHandler->SetOutputFileName("AliAOD.root");
259       aodHandler->SetFillAOD(kFillAOD);
260       
261       mgr->SetOutputEventHandler(aodHandler);
262       //
263       if (iAODanalysis) {
264
265         //         aodHandler->SetCreateNonStandardAOD();
266         //      if (iJETAN)aodHandler->SetOutputFileName(kDeltaAODJetName.Data());
267       } 
268       AliAnalysisDataContainer * cout_aod = mgr->GetCommonOutputContainer();
269       cout_aod->SetSpecialOutput();
270    }
271    // Debugging if needed
272    if (kUseDebug) mgr->SetDebugLevel(3);
273
274    //==========================================================================
275    // Create the chain. In this example it is created only from ALIEN files but
276    // can be done to work in batch or grid mode as well.
277    TChain *chain = CreateChain(smode, plugin_mode);
278         
279    //==========================================================================
280    // Load the tasks configuration macros for all wagons. These files are supposed now to be
281    // in the current workdir, but in AliEn they will be in the file catalog, 
282    // mapped from AliRoot and pecified in the jdl input list.
283     
284    // For now connection to top input container and common AOD output container
285    // is done in this macro, but in future these containers will be connected
286    // from each task configuration macro.
287
288    if(iPhysicsSelection && !iAODanalysis){
289      gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskPhysicsSelection.C");
290      AliPhysicsSelectionTask* physSelTask = AddTaskPhysicsSelection(kIsMC,kTRUE);
291    }
292
293    if (iESDfilter && !iAODanalysis) {
294       //  ESD filter task configuration.
295       gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskESDFilter.C");
296       AliAnalysisTaskESDfilter *taskesdfilter = AddTaskESDFilter(kUseKinefilter,kUseMuonfilter);
297    }   
298
299    // AOD tags
300    if (kUseAODTags) {
301       AliAnalysisTaskTagCreator* tagTask = new AliAnalysisTaskTagCreator("AOD Tag Creator");
302       mgr->AddTask(tagTask);
303       AliAnalysisDataContainer *coutTags = mgr->CreateContainer("cTag",  TTree::Class(), 
304                                            AliAnalysisManager::kOutputContainer, "AOD.tag.root");
305       mgr->ConnectInput (tagTask, 0, mgr->GetCommonInputContainer());
306       mgr->ConnectOutput(tagTask, 1, coutTags);
307    }   
308     
309     // Jet analysis
310    if (iJETAN) {
311       gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJets.C");
312       AliAnalysisTaskJets *taskjets = 0;
313       if(iJETAN&1)taskjets = AddTaskJets(kHighPtFilterMask); 
314       if(iJETAN&2){
315         UInt_t selection = 0;
316         if(!kFillAOD) selection = 0xffffff; //&~(1<<13);
317         else selection = 1<<0|1<<1|1<<2|1<<3|1<<4|1<<5|1<<6|1<<7|1<<8|1<<9;
318         AddTaskJetsDelta(kDeltaAODJetName.Data(),kHighPtFilterMask,kUseAODMC,selection); 
319       }
320       if (!taskjets) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskJets cannot run for this train conditions - EXCLUDED");
321    }
322
323    if (iDIJETAN) {
324       gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskDiJets.C");
325       AliAnalysisTaskDiJets *taskdijets = 0;
326       taskdijets = AddTaskDiJets(); 
327       if (!taskdijets) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskJets cannot run for this train conditions - EXCLUDED");
328    }
329
330        
331    if(iPWG1QASym){
332      gROOT->LoadMacro("$ALICE_ROOT/prod/acrcaf/qa_pp/AddTaskQAsym.C");
333      AliAnalysisTaskQASym *taskQASym = AddTaskQAsym(-1);
334      if (!taskQASym) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskQASym cannot run for this train conditions - EXCLUDED");
335    }
336
337
338
339    if(iPWG4TmpSourceSara){
340      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskEta.C");
341      AliAnalysisTaskEta *taskEta = AddTaskEta();
342      if (!taskEta) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskEta cannot run for this train conditions - EXCLUDED");
343    }
344
345
346    if(iPWG4JetServices){
347      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJetServices.C");
348      AliAnalysisTaskJetServices *taskjetServ = 0;
349      taskjetServ = AddTaskJetServices();
350      if (!taskjetServ) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskJetServices cannot run for this train conditions - EXCLUDED");
351      if(kGridRunRange[0]>0)taskjetServ->SetRunRange(kGridRunRange[0],kGridRunRange[1]);
352      else taskjetServ->SetRunRange(104000,105000);
353      if(!kIsMC) taskjetServ->SetRealData(kTRUE);
354      if(!iPhysicsSelection)taskjetServ->SetUsePhysicsSelection(kFALSE);
355    }
356
357
358    if(iPWG4JetSpectrum){
359      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJetSpectrum2.C");
360      AliAnalysisTaskJetSpectrum2 *taskjetSpectrum = 0;
361      if(iPWG4JetSpectrum&1){
362        taskjetSpectrum = AddTaskJetSpectrum2("jets","",kHighPtFilterMask,iPhysicsSelection);      
363        if(!iAODanalysis){
364          taskjetSpectrum = AddTaskJetSpectrum2("jets","tracks32",32,iPhysicsSelection);       // tmp hack to give it a different name
365          taskjetSpectrum = AddTaskJetSpectrum2("jets","tracks64",64,iPhysicsSelection);      
366        }
367        if (!taskjetSpectrum) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskJetSpectrum2 cannot run for this train conditions - EXCLUDED");
368        taskjetSpectrum->SetDebugLevel(0);
369      }
370
371      if(iPWG4JetSpectrum&2){
372        UInt_t selection = 0;
373        if(!iAODanalysis) selection = 0xffffff;
374        else selection = 1<<0|1<<1|1<<2|1<<3|1<<4|1<<5|1<<7|1<<8|1<<9;
375        AddTaskJetSpectrum2Delta(kHighPtFilterMask,kUseAODMC,iPhysicsSelection,selection);
376      }
377      if(iJETAN&3&&!kFillAOD&!iAODanalysis){
378        AddTaskJetSpectrum2("jetsAOD_FASTKT00","",kHighPtFilterMask,iPhysicsSelection);
379        AddTaskJetSpectrum2("jetsAOD_FASTKT01","",kHighPtFilterMask,iPhysicsSelection);
380        AddTaskJetSpectrum2("jetsAOD_FASTKT02","",kHighPtFilterMask,iPhysicsSelection);
381        AddTaskJetSpectrum2("jetsAOD_FASTKT06","",kHighPtFilterMask,iPhysicsSelection);
382        AddTaskJetSpectrum2("jetsAOD_FASTKT08","",kHighPtFilterMask,iPhysicsSelection);
383        if(kIsMC){
384          AddTaskJetSpectrum2("jetsAODMC2b_FASTKT00","",kHighPtFilterMask,iPhysicsSelection);
385          AddTaskJetSpectrum2("jetsAODMC2b_FASTKT01","",kHighPtFilterMask,iPhysicsSelection);
386          AddTaskJetSpectrum2("jetsAODMC2b_FASTKT02","",kHighPtFilterMask,iPhysicsSelection);
387          AddTaskJetSpectrum2("jetsAODMC2b_FASTKT06","",kHighPtFilterMask,iPhysicsSelection);
388          AddTaskJetSpectrum2("jetsAODMC2b_FASTKT08","",kHighPtFilterMask,iPhysicsSelection);
389        }
390      }
391    }
392
393    if(iPWG4UE){
394      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskUE.C");
395      AliAnalysisTaskUE *taskUE = 0;
396      if(iPWG4UE&1)taskUE = AddTaskUE(); 
397      if(iPWG4UE&2){
398        taskUE = AddTaskUE("jetsAOD_CDF07","CDF","LJ","TRANSV"); 
399        taskUE = AddTaskUE("jetsAOD_UA1LO07","CDF","LJ","TRANSV"); 
400        taskUE = AddTaskUE("jetsAOD_UA1LO07","CDF","BB","TRANSV"); 
401        taskUE = AddTaskUE("jetsAOD_FASTKT04","CDF","LJ","TRANSV"); 
402        taskUE = AddTaskUE("jetsAOD_FASTJET04","CDF","LJ","TRANSV"); 
403        taskUE = AddTaskUE("jetsAOD_SISCONE04","CDF","LJ","TRANSV"); 
404        taskUE = AddTaskUE("jetsAOD_CDF07","ALICE","LJ","TRANSV"); 
405        taskUE = AddTaskUE("jetsAOD_UA1LO07","ALICE","LJ","TRANSV"); 
406        taskUE = AddTaskUE("jetsAOD_UA1LO07","ALICE","BB","TRANSV"); 
407        taskUE = AddTaskUE("jetsAOD_FASTKT04","ALICE","LJ","TRANSV"); 
408        taskUE = AddTaskUE("jetsAOD_FASTJET04","ALICE","LJ","TRANSV"); 
409        taskUE = AddTaskUE("jetsAOD_SISCONE04","ALICE","LJ","TRANSV"); 
410      }
411
412      if (!taskUE) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskUE cannot run for this train conditions - EXCLUDED");
413    }
414
415    if(iPWG4ThreeJets){
416      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskThreeJets.C");
417      AliAnalysisTaskThreeJets *taskThree = AddTaskThreeJets();
418      if(!taskThree)::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskThreets cannot run for this train conditions - EXCLUDED");
419    }
420
421    if(iPWG4PtQAMC){
422      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskPWG4HighPtQAMC.C");
423      AliPWG4HighPtQAMC *taskQAMC = AddTaskPWG4HighPtQAMC();
424      if (!taskQAMC) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskQAMC cannot run for this train conditions - EXCLUDED");
425    }
426
427    if(iPWG4PtQATPC){
428      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskPWG4HighPtQATPConly.C");
429      AliPWG4HighPtQATPConly *taskQATPC = AddTaskPWG4HighPtQATPConly();
430      if (!taskQATPC) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskQATPC cannot run for this train conditions - EXCLUDED");
431    }
432    
433    if(iPWG4PtSpectra){
434      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskPWG4HighPtSpectra.C");
435      AliPWG4HighPtSpectra *taskPtSpectra = AddTaskPWG4HighPtSpectra();
436      if (!taskPtSpectra) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskPtSpectra cannot run for this train conditions - EXCLUDED");
437    }
438
439    if(iPWG4KMeans){
440      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskKMeans.C");
441      AliAnalysisTaskKMeans *taskKMeans = AddTaskKMeans();
442      if (!taskKMeans) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskKMenans cannot run for this train conditions - EXCLUDED");
443    }
444
445    if(iPWG4Cluster){
446      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJetCluster.C");
447      AliAnalysisTaskJetCluster *taskCl = 0;
448      if(iPWG4Cluster&1)taskCl = AddTaskJetCluster("AOD","",kHighPtFilterMask,iPhysicsSelection);
449      if(iPWG4Cluster&2){
450        UInt_t selection = 0;
451        if(!iAODanalysis) selection = 0xffffff;
452        else selection = 1<<0|1<<1|1<<2|1<<3|1<<4|1<<5|1<<7|1<<8|1<<9;
453        AddTaskJetClusterDelta(kHighPtFilterMask,kUseAODMC,iPhysicsSelection,selection);
454      }
455      if (!taskCl) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskCluster cannot run for this train conditions - EXCLUDED");
456
457    }
458
459    if(iPWG4PartCorr){
460      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskPartCorr.C");
461      AliAnalysisTaskParticleCorrelation *taskpartcorrPHOS = AddTaskPartCorr("AOD", "PHOS",kFALSE,kIsMC);
462      if (!taskpartcorrPHOS) ::Warning("AnalysisTrainNew", "AliAnalysisTaskParticleCorrelation PHOS cannot run for this train conditions - EXCLUDED");
463      AliAnalysisTaskParticleCorrelation *taskpartcorrEMCAL = AddTaskPartCorr("AOD", "EMCAL",kFALSE,kIsMC);
464      if (!taskpartcorrEMCAL) ::Warning("AnalysisTrainNew", "AliAnalysisTaskParticleCorrelation EMCAL cannot run for this train conditions - EXCLUDED");
465      if(kDeltaAODPartCorrName.Length()>0)mgr->RegisterExtraFile(kDeltaAODPartCorrName.Data()); // hmm this is written anyway.... but at least we do not register it...
466    } 
467
468    if(iPWG4CaloQA){
469      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/QA/AddTaskCalorimeterQA.C");
470      AliAnalysisTaskParticleCorrelation *taskcaloQA =  AddTaskCalorimeterQA("ESD",kFALSE,kIsMC);
471      if(!taskcaloQA)::Warning("AnalysisTrainNew", "AliAnalysisTaskParticleCorrelation QA cannot run - EXCLUDED");
472    } 
473
474
475    if(iPWG4JetCorr){
476      //     using namespace JetCorrelHD;
477
478      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJetCorrel.C");
479      AliAnalysisTaskJetCorrel *taskjetcorr = AddTaskJetCorrel();
480      if (!taskpartcorrEMCAL) ::Warning("AnalysisTrainNew", "AliAnalysisTaskJetCorrel  cannot run for this train conditions - EXCLUDED");
481    } 
482
483
484    if(iPWG4Tagged){
485      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskTaggedPhotons.C");
486      AliAnalysisTaskTaggedPhotons * taskTagged = AddTaskTaggedPhotons(kFALSE); // EMCAL
487      //     taskTagged = AddTaskTaggedPhotons(kTRUE); // PHOS 
488      if (!taskTagged) ::Warning("AnalysisTrainNew", "AliAnalysisTaskTaggedPhotons  cannot run for this train conditions - EXCLUDED");     
489    }
490
491    if (iPWG4omega3pi) {
492      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskomega3pi.C");
493      AliAnalysisTaskOmegaPi0PiPi *taskomega3pi = AddTaskomega3pi();
494      if (!taskomega3pi) ::Warning("AnalysisTrainNew", "AliAnalysisTaskomega3pi cannot run\
495  for these train conditions - EXCLUDED");
496    }
497
498
499    // PWG4 gamma conversion analysis
500    if (iPWG4GammaConv) {
501       gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskGammaConversion.C");
502       TString cdir = gSystem->WorkingDirectory();
503       gSystem->ChangeDirectory(gSystem->ExpandPathName("$ALICE_ROOT/PWG4/macros/"));
504       //      TString gcArguments = "-run-on-train -run-jet -run-chic -run-neutralmeson -run-cf";
505       TString gcArguments = "-run-on-train -run-jet -run-neutralmeson -run-cf -use-own-xyz -bg-off";
506       if(!kIsMC)gcArguments += " -mc-off";
507       AliAnalysisTaskGammaConversion * taskGammaConversion = AddTaskGammaConversion(gcArguments,mgr->GetCommonInputContainer());
508       gSystem->ChangeDirectory(cdir);
509       taskGammaConversion->SelectCollisionCandidates();
510       if (!taskGammaConversion) ::Warning("AnalysisTrainNew", "AliAnalysisTaskGammaConversion cannot run for these train conditions - EXCLUDED");
511    }   
512
513    //==========================================================================
514    // FOR THE REST OF THE TASKS THE MACRO AddTaskXXX() is not yet implemented/
515    // Run the analysis
516    //    
517    if (kPluginUse) {
518       AliAnalysisGrid *alienHandler = CreateAlienHandler(plugin_mode);
519       AliAnalysisManager::GetAnalysisManager()->SetGridHandler(alienHandler);
520    }
521    
522    if (mgr->InitAnalysis()) {
523      mgr->PrintStatus();
524      // if (kSaveTrain || strlen(config_file)) gSystem->ChangeDirectory(kTrainName);
525      if (!strcmp(plugin_mode,"submit")&&smode=="GRID"){
526        TString alien_workdir = gGrid->GetHomeDirectory();
527        if (iAODanalysis) alien_workdir += "analysisAOD";
528        else              alien_workdir += "analysisESD";
529        AliAnalysisAlien *gridhandler = (AliAnalysisAlien*)mgr->GetGridHandler();
530        printf("=== AnalysisTrainPWG4Jets:: Registering jdl in the work directory alien://%s/%s, should be done by the manager! ===\n",
531               alien_workdir.Data(),gridhandler->GetGridOutputDir());
532        TFile::Cp(Form("file:%s.jdl",kTrainName.Data()), Form("alien://%s/%s/%s.jdl",alien_workdir.Data(),
533                                                              gridhandler->GetGridOutputDir(),kTrainName.Data()));
534      }
535     
536      StartAnalysis(smode, chain);
537      if (!strcmp(plugin_mode, "offline")&&smode=="GRID"){
538        // Offline mode path files
539        //       PatchJDL();
540        PatchAnalysisMacro();
541      }
542
543      if (kSaveTrain && smode=="GRID") {
544        AliAnalysisAlien *gridhandler = (AliAnalysisAlien*)mgr->GetGridHandler();
545        TString alien_workdir = gGrid->GetHomeDirectory();
546        if (iAODanalysis) alien_workdir += "analysisAOD";
547          else              alien_workdir += "analysisESD";
548        //     kGridOutdir = gridhandler->GetGridOutputDir();
549        printf("=== Registering ConfigTrain.C in the work directory <%s> ===\n",
550                 alien_workdir.Data());
551        if (AliAnalysisAlien::FileExists(Form("%s/%sConfig.C", alien_workdir.Data(), kTrainName.Data())))
552          gGrid->Rm(Form("%s/%sConfig.C", alien_workdir.Data(), kTrainName.Data()));
553        if (strcmp(plugin_mode, "test"))
554          TFile::Cp(Form("file:%sConfig.C",kTrainName.Data()), Form("alien://%s/%sConfig.C", alien_workdir.Data(), kTrainName.Data()));
555      }
556    }
557 }
558
559 //______________________________________________________________________________
560 void StartAnalysis(const char *mode, TChain *chain) {
561 // Start analysis.
562    Int_t imode = -1;
563    AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
564    if (!strcmp(mode, "LOCAL")) imode = 0;
565    if (!strcmp(mode, "PROOF")) imode = 1;
566    if (!strcmp(mode, "GRID"))  imode = 2;
567    switch (imode) {
568       case 0:
569          if (!chain) {
570             ::Error("AnalysisTrainPWG4Jets.C::StartAnalysis", "Cannot create the chain");
571             return;
572          }   
573          mgr->StartAnalysis(mode, chain);
574          return;
575       case 1:
576          if (!kProofDataSet.Length()) {
577             ::Error("AnalysisTrainPWG4Jets.C::StartAnalysis", "kProofDataSet is empty");
578             return;
579          }   
580          mgr->StartAnalysis(mode, kProofDataSet, kProofEvents,kProofOffset);
581          return;
582       case 2:
583          if (kPluginUse) {
584             if (!mgr->GetGridHandler()) {
585                ::Error("AnalysisTrainPWG4Jets.C::StartAnalysis", "Grid plugin not initialized");
586                return;
587             }   
588             mgr->StartAnalysis("grid");
589          } else {
590             if (!chain) {
591                ::Error("AnalysisTrainPWG4Jets.C::StartAnalysis", "Cannot create the chain");
592                return;
593             }   
594             mgr->StartAnalysis(mode, chain);
595          }   
596          return;
597    }      
598 }          
599     
600 //______________________________________________________________________________
601 void CheckModuleFlags(const char *mode) {
602 // Checks selected modules and insure compatibility
603    Int_t imode = -1;
604    if (!strcmp(mode, "LOCAL")) imode = 0;
605    if (!strcmp(mode, "PROOF")) imode = 1;
606    if (!strcmp(mode, "GRID"))  imode = 2;
607
608
609    if (kUseCPAR) {
610      kPluginAliRootVersion    = ""; // NO aliroot if we use CPAR
611    }
612
613    if (imode==1) {
614       if (!kUsePAR) {
615          ::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PAR files enabled due to PROOF analysis");
616          kUsePAR = kTRUE;
617       }   
618    }  
619    if (imode != 2) {
620       ::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "AliEn plugin disabled since not in GRID mode");
621       kPluginUse = kFALSE; 
622    }   
623
624
625    if(!kIsMC){
626      // switch off anthin related to MC
627      kUseMC = 0;
628      kUseAODMC = 0;
629      kUseTR = kFALSE;
630    }
631
632    if (iAODanalysis) {
633    // AOD analysis
634       if (kUseMC)
635          ::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "MC usage disabled in analysis on AOD's");
636       if (kUseAODTags)
637          ::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "AOD tags usage disabled in analysis on AOD's");
638       kUseMC = kFALSE;
639       kUseTR = kFALSE;
640       kUseAODTags = kFALSE;
641       if (iESDfilter)
642          ::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "ESD filter disabled in analysis on AOD's");
643       iESDfilter   = 0;
644       if (iPhysicsSelection)
645          ::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "Physics Selection disabled in analysis on AOD's");
646       iPhysicsSelection   = 0;
647       if (!iAODhandler) {
648          if (iJETAN) 
649             ::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "JETAN disabled in analysis on AOD's without AOD handler");
650          iJETAN = 0;
651          iDIJETAN = 0;
652       }
653       // Disable tasks that do not work yet on AOD data
654       if( iPWG4PtQAMC)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4 PtQAMC disabled in analysis on AOD's");
655       iPWG4PtQAMC        = 0;
656       if( iPWG4PtQATPC)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4 PtTPC disabled in analysis on AOD's");
657       iPWG4PtQATPC        = 0;
658       if( iPWG4PtSpectra)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4 PtQAMC disabled in analysis on AOD's");
659       iPWG4PtSpectra     = 0;
660       if(iPWG4KMeans)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4KMeans disabled on AOD's");
661       iPWG4KMeans       = 0;
662       if (iPWG4JetCorr)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4Jetcorr disabled on AOD's");
663       iPWG4JetCorr = 0;
664       if (iPWG4PartCorr)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4partcorr disabled on AOD's");
665       iPWG4PartCorr = 0;
666       if (iPWG4CaloQA)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4CaloQA disabled on AOD's");
667       iPWG4CaloQA = 0;
668       if (iPWG4Tagged)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4tagged disabled on AOD's");
669       iPWG4Tagged = 0;
670       if (iPWG4omega3pi)
671         ::Info("AnalysisTrainNew.C::CheckModuleFlags", "PWG4omega3pi disabled on AOD's");
672       iPWG4omega3pi = 0;
673       if(iPWG1QASym)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG1 QA Sym disabled in analysis on AOD's");
674       if (iPWG4GammaConv)::Info("AnalysisPWG4Jets.C::CheckModuleFlags", "PWG4gammaconv disabled on AOD's");
675       iPWG4GammaConv = 0;   
676       iPWG1QASym     = 0;
677    } else {   
678    // ESD analysis
679      if (!kUseMC){
680        kUseTR = kFALSE;
681        
682        if(kUseKinefilter)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4 Kine Filter disabled in analysis without MC");
683        kUseKinefilter = kFALSE;
684        if( iPWG4PtQAMC)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4 PtQAMC disabled in analysis without MC");
685        iPWG4PtQAMC        = 0;
686
687      }
688      if (!kUseTR) {
689        //         ::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "iPWG2evchar disabled if not reading track references");
690      }   
691      if (iJETAN){
692        iESDfilter=1;
693      }
694       if (!iESDfilter){
695         kUseKinefilter = kFALSE;
696         kUseMuonfilter = kFALSE;
697       }
698       if(!iJETAN){
699         iPWG4JetSpectrum = iPWG4UE = iPWG4ThreeJets = iDIJETAN = 0;
700       }
701    }
702    iPWG4JetTasks = iPWG4JetServices||iPWG4JetSpectrum||iPWG4UE||iPWG4PtQAMC||iPWG4PtSpectra||iPWG4PtQATPC||iPWG4ThreeJets;
703    iPWG4PartCorrLibs = iPWG4PartCorr||iPWG4Tagged||iPWG4CaloQA;
704    iJETANLib = iPWG4JetTasks||iJETAN||iDIJETAN;
705    if (iESDfilter) {iAODhandler=1;}
706    if (kUseKinefilter && !kUseMC) kUseKinefilter = kFALSE;
707    if (kUseAODTags && !iAODhandler) kUseAODTags = kFALSE;
708
709
710    
711 }
712
713 //______________________________________________________________________________
714 Bool_t Connect(const char *mode) {
715 // Connect <username> to the back-end system.
716    Int_t imode = -1;
717    if (!strcmp(mode, "LOCAL")) imode = 0;
718    if (!strcmp(mode, "PROOF")) imode = 1;
719    if (!strcmp(mode, "GRID"))  imode = 2;
720    TString username = gSystem->Getenv("alien_API_USER");
721    switch (imode) {
722       case 0:
723          break;
724       case 1:
725          if  (!username.Length()) {
726             ::Error(Form("AnalysisTrainPWG4Jets.C::Connect <%s>", mode), "Make sure you:\n \
727                            1. Have called: alien-token-init <username>\n \
728                            2. Have called: >source /tmp/gclient_env_$UID");
729             return kFALSE;
730          }
731          ::Info("AnalysisTrainPWG4Jets.C::Connect", "Connecting user <%s> to PROOF cluster <%s>", 
732                 username.Data(), kProofCluster.Data());
733          gEnv->SetValue("XSec.GSI.DelegProxy", "2");
734 //         TProof::Open(Form("%s@%s:31093", username.Data(), kProofCluster.Data()));       
735          TProof::Open(Form("%s@%s", username.Data(), kProofCluster.Data()));       
736          if (!gProof) {
737             if (strcmp(gSystem->Getenv("XrdSecGSISRVNAMES"), "lxfsrd0506.cern.ch"))
738                ::Error(Form("AnalysisTrainPWG4Jets.C::Connect <%s>", mode), "Environment XrdSecGSISRVNAMES different from lxfsrd0506.cern.ch");
739             return kFALSE;
740          }
741          if(kProofClearPackages)gProof->ClearPackages();
742
743          if(kProofSaveToAlien){
744            TGrid::Connect("alien://");
745            if (gGrid) {
746              TString homedir = gGrid->GetHomeDirectory();
747              TString workdir = homedir + kTrainName;
748              if (!gGrid->Cd(workdir)) {
749                gGrid->Cd(homedir);
750                if (gGrid->Mkdir(workdir)) {
751                  gGrid->Cd(kTrainName);
752                  ::Info("AnalysisTrainPWG4Jets::Connect()", "Directory %s created", gGrid->Pwd());
753                }
754              }
755              gGrid->Mkdir("proof_output");
756              gGrid->Cd("proof_output");
757              kProofOutdir = Form("alien://%s", gGrid->Pwd());
758            }   
759          }
760          break;
761       case 2:      
762          if  (!username.Length()) {
763             ::Error(Form("AnalysisTrainPWG4Jets.C::Connect <%s>", mode), "Make sure you:\n \
764                            1. Have called: alien-token-init <username>\n \
765                            2. Have called: >source /tmp/gclient_env_$UID");
766             return kFALSE;
767          }
768          if (kPluginUse && !gSystem->Getenv("alien_CLOSE_SE")) {
769             ::Error(Form("AnalysisTrainPWG4Jets.C::Connect <%s>", mode), 
770                            "When using the AliEn plugin it is preferable to define the \
771                            variable alien_CLOSE_SE in your environment.");
772             return kFALSE;
773          }
774          ::Info("AnalysisTrainPWG4Jets.C::Connect", "Connecting user <%s> to AliEn ...", 
775                 username.Data());
776          TGrid::Connect("alien://");
777          if (!gGrid || !gGrid->IsConnected()) return kFALSE;
778          break;
779       default:
780          ::Error("AnalysisTrainPWG4Jets.C::Connect", "Unknown run mode: %s", mode);
781          return kFALSE;
782    }
783    ::Info("AnalysisTrainPWG4Jets.C::Connect","Connected in %s mode", mode);
784    return kTRUE;
785 }
786
787 //______________________________________________________________________________
788 Bool_t LoadCommonLibraries(const char *mode)
789 {
790 // Load common analysis libraries.
791    Int_t imode = -1;
792    if (!strcmp(mode, "LOCAL")) imode = 0;
793    if (!strcmp(mode, "PROOF")) imode = 1;
794    if (!strcmp(mode, "GRID"))  imode = 2;
795    if (!gSystem->Getenv("ALICE_ROOT")) {
796       ::Error("AnalysisTrainPWG4Jets.C::LoadCommonLibraries", "Analysis train requires that analysis libraries are compiled with a local AliRoot"); 
797       return kFALSE;
798    }   
799    Bool_t success = kTRUE;
800    // ROOT libraries
801    gSystem->Load("libTree.so");
802    gSystem->Load("libGeom.so");
803    gSystem->Load("libVMC.so");
804    gSystem->Load("libPhysics.so");
805    
806    // Load framework classes. Par option ignored here.
807    switch (imode) {
808       case 0:
809       case 2:
810          if (kUseCPAR) {
811             success &= LoadLibrary("STEERBase", mode, kTRUE);
812             success &= LoadLibrary("ESD", mode, kTRUE);
813             success &= LoadLibrary("AOD", mode, kTRUE);
814             success &= LoadLibrary("ANALYSIS", mode, kTRUE);
815             success &= LoadLibrary("ANALYSISalice", mode, kTRUE);
816             success &= LoadLibrary("CORRFW", mode, kTRUE);
817          } else {   
818             success &= LoadLibrary("libSTEERBase.so", mode);
819             success &= LoadLibrary("libESD.so", mode);
820             success &= LoadLibrary("libAOD.so", mode);
821             success &= LoadLibrary("libANALYSIS.so", mode);
822             success &= LoadLibrary("libANALYSISalice.so", mode);
823             success &= LoadLibrary("libCORRFW.so", mode);
824             gROOT->ProcessLine(".include $ALICE_ROOT/include");
825          }   
826          break;
827       case 1:
828          Int_t ires = -1;
829          if (kProofUseAFPAR && !gSystem->AccessPathName(kProofAFversion)) ires = gProof->UploadPackage(kProofAFversion);
830          if (ires < 0) {
831             success &= LoadLibrary("STEERBase", mode);
832             success &= LoadLibrary("ESD", mode);
833             success &= LoadLibrary("AOD", mode);
834             success &= LoadLibrary("ANALYSIS", mode);
835             success &= LoadLibrary("ANALYSISalice", mode);
836             success &= LoadLibrary("CORRFW", mode);
837          } else { 
838             ires = gProof->EnablePackage(kProofAFversion);
839             if (ires<0) success = kFALSE;
840             success &= LoadLibrary("CORRFW", mode);
841          }
842          break;         
843       default:
844          ::Error("AnalysisTrainPWG4Jets.C::LoadCommonLibraries", "Unknown run mode: %s", mode);
845          return kFALSE;
846    }
847    if (success) {
848       ::Info("AnalysisTrainPWG4Jets.C::LoadCommodLibraries", "Load common libraries:    SUCCESS");
849       ::Info("AnalysisTrainPWG4Jets.C::LoadCommodLibraries", "Include path for Aclic compilation:\n%s",
850               gSystem->GetIncludePath());
851    } else {           
852       ::Info("AnalysisTrainPWG4Jets.C::LoadCommodLibraries", "Load common libraries:    FAILED");
853    }   
854       
855    return success;
856 }
857
858 //______________________________________________________________________________
859 Bool_t LoadAnalysisLibraries(const char *mode)
860 {
861 // Load common analysis libraries.
862    Bool_t success = kTRUE;
863    if (iESDfilter) {
864       if (!LoadLibrary("PWG3base", mode, kTRUE) ||
865           !LoadLibrary("PWG3muon", mode, kTRUE)) return kFALSE;
866    }   
867    // JETAN
868    if (iJETANLib) {
869      // this part needs some rework in case we do not need the fastjed finders for processing
870      if (!LoadLibrary("JETAN", mode, kTRUE)) return kFALSE;
871      if (!strcmp(mode, "PROOF")){
872        gProof->Exec("gSystem->Load\(\"/afs/cern.ch/user/d/dperrino/public/libCGAL.so\"\)", kTRUE); 
873        gProof->Exec("gSystem->Load\(\"/afs/cern.ch/user/d/dperrino/public/libfastjet.so\"\)", kTRUE); 
874        // problem when loading siscone copiled with different gcc version??
875        // gProof->Exec("gSystem->Load\(\"/afs/cern.ch/user/d/dperrino/public/libsiscone.so\"\)", kTRUE); 
876        gProof->Exec("gSystem->Load\(\"/afs/cern.ch/user/d/dperrino/public/libSISConePlugin.so\"\)", kTRUE);      
877      }
878      if(!kUsePAR){ 
879        if (!LoadLibrary("CGAL", mode, kTRUE)) return kFALSE;
880        if (!LoadLibrary("fastjet", mode, kTRUE)) return kFALSE;
881        if (!LoadLibrary("siscone", mode, kTRUE)) return kFALSE;
882        if (!LoadLibrary("SISConePlugin", mode, kTRUE)) return kFALSE;
883      }
884      else{
885        // par files plus FASTJET needs some extra work... need to change
886        // the loading sequence in the auto generated .C file
887        if (!LoadLibrary("libCGAL.so", mode, kTRUE)) return kFALSE;
888        if (!LoadLibrary("libfastjet.so", mode, kTRUE)) return kFALSE;
889        if (!LoadLibrary("libsiscone.so", mode, kTRUE)) return kFALSE;
890        if (!LoadLibrary("libSISConePlugin.so", mode, kTRUE)) return kFALSE;
891      }
892      if (!LoadLibrary("FASTJETAN", mode, kTRUE)) return kFALSE;
893    }
894    if(iPWG4JetTasks){
895      // PWG4 particle correlations
896      if (!LoadLibrary("PWG4JetTasks", mode, kTRUE)) return kFALSE;
897    }
898    if(iPWG1QASym){
899      if (!LoadSource(Form("%s/PWG1/AliAnalysisTaskQASym.cxx",gSystem->ExpandPathName("$ALICE_ROOT")), mode, kTRUE))return kFALSE;
900    }
901    if(iPWG4TmpSourceSara){
902      //  gSystem->AddIncludePath("-I$ALICE_ROOT/include/JetTasks"); // ugly hack!!
903      if(!LoadSource(Form("%s/PWG4/JetTasks/AliAnalysisTaskEta.cxx",gSystem->ExpandPathName("$ALICE_ROOT")), mode, kTRUE))return kFALSE;
904    }
905    if (iPWG4PartCorrLibs) {   
906       if (!LoadLibrary("EMCALUtils", mode, kTRUE) ||
907           !LoadLibrary("PHOSUtils", mode, kTRUE) ||
908           !LoadLibrary("PWG4PartCorrBase", mode, kTRUE) ||
909           !LoadLibrary("PWG4PartCorrDep", mode, kTRUE)) return kFALSE;
910    }
911    if (iPWG4JetCorr) { 
912      if (!LoadLibrary("PWG4JetCorrel", mode, kTRUE)) return kFALSE;
913    }  
914    if (iPWG4omega3pi) {
915      if (!LoadLibrary("PWG4omega3pi", mode, kTRUE)) return kFALSE;
916    }
917    if (iPWG4GammaConv) {
918       if (!LoadLibrary("PWG4GammaConv", mode, kTRUE)) return kFALSE;
919    }      
920
921    ::Info("AnalysisTrainPWG4Jets.C::LoadAnalysisLibraries", "Load other libraries:   SUCCESS");
922    return kTRUE;
923 }
924
925 //______________________________________________________________________________
926 Bool_t LoadLibrary(const char *module, const char *mode, Bool_t rec=kFALSE)
927 {
928 // Load a module library in a given mode. Reports success.
929    Int_t imode = -1;
930    Int_t result;
931    TString smodule(module);
932    if (!strcmp(mode, "LOCAL")) imode = 0;
933    if (!strcmp(mode, "PROOF")) imode = 1;
934    if (!strcmp(mode, "GRID"))  imode = 2;
935    TString mod(module);
936    if (!mod.Length()) {
937       ::Error("AnalysisTrainPWG4Jets.C::LoadLibrary", "Empty module name");
938       return kFALSE;
939    }   
940    // If a library is specified, just load it
941    if (smodule.EndsWith(".so")) {
942       mod.Remove(mod.Index(".so"));
943       result = gSystem->Load(mod);
944       if (result < 0) {
945          ::Error("AnalysisTrainPWG4Jets.C::LoadLibrary", "Could not load library %s", module);
946          return kFALSE;
947       }
948       if (rec) anaLibs += Form("%s.so ",mod.Data()); 
949       if (rec) anaLibsExtra += Form("%s.so ",mod.Data()); 
950       return kTRUE;
951    } 
952    // Check if the library is already loaded
953    if (strlen(gSystem->GetLibraries(Form("%s.so", module), "", kFALSE)) > 0)
954       return kTRUE;    
955    switch (imode) {
956       case 0:
957       case 2:
958          if (kUsePAR) {
959             result = SetupPar(module);
960             if (rec) anaPars += Form("%s.par ", module);
961          } else {
962             result = gSystem->Load(Form("lib%s.so", module));
963             if (rec) anaLibs += Form("lib%s.so ", module);
964          }   
965          break;
966       case 1:
967         if(!gSystem->AccessPathName(module)){
968           ::Info("AnalysisTrainPWG4Jets.C::LoadLibrary", "Removing directory %s",module);
969           gSystem->Exec(Form("rm -rf %s",module));
970         }
971          result = gProof->UploadPackage(module);
972          if (result<0) {
973             result = gProof->UploadPackage(gSystem->ExpandPathName(Form("$ALICE_ROOT/%s.par", module)));
974             if (result<0) {
975                ::Error("AnalysisTrainPWG4Jets.C::LoadLibrary", "Could not find module %s.par in current directory nor in $ALICE_ROOT", module);
976                return kFALSE;
977             }
978          }   
979          result = gProof->EnablePackage(module);
980          break;
981       default:
982          return kFALSE;
983    }         
984    if (result < 0) {
985       ::Error("AnalysisTrainPWG4Jets.C::LoadLibrary", "Could not load module %s", module);
986       return kFALSE;
987    }
988    return kTRUE;
989 }           
990
991
992
993 //______________________________________________________________________________
994 Bool_t LoadSource(const char *source, const char *mode, Bool_t rec=kFALSE)
995 {
996 // Load a module library in a given mode. Reports success.
997    Int_t imode = -1;
998    Int_t result = -1;
999    if (!strcmp(mode, "LOCAL")) imode = 0;
1000    if (!strcmp(mode, "PROOF")) imode = 1;
1001    if (!strcmp(mode, "GRID"))  imode = 2;
1002    TString ssource(source);
1003    TString basename = gSystem->BaseName(ssource.Data());
1004    if (!ssource.Length()) {
1005       ::Error("AnalysisTrainPWG4Jets.C::LoadSource", "Empty task name");
1006       return kFALSE;
1007    }   
1008     // we have a source code so compile it
1009    if (ssource.EndsWith(".cxx")) {
1010      // need to copy it here other wise the path is also used on grid...
1011      ssource.Remove(ssource.Index(".cxx"));
1012      basename.Remove(basename.Index(".cxx"));
1013      Printf("LoadSources:: Copying...  path %s{cxx,h}",ssource.Data());
1014      gSystem->Exec(Form("cp %s.cxx . ",ssource.Data()));
1015      gSystem->Exec(Form("cp %s.h . ",ssource.Data()));
1016      // Path to code
1017      // only needed for local compilation, in grid and proof mode 
1018      // the task headers are uploaded 
1019      //     path.Remove(path.Index(gSystem->BaseName(path.Data())));
1020      // Printf("LoadSources:: Including path %s",path.Data());
1021      //  if(path.Length()>0)gROOT->ProcessLine(Form(".include %s",path.Data()));
1022      Printf("LoadSources:: Loading...  path %s",basename.Data());
1023      switch (imode) {
1024      case 0:
1025        result = gROOT->LoadMacro(Form("%s.cxx++g",basename.Data()));
1026        break;
1027      case 1:
1028        result = gProof->LoadMacro(Form("%s.cxx++g",basename.Data()));
1029        break;
1030      case 2:
1031        result = gROOT->LoadMacro(Form("%s.cxx++g",basename.Data()));
1032        if (rec){
1033          // what we want to compile
1034          anaSources += Form("%s.cxx ",basename.Data()); 
1035          // what we need as input...
1036          anaLibs += Form("%s.cxx %s.h ",basename.Data(),basename.Data()); 
1037        }
1038        break;
1039      default:
1040        return kFALSE;
1041      }
1042    } 
1043    if (result < 0) {
1044       ::Error("AnalysisTrainPWG4Jets.C::LoadSources", "Could not load source %s", source);
1045       return kFALSE;
1046    }
1047    return kTRUE;
1048 }           
1049
1050
1051 //______________________________________________________________________________
1052 TChain *CreateChain(const char *mode, const char *plugin_mode)
1053 {
1054 // Create the input chain
1055    Int_t imode = -1;
1056    if (!strcmp(mode, "LOCAL")) imode = 0;
1057    if (!strcmp(mode, "PROOF")) imode = 1;
1058    if (!strcmp(mode, "GRID"))  imode = 2;
1059    TChain *chain = NULL;
1060    // Local chain
1061    switch (imode) {
1062       case 0:
1063          if (iAODanalysis) {
1064             if (!kLocalXMLDataset.Length()) {
1065                // Local AOD
1066                chain = new TChain("aodTree");
1067                TString line;
1068                ifstream in;
1069                in.open(kLocalDataList.Data());
1070                while (in.good()) {
1071                  in >> line;
1072                  if (line.Length() == 0) continue;
1073                  // cout << " line = " << line << endl;
1074                  chain->Add(line.Data());
1075                }       
1076             } else {
1077                // Interactive AOD
1078                chain = CreateChainSingle(kLocalXMLDataset, "aodTree");
1079             }
1080          } else {      
1081            if (!kLocalXMLDataset.Length()) {
1082              // Local ESD
1083              chain = new TChain("esdTree");
1084              TString line;
1085              ifstream in;
1086              in.open(kLocalDataList.Data());
1087              while (in.good()) {
1088                in >> line;
1089                if (line.Length() == 0) continue;
1090                cout << " line = " << line << endl;
1091                chain->Add(line.Data());
1092              }       
1093            } else {
1094              // Interactive ESD
1095                chain = CreateChainSingle(kLocalXMLDataset, "esdTree");
1096            }   
1097          }
1098          break;
1099       case 1:
1100          break;
1101       case 2:
1102          if (kPluginUse) {
1103 //            AliAnalysisGrid *alienHandler = CreateAlienHandler(plugin_mode);
1104 //            AliAnalysisManager::GetAnalysisManager()->SetGridHandler(alienHandler);
1105          } else {
1106             TString           treeName = "esdTree";
1107             if (iAODanalysis) treeName = "aodTree";
1108             chain = CreateChainSingle("wn.xml", treeName);
1109          }
1110          break;      
1111       default:   
1112    }
1113    if (chain && chain->GetNtrees()) return chain;
1114    return NULL;
1115 }   
1116
1117 //______________________________________________________________________________
1118 TChain* CreateChainSingle(const char* xmlfile, const char *treeName)
1119 {
1120    printf("*******************************\n");
1121    printf("*** Getting the ESD Chain   ***\n");
1122    printf("*******************************\n");
1123    TAlienCollection * myCollection  = TAlienCollection::Open(xmlfile);
1124
1125    if (!myCollection) {
1126       ::Error("AnalysisTrainPWG4Jets.C::CreateChainSingle", "Cannot create an AliEn collection from %s", xmlfile) ;
1127       return NULL ;
1128    }
1129
1130    TChain* chain = new TChain(treeName);
1131    myCollection->Reset() ;
1132    while ( myCollection->Next() ) chain->Add(myCollection->GetTURL("")) ;
1133    chain->ls();
1134    return chain;
1135 }
1136
1137 //______________________________________________________________________________
1138 Int_t SetupPar(char* pararchivename)
1139 {
1140    if (!pararchivename || !strlen(pararchivename)) return -1;
1141    char processline[1024];
1142    if (gSystem->AccessPathName(Form("%s.par", pararchivename))) {
1143       if (!gSystem->AccessPathName(Form("%s/%s.par", gSystem->Getenv("ALICE_ROOT"),pararchivename))) {
1144          ::Info("AnalysisTrainPWG4Jets.C::SetupPar", "Getting %s.par from $ALICE_ROOT", pararchivename);
1145          TFile::Cp(gSystem->ExpandPathName(Form("$ALICE_ROOT/%s.par", pararchivename)), 
1146                    Form("%s.par",pararchivename));
1147       } else {
1148          ::Error("AnalysisTrainPWG4Jets.C::SetupPar", "Cannot find %s.par", pararchivename);
1149          return -1;
1150       }   
1151    }
1152    if (kPluginUse && kSaveTrain) gSystem->Exec(Form("ln -s ../%s.par %s",pararchivename, kTrainName.Data()));
1153    gSystem->Exec(Form("tar xvzf %s.par", pararchivename));
1154
1155    TString ocwd = gSystem->WorkingDirectory();
1156    if (!gSystem->ChangeDirectory(pararchivename)) return -1;
1157         
1158    // check for BUILD.sh and execute
1159    if (!gSystem->AccessPathName("PROOF-INF/BUILD.sh")) {
1160       printf("*******************************\n");
1161       printf("*** Building PAR archive    ***\n");
1162       printf("*******************************\n");          
1163       if (gSystem->Exec("PROOF-INF/BUILD.sh")) {
1164          Error("runProcess","Cannot Build the PAR Archive! - Abort!");
1165          return -1;
1166       }
1167    }
1168
1169         // check for SETUP.C and execute
1170         if (!gSystem->AccessPathName("PROOF-INF/SETUP.C")) {
1171             printf("*******************************\n");
1172             printf("*** Setup PAR archive       ***\n");
1173             printf("*******************************\n");
1174             gROOT->Macro("PROOF-INF/SETUP.C");
1175         }       
1176         if (!gSystem->ChangeDirectory(ocwd.Data())) return -1;
1177    return 0;
1178 }
1179
1180 //______________________________________________________________________________
1181 AliAnalysisAlien* CreateAlienHandler(const char *plugin_mode)
1182 {
1183 // Check if user has a valid token, otherwise make one. This has limitations.
1184 // One can always follow the standard procedure of calling alien-token-init then
1185 //   source /tmp/gclient_env_$UID in the current shell.
1186    if (!AliAnalysisGrid::CreateToken()) return NULL;
1187    AliAnalysisAlien *plugin = new AliAnalysisAlien();
1188 // Set the run mode (can be "full", "test", "offline", "submit" or "terminate")
1189    plugin->SetRunMode(plugin_mode);
1190    if (kPluginUseProductionMode) plugin->SetProductionMode();
1191    plugin->SetJobTag(kJobTag);
1192    plugin->SetNtestFiles(2);
1193 //   plugin->SetPreferedSE("ALICE::NIHAM::File");
1194 // Set versions of used packages
1195    plugin->SetAPIVersion("V1.1x");
1196    //   plugin->SetAPIVersion("V1.0x");
1197 //   plugin->SetAPIVersion("V2.4");
1198    plugin->SetROOTVersion(kPluginRootVersion);
1199    plugin->SetAliROOTVersion(kPluginAliRootVersion);
1200 // Declare input data to be processed.
1201 // Method 1: Create automatically XML collections using alien 'find' command.
1202 // Define production directory LFN
1203    plugin->SetGridDataDir(kGridDatadir.Data());
1204 // Set data search pattern
1205    if (iAODanalysis) plugin->SetDataPattern(" *AliAOD.root");
1206    else              plugin->SetDataPattern(Form(" %s/*/*ESD.tag.root",kGridPassPattern.Data()));
1207 // ...then add run numbers to be considered
1208 //   plugin->SetRunRange(kGridRunRange[0], kGridRunRange[1]);
1209    for (Int_t i=kGridRunRange[0]; i<=kGridRunRange[1]; i++) {
1210      Printf("AnalysisTrainPWG4Jets Adding run number %s", Form(kGridRunPattern.Data(),i));
1211      plugin->AddRunNumber(Form(kGridRunPattern.Data(),i));
1212    }   
1213
1214    if(kGridLocalRunList.Length()>0){
1215      ifstream in1;
1216      in1.open(kGridLocalRunList.Data());
1217      int iRun;
1218      char c;
1219      char cLine[250];
1220      while(!in1.eof()){
1221        c = in1.get();
1222        if ( (c >= '0') && (c <= '9') )
1223          {
1224            in1.putback (c);
1225            in1>>iRun;
1226            Printf("AnalysisTrainPWG4Jets Adding run number from File %s", Form(kGridRunPattern.Data(),iRun));
1227            plugin->AddRunNumber(Form(kGridRunPattern.Data(),iRun));
1228        }
1229      else
1230        {
1231          in1.putback (c);
1232          in1.getline(cLine,250);
1233          Printf("AnalysisTrainPWG4Jets Skipping run number from File %s", cLine);
1234        }
1235      }
1236    }
1237
1238 // Method 2: Declare existing data files (raw collections, xml collections, root file)
1239 // If no path mentioned data is supposed to be in the work directory (see SetGridWorkingDir())
1240 // XML collections added via this method can be combined with the first method if
1241 // the content is compatible (using or not tags)
1242 //   plugin->AddDataFile("tag.xml");
1243 //   plugin->AddDataFile("/alice/data/2008/LHC08c/000057657/raw/Run57657.Merged.RAW.tag.root");
1244 // Define alien work directory where all files will be copied. Relative to alien $HOME.
1245    if (iAODanalysis) plugin->SetGridWorkingDir("analysisAOD");
1246    else              plugin->SetGridWorkingDir("analysisESD");
1247    // Declare alien output directory. Relative to working directory.
1248    if (!kGridOutdir.Length()) kGridOutdir = Form("output_%s",kTrainName.Data());
1249    plugin->SetGridOutputDir(kGridOutdir);
1250
1251    // Add external packages
1252    if (iJETAN||iDIJETAN) {
1253       plugin->AddExternalPackage("boost::v1_38_0");
1254       plugin->AddExternalPackage("cgal::v3.3.1");
1255       plugin->AddExternalPackage("fastjet::v2.4.0");
1256    }   
1257
1258
1259    // set extra libs before par file compilation
1260    anaLibs += kGridExtraFiles;
1261    anaLibs     = anaLibs.Strip();   
1262    Printf("anaLibs %s",anaLibs.Data());
1263    Printf("anaLibsExtra %s",anaLibsExtra.Data());
1264
1265    if (anaLibs.Length())          plugin->SetAdditionalLibs(anaLibs.Data());
1266    if (anaLibsExtra.Length())     plugin->SetAdditionalRootLibs(anaLibsExtra.Data());
1267
1268    TString ana_sources = "";
1269    TString ana_add = "";
1270    if (kUsePAR && anaPars.Length()) {
1271       printf("%s\n", anaPars.Data());
1272       TObjArray *arr;
1273       TObjString *objstr;
1274       arr = anaPars.Tokenize(" ");
1275       TIter next(arr);
1276       while ((objstr=(TObjString*)next())) plugin->EnablePackage(objstr->GetString());
1277       delete arr;
1278    } 
1279    
1280 // Declare the analysis source files names separated by blancs. To be compiled runtime
1281 // using ACLiC on the worker nodes.
1282    ana_sources = anaSources.Strip();
1283 // Declare all libraries (other than the default ones for the framework. These will be
1284 // loaded by the generated analysis macro. Add all extra files (task .cxx/.h) here.
1285
1286    if (ana_sources.Length()) plugin->SetAnalysisSource(ana_sources);
1287    plugin->SetExecutableCommand(kPluginExecutableCommand.Data());  
1288 // Declare the output file names separated by blancs.
1289 // (can be like: file.root or file.root@ALICE::Niham::File)
1290    plugin->SetDefaultOutputs();
1291    plugin->SetMergeExcludes(kGridMergeExclude);
1292    plugin->SetMaxMergeFiles(kGridMaxMergeFiles);
1293    plugin->SetNrunsPerMaster(kGridRunsPerMaster);
1294 // Optionally define the files to be archived.
1295 //   plugin->SetOutputArchive("log_archive.zip:stdout,stderr@ALICE::NIHAM::File root_archive.zip:AliAOD.root,AOD.tag.root@ALICE::NIHAM::File");
1296    
1297    
1298    // Put default output files to archive
1299    TString listhists = "";
1300    TString listaods  = "";
1301    AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
1302    TIter next(mgr->GetOutputs());
1303    AliAnalysisDataContainer *output;
1304    while ((output=(AliAnalysisDataContainer*)next())) {
1305       const char *filename = output->GetFileName();
1306       if (!(strcmp(filename, "default"))) {
1307         if (!mgr->GetOutputEventHandler()) continue;
1308          filename = mgr->GetOutputEventHandler()->GetOutputFileName();
1309          if (listaods.Length()) listaods += " ";
1310          listaods += filename;
1311       } else {
1312         if(!listhists.Contains(filename)){
1313           if (listhists.Length()) listhists += " ";
1314           listhists += filename;
1315         }
1316       }
1317    }
1318
1319    if(kUseSysInfo>0){
1320      if (listhists.Length()) listhists += " ";
1321      listhists += "syswatch.root";
1322    }
1323
1324    if(kIsMC){
1325      if (listaods.Length()) listaods += " ";
1326      listaods += "pyxsec_hists.root";
1327    }
1328
1329
1330    if (mgr->GetExtraFiles().Length()) {
1331      if (listaods.Length()) listaods += " ";
1332      listaods += mgr->GetExtraFiles();
1333    }
1334
1335    // if we do not fill the aod we do not need to store it
1336    kGridMergeExclude = listaods;
1337    
1338    if(!kFillAOD){
1339      listaods="";
1340      plugin->SetDefaultOutputs(kFALSE);
1341      plugin->SetOutputFiles(listhists.Data());
1342    }
1343
1344
1345    listaods.ReplaceAll(" ", ",");
1346    listhists.ReplaceAll(" ", ",");
1347    if (listhists.Length()) listhists = Form("hist_archive.zip:%s@%s", listhists.Data(), kGridOutputStorages.Data());;
1348    if (listaods.Length())  listaods  = Form("aod_archive.zip:%s@%s", listaods.Data(), kGridOutputStorages.Data());;
1349
1350    if (!listhists.Length() && !listaods.Length()) {
1351       ::Fatal("AnalysisTrainPWG4Jets", "No task output !");
1352    }
1353
1354
1355
1356    TString outputArchive = "log_archive.zip:stdout,stderr@ALICE::FZK::SE,ALICE::GSI::SE";
1357    if(kUseSysInfo>0)outputArchive = "log_archive.zip:stdout,stderr,syswatch.log@ALICE::FZK::SE,ALICE::GSI::SE";
1358    if (listaods.Length()) {
1359       outputArchive += " ";
1360       outputArchive += listaods;
1361    }   
1362    if (listhists.Length()) {
1363       outputArchive += " ";
1364       outputArchive += listhists;
1365    }   
1366    plugin->SetOutputArchive(outputArchive);
1367 // Optionally set a name for the generated analysis macro (default MyAnalysis.C)
1368    plugin->SetAnalysisMacro(Form("%s.C", kTrainName.Data()));
1369 // Optionally set maximum number of input files/subjob (default 100, put 0 to ignore)
1370    plugin->SetSplitMaxInputFileNumber(kGridFilesPerJob);
1371 // Optionally set number of failed jobs that will trigger killing waiting sub-jobs.
1372 //   plugin->SetMaxInitFailed(5);
1373 // Optionally resubmit threshold.
1374 //   plugin->SetMasterResubmitThreshold(90);
1375 // Optionally set time to live (default 30000 sec)
1376    plugin->SetTTL(30000);
1377 // Optionally set input format (default xml-single)
1378    plugin->SetInputFormat("xml-single");
1379 // Optionally modify the name of the generated JDL (default analysis.jdl)
1380    plugin->SetJDLName(Form("%s.jdl", kTrainName.Data()));
1381 // Optionally modify the executable name (default analysis.sh)
1382    plugin->SetExecutable(Form("%s.sh", kTrainName.Data()));
1383 // Optionally modify job price (default 1)
1384    plugin->SetPrice(1);      
1385 // Optionally modify split mode (default 'se')    
1386    plugin->SetSplitMode("se");
1387    return plugin;
1388 }
1389
1390 //______________________________________________________________________________
1391 void WriteConfig()
1392 {
1393 // Write train configuration in a file. The file name has the format:
1394 // train_[trainName]_ddMonthyyyy_time.C
1395    if (kUseDate) {
1396       gSystem->Exec("date +%d%b%Y_%Hh%M > date.tmp");
1397       ifstream fdate("date.tmp");
1398       if (!fdate.is_open()) {
1399          ::Error("AnalysisTrainPWG4Jets.C::Export","Could not generate file name");
1400          return;
1401       }
1402       const char date[64];
1403       fdate.getline(date,64);
1404       fdate.close();
1405       gSystem->Exec("rm date.tmp");
1406       kTrainName = Form("train_%s_%s", kTrainName.Data(), date);
1407    } else {
1408       kTrainName = Form("train_%s", kTrainName.Data());
1409    }   
1410    TString cdir = gSystem->WorkingDirectory();
1411    gSystem->MakeDirectory(kTrainName);
1412    gSystem->ChangeDirectory(kTrainName);
1413    ofstream out;
1414    out.open(Form("%sConfig.C",kTrainName.Data()), ios::out); 
1415    if (out.bad()) {
1416       ::Error("AnalysisTrainPWG4Jets.C::Export", "Cannot open ConfigTrain.C for writing");
1417       return;
1418    }
1419    out << "{" << endl;
1420    out << "   kTrainName      = " << "\"" << kTrainName.Data() << "\";" << endl;
1421    out << "   kProofCluster   = " << "\"" << kProofCluster.Data() << "\";" << endl;
1422    out << "   kProofUseAFPAR        = " << kProofUseAFPAR << ";" << endl;
1423    if (kProofUseAFPAR) 
1424       out << "   kProofAFversion       = " << kProofAFversion.Data() << ";" << endl;
1425    out << "   kProofDataSet   = " << "\"" << kProofDataSet.Data() << "\";" << endl;
1426    out << "   kPluginUse       = " << kPluginUse << ";" << endl;
1427    out << "   kUsePAR          = " << kUsePAR << ";" << endl;
1428    out << "   kUseCPAR         = " << kUseCPAR << ";" << endl;
1429    out << "   kPluginRootVersion    = " << "\"" << kPluginRootVersion.Data() << "\";" << endl;
1430    out << "   kPluginAliRootVersion = " << "\"" << kPluginAliRootVersion.Data() << "\";" << endl;
1431    out << "   kGridDatadir   = " << "\"" << kGridDatadir.Data() << "\";" << endl;
1432    if (!kGridOutdir.Length()) kGridOutdir = Form("output_%s",kTrainName.Data());
1433    out << "   kGridOutdir    = " << "\"" << kGridOutdir.Data() << "\";" << endl;
1434    out << "   kGridMaxMergeFiles   = " << kGridMaxMergeFiles << ";" << endl;
1435    out << "   kGridMergeExclude    = " << "\"" << kGridMergeExclude.Data() << "\";" << endl;
1436    out << "   kGridRunsPerMaster  = " << kGridRunsPerMaster << ";" << endl;
1437    out << "   kGridFilesPerJob    = " << kGridFilesPerJob << ";" << endl;
1438    out << "   kGridRunRange[0]    = " << kGridRunRange[0] << ";" << endl;
1439    out << "   kGridRunRange[1]    = " << kGridRunRange[1] << ";" << endl;
1440    out << "   kUseDebug          = " << kUseDebug << ";" << endl;
1441    out << "   kUseMC           = " << kUseMC << ";" << endl;
1442    out << "   kUseESDTags         = " << kUseESDTags << ";" << endl;
1443    out << "   kUseKinefilter      = " << kUseKinefilter << ";" << endl;
1444    out << "   kUseTR           = " << kUseTR << ";" << endl;
1445    out << "   kUseAODTags      = " << kUseAODTags << ";" << endl;
1446    out << "   kSaveTrain       = " << "kFALSE;" << endl << endl;
1447    out << "   // Analysis modules" << endl;
1448    out << "   iAODanalysis    = " << iAODanalysis << ";" << endl;
1449    out << "   iAODhandler     = " << iAODhandler << ";" << endl;
1450    out << "   iESDfilter      = " << iESDfilter << ";" << endl;
1451    out << "   iJETAN          = " << iJETAN << ";" << endl;
1452    out << "// Configuration fot the wagons" << endl;
1453    out << "}" << endl;
1454    ::Info("AnalysisTrainPWG4Jets.C::WriteConfig", "Train configuration wrote to file %s", Form("config_%s.C", kTrainName.Data()));
1455    gSystem->ChangeDirectory(cdir);
1456 }   
1457
1458 //______________________________________________________________________________
1459 Bool_t LoadConfig(const char *filename)
1460 {
1461 // Read train configuration from file
1462    if (gSystem->AccessPathName(filename)) {
1463       ::Error("AnalysisTrainPWG4Jets.C::LoadConfig", "Config file name not found");
1464       return kFALSE;
1465    }   
1466    gROOT->ProcessLine(Form(".x %s", filename));
1467    ::Info("AnalysisTrainPWG4Jets.C::LoadConfig", "Train configuration loaded from file %s", filename);
1468    return kTRUE;
1469 }
1470
1471 Bool_t PatchJDL(){
1472   Printf(">>> Patching JDL");
1473   AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
1474   AliAnalysisAlien*    gridHandler = (AliAnalysisAlien*)mgr->GetGridHandler();
1475   TGridJDL *jdl = gridHandler->GetGridJDL();
1476   if(iJETAN)jdl->AddToPackages("fastjet","v2.4.0");
1477   gridHandler->WriteJDL(kFALSE);
1478   Printf("<<< Patching JDL");
1479   return kTRUE;
1480 }
1481
1482 Bool_t PatchAnalysisMacro(){
1483     Printf(">>> Patching AnalysisMacro");
1484     gSystem->Exec(Form("mv %s.C %s.C_tmp",kTrainName.Data(),kTrainName.Data()));
1485
1486   ifstream in1; 
1487   in1.open(Form("%s.C_tmp", kTrainName.Data()));
1488   char cLine[250];
1489   TString st;
1490   while(in1.getline(cLine,250)){
1491     st += cLine;
1492     st += "\n";
1493   }
1494   Int_t index;
1495   index = st.Index("gSystem->Load(\"libPhysics\");");
1496   index += strlen("gSystem->Load(\"libPhysics\");");
1497   if(iJETAN&&kUsePAR){
1498     TObjArray *arr;
1499     TObjString *objstr;
1500     arr = anaLibs.Tokenize(" ");
1501     TIter next(arr);
1502     TString add = "";
1503     add += "\n\n // added by CKB \n";
1504     while ((objstr=(TObjString*)next())){
1505       if(objstr->GetString().Contains("PWG3"))continue;
1506       if(objstr->GetString().EndsWith(".so"))add += Form("gSystem->Load(\"%s\");\n",objstr->GetString().Data());
1507     }
1508     delete arr; 
1509     add += "// BKC \n\n";
1510     st.Insert(index,add.Data());
1511   }
1512
1513   if(kUseDebug){
1514     st.Insert(index,"\n gROOT->ProcessLine(\".trace\"); // CKB \n");
1515   }
1516
1517   ofstream out;
1518   out.open(Form("%s.C", kTrainName.Data()));
1519   if (out.bad()) {
1520     return kFALSE;
1521   }
1522   out << st << endl;
1523   Printf("<<< Patching AnalysisMacro");
1524   return kTRUE;
1525
1526 }