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